' +
'
' +
'
' +
'
{{::document.DocumentType}}: {{::document.DocumentID}}
' +
'
{{::document.DocumentType}}: {{::document.DocumentID}} ({{"DOCUMENTSTATUS_READONLY" | translate}})
' +
'
' +
' ' +
' ' +
' ' +
' ' +
'
' +
'
' +
'
' +
'
{{::document.DocumentType}}: {{::document.DocumentID}}
' +
'
{{::document.DocumentType}}: {{::document.DocumentID}} ({{"DOCUMENTSTATUS_READONLY" | translate}})
' +
'
' +
' ' +
'
' +
'
' +
'
' +
'
',
replace: true,
transclude: true,
scope: {
document: "=document",
containerid: "=containerid",
ViewMode: '=viewMode',
CurrentWorkflowStatus: '=currentWorkflowStatus',
CurrentWorkflow: '=currentWorkflow',
canMinimize: '=canMinimize',
canMaximize: '=canMaximize',
canClose: '=canClose',
displayMode: '=displayMode'
},
link: function (scope, element, attributes) {
scope.windowState = "normal";
},
controller: ['$scope', '$element', function ($scope, $element) {
var normalState = {};
var positionState = null;
var sizeState = null;
$scope.windowId = $scope.containerid + "_wmWindow_" + $scope.document.DocumentID;
$scope.$on("viewer-window-manager-window-resized", function (event, args) {
if (args.windowId === $scope.windowId && $scope.windowState !== args.windowState) {
$timeout(function () {
$scope.windowState = args.windowState;
});
}
});
$scope.setDocumentFocus = function (windowId) {
$scope.IsFocused = true;
$rootScope.$broadcast("viewer-window-manager-window-focused", {
windowId: windowId,
documentId: $scope.document.DocumentID
});
};
$scope.$on("viewer-window-manager-window-focused", function (event, args) {
if (args.windowId === $scope.windowId || $scope.containerid + "_wmWindow_" + args.windowId === $scope.windowId) {
$scope.IsFocused = true;
} else {
$scope.IsFocused = false;
}
});
//#region minimize, maximize and Restore
$scope.maximize = function () {
//Store the position and the size state
normalState = {
x: parseInt($("#" + $scope.windowId).css('left'), 10),
y: parseInt($("#" + $scope.windowId).css('top'), 10),
width: parseInt($("#" + $scope.windowId).css('width'), 10),
height: parseInt($("#" + $scope.windowId).css('height'), 10),
z: $("#" + $scope.windowId).css('z-index')
};
var containerWidth = $("#" + $scope.containerid).width();
var containerHeight = $("#" + $scope.containerid).height() - $("#" + $scope.containerid + " .minimizedWindowBar").height();
var windowWidth = containerWidth;
var windowHeight = containerHeight;
$("#" + $scope.windowId).addClass('maximizing');
$("#" + $scope.windowId).css({
height: windowHeight,
width: windowWidth,
top: 0,
left: 0,
});
$("#" + $scope.windowId).addClass('maximized');
$scope.windowState = "maximized";
setTimeout(function () {
$rootScope.$broadcast("viewer-window-manager-window-resized", {
windowId: $scope.windowId,
document: $scope.document,
windowState: "maximized"
});
$rootScope.$broadcast("viewer-window-manager-window-maximized", {
windowId: $scope.windowId,
document: $scope.document
});
}, 500);
};
$scope.restore = function () {
if ($scope.displayMode === "maximized") {
$scope.maximize();
} else {
//add animation class
$timeout(function () {
//move and resize to previous state
$("#" + $scope.windowId).addClass('restoring');
$("#" + $scope.windowId).removeClass('maximized');
//move and resize to prior state
$("#" + $scope.windowId).css({
height: normalState.height,
width: normalState.width,
top: normalState.y,
left: normalState.x,
zIndex: normalState.z
});
//remove animation class
$timeout(function () {
$("#" + $scope.windowId).removeClass('restoring');
$rootScope.$broadcast("viewer-window-manager-window-resized", {
windowId: $scope.windowId,
document: $scope.document,
windowState: "normal"
});
}, 10);
$scope.windowState = "normal";
}, 10);
}
$rootScope.$broadcast("viewer-window-manager-window-restored", {
windowId: $scope.windowId,
document: $scope.document
});
};
$scope.minimize = function () {
//Store the position and the size state
normalState = {
x: parseInt($("#" + $scope.windowId).css('left'), 10),
y: parseInt($("#" + $scope.windowId).css('top'), 10),
width: parseInt($("#" + $scope.windowId).css('width'), 10),
height: parseInt($("#" + $scope.windowId).css('height'), 10),
z: $("#" + $scope.windowId).css('z-index')
};
$("#" + $scope.windowId).addClass('minimized');
$rootScope.$broadcast("viewer-window-manager-window-minimized", {
windowId: $scope.windowId,
document: $scope.document,
normalState: normalState,
title: $scope.document.DocumentType + ": " + $scope.document.DocumentID
});
};
function toggleMaximizedState() {
if ($scope.windowState === "maximized") {
$scope.restore();
} else {
$scope.maximize();
}
};
//#endregion
//#region dragging
var getEventCoords = function (e) {
var moveRef = e;
if (e.changedTouches && e.changedTouches.length === 1) {
moveRef = e.changedTouches[0];
}
if (e.originalEvent.changedTouches && e.originalEvent.changedTouches.length === 1) {
moveRef = e.originalEvent.changedTouches[0];
}
return moveRef;
}
var IsTouch = function (e) {
if (e.changedTouches && e.changedTouches.length === 1) {
return true;
}
if (e.originalEvent.changedTouches && e.originalEvent.changedTouches.length === 1) {
return true;
}
return false;
}
//it just makes a postion calculation from the current positon reference passed
var calculatePos = function (ref) {
var winX = parseInt($("#" + $scope.windowId).css('left'), 10);
var winY = parseInt($("#" + $scope.windowId).css('top'), 10);
return {
x: ref.x - winX,
y: ref.y - winY
};
};
//Execute when user moves the mouse after title is clicked
var dragWindow = function (e) {
var moveRef = getEventCoords(e);
if (positionState) {
var x = moveRef.pageX - positionState.x;
var y = moveRef.pageY - positionState.y;
var maxX = parseInt($("#" + $scope.containerid).offsetWidth || $("#" + $scope.containerid).innerWidth, 10) || $("#" + $scope.containerid).width();
var maxY = parseInt($("#" + $scope.containerid).offsetHeight || $("#" + $scope.containerid).innerHeight, 10) || $("#" + $scope.containerid).height() - 45;
//don't allow window to go past the left/right limits
if ($("#" + $scope.windowId).width() + x > maxX) {
x = maxX - $("#" + $scope.windowId).width();
}
if (x < 0) {
x = 0;
}
//don't allow window to go past the top/bottom limits
if ($("#" + $scope.windowId).height() + y > maxY) {
y = maxY - $("#" + $scope.windowId).height();
}
if (y < 0) {
y = 0;
}
if (angular.isDefined(x)) { $("#" + $scope.windowId).css('left', x + 'px'); }
if (angular.isDefined(y)) { $("#" + $scope.windowId).css('top', y + 'px'); }
}
e.preventDefault();
};
//The user ends moving window when mouseup or touchends
var dragWindowEnds = function (e) {
if (positionState) {
$("#" + $scope.windowId).removeClass('moving');
positionState = null;
}
$("body").off("mousemove", dragWindow);
$("body").off("mouseup", dragWindowEnds);
$("body").off("touchmove", dragWindow);
$("body").off("touchend", dragWindowEnds);
$rootScope.$broadcast("viewer-window-manager-window-moved", {
windowId: $scope.windowId,
documentId: $scope.document.DocumentID
});
e.preventDefault();
};
var startMoving = function (e) {
var isTouch = IsTouch(e);
var moveRef = getEventCoords(e);
positionState = calculatePos({
x: moveRef.pageX,
y: moveRef.pageY
});
$("#" + $scope.windowId).addClass('moving');
if (isTouch) {
$("body").on("touchmove", dragWindow);
$("body").on("touchend", dragWindowEnds);
} else {
$("body").on("mousemove", dragWindow);
$("body").on("mouseup", dragWindowEnds);
}
e.preventDefault();
};
//#endregion dragging
//#region resizing
//it just makes a size calculation from the current positon reference passed
var calculateSize = function (ref) {
var winWidth = parseInt($("#" + $scope.windowId).css('width'), 10);
var winHeight = parseInt($("#" + $scope.windowId).css('height'), 10);
return {
width: winWidth - ref.width,
height: winHeight - ref.height
};
};
//Executed when touches or clicks in the resize button
var startResizing = function (e) {
var isTouch = IsTouch(e);
var moveRef = getEventCoords(e);
sizeState = calculateSize({
width: moveRef.pageX,
height: moveRef.pageY
});
$("#" + $scope.windowId).addClass('resizing');
if (isTouch) {
$("#" + $scope.containerid).on("touchmove", dragWindowCorner);
$("#" + $scope.containerid).on("touchend", dragWindowCornerEnds);
} else {
$("#" + $scope.containerid).on("mousemove", dragWindowCorner);
$("#" + $scope.containerid).on("mouseup", dragWindowCornerEnds);
}
e.preventDefault();
};
//Execute when user moves the pointer after resize button is clicked
var dragWindowCorner = function (e) {
var isTouch = IsTouch(e);
var moveRef = getEventCoords(e);
if (sizeState) {
$("#" + $scope.windowId).css('width', moveRef.pageX + sizeState.width + 'px');
$("#" + $scope.windowId).css('height', moveRef.pageY + sizeState.height + 'px');
}
e.preventDefault();
};
//The user ends moving the resize button when mouseup or touchends
var dragWindowCornerEnds = function (e) {
var isTouch = IsTouch(e);
var moveRef = getEventCoords(e);
if (sizeState) {
$("#" + $scope.windowId).removeClass('resizing');
sizeState = null;
}
$("#" + $scope.containerid).off("mousemove", dragWindowCorner);
$("#" + $scope.containerid).off("mouseup", dragWindowCornerEnds);
$("#" + $scope.containerid).off("touchmove", dragWindowCorner);
$("#" + $scope.containerid).off("touchend", dragWindowCornerEnds);
e.preventDefault();
$rootScope.$broadcast("viewer-window-manager-window-resized", {
windowId: $scope.windowId,
documentId: $scope.document.DocumentID,
windowState: $scope.windowState
});
};
//#endregion resizing
//#region closing
//This function is executed when close button is pushed
$scope.close = function () {
DocumentService.SaveChanges($scope.document).then(function () {
$scope.document.CurrentPage.PageSrc = null;
$scope.document.CurrentPage.ThumbNailSrc = null;
$scope.document.CurrentPage.ForceReload = true;
doClose();
}, function (failure) {
doClose();
});
};
function doClose() {
setTimeout(function () {
$("#" + $scope.windowId).addClass('closing');
setTimeout(function () {
$("#" + $scope.windowId).removeClass('closing');
$("#" + $scope.windowId).remove();
$rootScope.$broadcast("viewer-window-manager-window-closed", {
windowId: $scope.windowId,
documentId: $scope.document.DocumentID
});
}, 300);
}, 50);
}
//#endregion closing
//#region initialization and teardown
function bindEvents() {
$("#" + $scope.windowId + " .wmTitleBar").bind("mousedown", startMoving);
$("#" + $scope.windowId + " .wmTitleBar").bind("touchstart", startMoving);
$("#" + $scope.windowId + " .wmTitleBar").bind("dblclick", toggleMaximizedState);
$("#" + $scope.windowId + " .wmResize").bind("mousedown", startResizing);
$("#" + $scope.windowId + " .wmResize").bind("touchstart", startResizing);
}
function unbindEvents() {
$("#" + $scope.windowId + " .wmTitleBar").unbind("mousedown");
$("#" + $scope.windowId + " .wmTitleBar").unbind("touchstart");
$("#" + $scope.windowId + " .wmTitleBar").unbind("dblclick");
$("#" + $scope.windowId + " .wmResize").unbind("mousedown");
$("#" + $scope.windowId + " .wmResize").unbind("touchstart");
}
function init() {
//To avoid adding transition listeners we remove tha class after some time
setTimeout(function () {
$("#" + $scope.windowId).addClass('active');
$("#" + $scope.windowId).addClass('opening');
if (!$(".device-xs").is(":visible")) {
bindEvents();
}
setTimeout(function () {
$("#" + $scope.windowId).removeClass('opening');
$rootScope.$broadcast("viewer-window-manager-window-opened", {
windowId: $scope.windowId,
documentId: $scope.document.DocumentID
});
}, 400);
}, 50);
}
init();
$scope.$on("destroy", function () {
//unbind event handlers
if (!$(".device-xs").is(":visible")) {
unbindEvents();
}
$("#" + $scope.windowId).unbind("touchmove");
$("#" + $scope.windowId).unbind("touchend");
$("#" + $scope.windowId).unbind("mousemove");
$("#" + $scope.windowId).unbind("mouseup");
$("#" + $scope.containerid).off("touchmove");
$("#" + $scope.containerid).off("touchend");
$("#" + $scope.containerid).off("mousemove");
$("#" + $scope.containerid).off("mouseup");
});
//#endregion initialization and teardown
}]
}
}
function attachmentWindow($rootScope, $timeout, $translate) {
return {
restrict: 'AE',
template: '
' +
'
' +
'
' +
'
' +
'
' +
' ' +
' ' +
' ' +
' ' +
'
' +
'
' +
'
' +
'
' +
'
' +
' ' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
',
replace: true,
transclude: true,
scope: {
containerid: "=containerid",
focusedDocumentId: "=focusedDocumentId",
document: "=document",
displayMode: "=displayMode"
},
link: function (scope, element, attributes) {
scope.canMinimize = angular.isDefined(attributes.canMinimize) ? (attributes.canMinimize === 'true') : true;
scope.canMaximize = angular.isDefined(attributes.canMaximize) ? (attributes.canMaximize === 'true') : true;
scope.canClose = angular.isDefined(attributes.canClose) ? (attributes.canClose === 'true') : false;
scope.displayMode = "cascade";
scope.windowState = "normal";
},
controller: ['$scope', '$element', function ($scope, $element) {
var normalState = {};
var positionState = null;
var sizeState = null;
$scope.windowId = $scope.containerid + "_wmWindow_attachmentwindow";
$scope.setAttachmentWindowFocus = function () {
$rootScope.$broadcast("viewer-window-manager-window-focused", {
windowId: $scope.windowId,
documentId: null
});
$scope.IsFocused = true;
};
$scope.$on("viewer-window-manager-window-focused", function (event, args) {
if (args.windowId === $scope.windowId) {
$scope.IsFocused = true;
} else {
$scope.IsFocused = false;
}
});
$scope.$on("viewer-window-manager-window-resized", function (event, args) {
if (args.windowId === $scope.windowId && $scope.windowState !== args.windowState) {
$timeout(function () {
$scope.windowState = args.windowState;
});
}
});
//$scope.$on("viewer-window-manager-change-display-mode", function (event, args) {
// $scope.displayMode = args.displayMode;
//});
//#region minimize, maximize and Restore
$scope.maximize = function () {
//Store the position and the size state
normalState = {
x: parseInt($("#" + $scope.windowId).css('left'), 10),
y: parseInt($("#" + $scope.windowId).css('top'), 10),
width: parseInt($("#" + $scope.windowId).css('width'), 10),
height: parseInt($("#" + $scope.windowId).css('height'), 10),
z: $("#" + $scope.windowId).css('z-index')
};
var containerWidth = $("#" + $scope.containerid).width();
var containerHeight = $("#" + $scope.containerid).height() - $("#" + $scope.containerid + " .minimizedWindowBar").height();
var windowWidth = containerWidth;
var windowHeight = containerHeight;
$("#" + $scope.windowId).addClass('maximizing');
$("#" + $scope.windowId).css({
height: windowHeight,
width: windowWidth,
top: 0,
left: 0,
});
$("#" + $scope.windowId).addClass('maximized');
$scope.windowState = "maximized";
setTimeout(function () {
$rootScope.$broadcast("viewer-window-manager-window-resized", {
windowId: $scope.windowId,
document: $scope.document,
windowState: "maximized"
});
$rootScope.$broadcast("viewer-window-manager-window-maximized", {
windowId: $scope.windowId,
document: $scope.document
});
}, 500);
};
$scope.restore = function () {
if ($scope.displayMode === "maximized") {
$scope.maximize();
} else {
//add animation class
$timeout(function () {
//move and resize to previous state
$("#" + $scope.windowId).addClass('restoring');
$("#" + $scope.windowId).removeClass('maximized');
//move and resize to prior state
$("#" + $scope.windowId).css({
height: normalState.height,
width: normalState.width,
top: normalState.y,
left: normalState.x,
zIndex: normalState.z
});
//remove animation class
$timeout(function () {
$("#" + $scope.windowId).removeClass('restoring');
$rootScope.$broadcast("viewer-window-manager-window-resized", {
windowId: $scope.windowId,
document: $scope.document,
windowState: "normal"
});
}, 10);
$scope.windowState = "normal";
}, 10);
}
$rootScope.$broadcast("viewer-window-manager-window-restored", {
windowId: $scope.windowId,
document: $scope.document
});
};
$scope.minimize = function () {
//Store the position and the size state
normalState = {
x: parseInt($("#" + $scope.windowId).css('left'), 10),
y: parseInt($("#" + $scope.windowId).css('top'), 10),
width: parseInt($("#" + $scope.windowId).css('width'), 10),
height: parseInt($("#" + $scope.windowId).css('height'), 10),
z: $("#" + $scope.windowId).css('z-index')
};
$("#" + $scope.windowId).addClass('minimized');
$rootScope.$broadcast("viewer-window-manager-window-minimized", {
windowId: $scope.windowId,
document: $scope.document,
normalState: normalState,
title: $translate.instant("ATTACHMENTVIEWER_WINDOWTITLE", { "documentId": $scope.focusedDocumentId })
});
};
function toggleMaximizedState() {
if ($scope.windowState === "maximized") {
$scope.restore();
} else {
$scope.maximize();
}
};
//#endregion
//#region dragging
//it just makes a postion calculation from the current positon reference passed
var calculatePos = function (ref) {
var winX = parseInt($("#" + $scope.windowId).css('left'), 10);
var winY = parseInt($("#" + $scope.windowId).css('top'), 10);
return {
x: ref.x - winX,
y: ref.y - winY
};
};
//Execute when user moves the mouse after title is clicked
var dragWindow = function (e) {
var moveRef = (e.targetTouches && e.targetTouches.length === 1) ? e.targetTouches[0] : e;
if (positionState) {
var x = moveRef.pageX - positionState.x;
var y = moveRef.pageY - positionState.y;
var maxX = parseInt($("#" + $scope.containerid).offsetWidth || $("#" + $scope.containerid).innerWidth, 10) || $("#" + $scope.containerid).width();
var maxY = parseInt($("#" + $scope.containerid).offsetHeight || $("#" + $scope.containerid).innerHeight, 10) || $("#" + $scope.containerid).height() - 45;
//don't allow window to go past the left/right limits
if ($("#" + $scope.windowId).width() + x > maxX) {
x = maxX - $("#" + $scope.windowId).width();
}
if (x < 0) {
x = 0;
}
//don't allow window to go past the top/bottom limits
if ($("#" + $scope.windowId).height() + y > maxY) {
y = maxY - $("#" + $scope.windowId).height();
}
if (y < 0) {
y = 0;
}
if (angular.isDefined(x)) { $("#" + $scope.windowId).css('left', x + 'px'); }
if (angular.isDefined(y)) { $("#" + $scope.windowId).css('top', y + 'px'); }
}
e.preventDefault();
};
//The user ends moving window when mouseup or touchends
var dragWindowEnds = function (e) {
var isTouch = (e.targetTouches && e.targetTouches.length === 1);
if (positionState) {
$("#" + $scope.windowId).removeClass('moving');
positionState = null;
}
$("body").off("mousemove", dragWindow);
$("body").off("mouseup", dragWindowEnds);
$("body").off("touchmove", dragWindow);
$("body").off("touchend", dragWindowEnds);
$rootScope.$broadcast("viewer-window-manager-window-moved", {
windowId: $scope.windowId,
documentId: null
});
e.preventDefault();
};
var startMoving = function (e) {
var isTouch = (e.targetTouches && e.targetTouches.length === 1);
var moveRef = isTouch ? e.targetTouches[0] : e;
positionState = calculatePos({
x: moveRef.pageX,
y: moveRef.pageY
});
$("#" + $scope.windowId).addClass('moving');
if (isTouch) {
$("body").on("touchmove", dragWindow);
$("body").on("touchend", dragWindowEnds);
} else {
$("body").on("mousemove", dragWindow);
$("body").on("mouseup", dragWindowEnds);
}
$scope.setAttachmentWindowFocus();
e.preventDefault();
};
//#endregion dragging
//#region resizing
//it just makes a size calculation from the current positon reference passed
var calculateSize = function (ref) {
var winWidth = parseInt($("#" + $scope.windowId).css('width'), 10);
var winHeight = parseInt($("#" + $scope.windowId).css('height'), 10);
return {
width: winWidth - ref.width,
height: winHeight - ref.height
};
};
//Executed when touches or clicks in the resize button
var startResizing = function (e) {
var isTouch = (e.targetTouches && e.targetTouches.length === 1);
var moveRef = isTouch ? e.targetTouches[0] : e;
sizeState = calculateSize({
width: moveRef.pageX,
height: moveRef.pageY
});
$("#" + $scope.windowId).addClass('resizing');
if (isTouch) {
$("#" + $scope.containerid).on("touchmove", dragWindowCorner);
$("#" + $scope.containerid).on("touchend", dragWindowCornerEnds);
} else {
$("#" + $scope.containerid).on("mousemove", dragWindowCorner);
$("#" + $scope.containerid).on("mouseup", dragWindowCornerEnds);
}
e.preventDefault();
};
//Execute when user moves the pointer after resize button is clicked
var dragWindowCorner = function (e) {
var moveRef = (e.targetTouches && e.targetTouches.length === 1) ? e.targetTouches[0] : e;
if (sizeState) {
$("#" + $scope.windowId).css('width', moveRef.pageX + sizeState.width + 'px');
$("#" + $scope.windowId).css('height', moveRef.pageY + sizeState.height + 'px');
}
e.preventDefault();
};
//The user ends moving the resize button when mouseup or touchends
var dragWindowCornerEnds = function (e) {
var isTouch = (e.targetTouches && e.targetTouches.length === 1);
if (sizeState) {
$("#" + $scope.windowId).removeClass('resizing');
sizeState = null;
}
$("#" + $scope.containerid).off("mousemove", dragWindowCorner);
$("#" + $scope.containerid).off("mouseup", dragWindowCornerEnds);
$("#" + $scope.containerid).off("touchmove", dragWindowCorner);
$("#" + $scope.containerid).off("touchend", dragWindowCornerEnds);
e.preventDefault();
$rootScope.$broadcast("viewer-window-manager-window-resized", {
windowId: $scope.windowId,
documentId: null,
windowState: $scope.windowState
});
};
//#endregion resizing
//#region closing
//This function is executed when close button is pushed
$scope.close = function () {
setTimeout(function () {
$("#" + $scope.windowId).addClass('closing');
setTimeout(function () {
$("#" + $scope.windowId).removeClass('closing');
$("#" + $scope.windowId).remove();
$rootScope.$broadcast("attachmentviewer.close");
}, 300);
}, 50);
};
//#endregion closing
//#region initialization and teardown
function bindEvents() {
$("#" + $scope.windowId + " .wmTitleBar").bind("mousedown", startMoving);
$("#" + $scope.windowId + " .wmTitleBar").bind("touchstart", startMoving);
$("#" + $scope.windowId + " .wmTitleBar").bind("dblclick", toggleMaximizedState);
$("#" + $scope.windowId + " .wmResize").bind("mousedown", startResizing);
$("#" + $scope.windowId + " .wmResize").bind("touchstart", startResizing);
}
function unbindEvents() {
$("#" + $scope.windowId + " .wmTitleBar").unbind("mousedown");
$("#" + $scope.windowId + " .wmTitleBar").unbind("touchstart");
$("#" + $scope.windowId + " .wmTitleBar").unbind("dblclick");
$("#" + $scope.windowId + " .wmResize").unbind("mousedown");
$("#" + $scope.windowId + " .wmResize").unbind("touchstart");
}
function init() {
//To avoid adding transition listeners we remove tha class after some time
setTimeout(function () {
$("#" + $scope.windowId).addClass('active');
$("#" + $scope.windowId).addClass('opening');
if (!$(".device-xs").is(":visible")) {
bindEvents();
}
setTimeout(function () {
$("#" + $scope.windowId).removeClass('opening');
$rootScope.$broadcast("viewer-window-manager-window-opened", {
windowId: $scope.windowId,
documentId: null
});
$rootScope.$broadcast("viewer-window-manager-window-focused", {
windowId: $scope.windowId
});
}, 400);
}, 50);
}
init();
$scope.$on("destroy", function () {
//unbind event handlers
if (!$(".device-xs").is(":visible")) {
unbindEvents();
}
$("#" + $scope.windowId).unbind("touchmove");
$("#" + $scope.windowId).unbind("touchend");
$("#" + $scope.windowId).unbind("mousemove");
$("#" + $scope.windowId).unbind("mouseup");
$("#" + $scope.containerid).off("touchmove");
$("#" + $scope.containerid).off("touchend");
$("#" + $scope.containerid).off("mousemove");
$("#" + $scope.containerid).off("mouseup");
});
//#endregion initialization and teardown
}]
}
}
})();
(function () {
'use strict';
angular.module('CommonDirectives').directive('exportResults', ['$uibModal', '$translate', exportResults]);
function exportResults($uibModal, $translate) {
return {
restrict: 'A',
scope: {
DoExport: "&doExport",
},
compile: function (el) {
el.attr('title', $translate.instant("RESULTSTOOLBAR_EXPORTBUTTON_TITLE"));
},
controller: ['$scope', '$element', function ($scope, $element) {
//dialog model
$scope.DialogModel = {};
$scope.DialogModel.WhatToExport = "all";
$scope.DialogModel.IncludeHeaders = true;
$scope.clickingCallback = function () {
$scope.DialogModel.WhatToExport = "all";
$scope.DialogModel.IncludeHeaders = true;
var exportDialog = '' +
'' +
'
' +
'';
var modalInstance = $uibModal.open({
animation: true,
template: exportDialog,
size: "lg",
scope: $scope,
controller: ['$scope', '$uibModalInstance', function ($scope, $modalInstance) {
$scope.ContinueExport = function (options) {
$modalInstance.close();
$scope.DoExport({ "WhatToExport": options.WhatToExport, "IncludeHeaders": options.IncludeHeaders });
};
$scope.CancelExport = function () {
$modalInstance.close();
}
}]
});
};
$element.bind('click', $scope.clickingCallback);
//remove the event listener on scope destroy
$scope.$on('$destroy', function () {
//console.log("$destroy in exportResults")
$element.unbind();
});
}]
};
}
})();
(function () {
'use strict';
angular.module('Settings').directive('settingsPopup', ['$rootScope', '$translate', '$uibModal', 'LocalStorageService', 'PropertyService', 'DocumentInquiryService', '$timeout', 'growl', settingsPopupFn]);
function settingsPopupFn($rootScope, $translate, $uibModal, LocalStorageService, PropertyService, DocumentInquiryService, $timeout, growl) {
return {
restrict: 'AE',
scope: true,
controller: ['$rootScope', '$scope', '$element', function ($rootScope, $scope, $element) {
// ---
// PUBLIC PROPERTIES.
// ---
//#region PUBLIC PROPERTIES.
$scope.Settings = {};
$scope.sortablePropertiesConfig = {
animation: 150,
dataIdAttr: "propertyID",
group: 'property',
handle: '.grabHandle',
onSort: function (/** ngSortEvent */evt) {
var sortedIds = [];
//console.log(evt.model.prompt + " was moved from " + evt.oldIndex + "=>" + evt.newIndex);
$.each(evt.models, function (index) {
evt.models[index].position = index;
});
//re-sort
var sortedProps = evt.models.sort(function (a, b) {
var aPos = parseInt(a.position, 10);
var bPos = parseInt(b.position, 10);
return ((aPos < bPos) ? -1 : ((aPos > bPos) ? 1 : 0));
});
//save the changes
PropertyService.SaveOptionsChanges(sortedProps).then(function (newPropertyArray) {
$scope.AllProperties = newPropertyArray;
PropertyService.GetAllProperties().then(function (properties) {
$rootScope.MasterProperties = properties;
});
//wait a second until the current scope refresh is completed so the new width is available
$timeout(function () {
$rootScope.$broadcast("setting_changed", {
SettingName: LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER,
NewValue: $scope.Settings[LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER]
});
});
});
}
};
$scope.AllProperties = [];
$scope.AllQuickSearches = [];
$scope.DynamicUIViewerTabs = [];
//#endregion PUBLIC PROPERTIES.
// ---
// PUBLIC METHODS.
// ---
//#region PUBLIC METHODS.
$scope.movePropertyToTop = function (property) {
//console.log("movePropertyToTop");
var propertyId = property.propertyID;
var currentPosition = parseInt(property.position, 10);
//early escape if we're already at the top
if (currentPosition === 0) {
return;
}
//spin through properties and move this one to the top and all others down one
PropertyService.GetPropertiesByPosition().then(function (properties) {
var newPosition = 0, iPos;
for (iPos = 0; iPos < properties.length; iPos++) {
if (properties[iPos].propertyID === propertyId) {
properties[iPos].position = 0;
//console.log("moved " + properties[iPos].name + " to top");
} else {
properties[iPos].position = ++newPosition;
//console.log("moved " + properties[iPos].name + " down one to " + properties[iPos].position);
}
}
//re-sort
var sortedProps = properties.sort(function (a, b) {
var aPos = parseInt(a.position, 10);
var bPos = parseInt(b.position, 10);
return ((aPos < bPos) ? -1 : ((aPos > bPos) ? 1 : 0));
});
PropertyService.SaveOptionsChanges(sortedProps).then(function (newPropertyArray) {
$scope.AllProperties = newPropertyArray;
PropertyService.GetAllProperties().then(function (properties) {
$rootScope.MasterProperties = properties;
});
//wait a second until the current scope refresh is completed so the new width is available
$timeout(function () {
$rootScope.$broadcast("setting_changed", {
SettingName: LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER,
NewValue: $scope.Settings[LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER]
});
});
});
});
};
$scope.movePropertyUpOne = function (property) {
//console.log("movePropertyUpOne");
var currentPosition = parseInt(property.position, 10);
var previousPosition = currentPosition - 1;
//early escape if we're already at the top
if (previousPosition < 0) {
return;
}
//spin through properties and move this one down and the one below it up
$.each($scope.AllProperties, function (index) {
if ($scope.AllProperties[index].position == currentPosition) {
$scope.AllProperties[index].position = previousPosition;
} else if ($scope.AllProperties[index].position == previousPosition) {
$scope.AllProperties[index].position = currentPosition;
}
});
//re-sort
var sortedProps = $scope.AllProperties.sort(function (a, b) {
var aPos = parseInt(a.position, 10);
var bPos = parseInt(b.position, 10);
return ((aPos < bPos) ? -1 : ((aPos > bPos) ? 1 : 0));
});
//save the changes
PropertyService.SaveOptionsChanges(sortedProps).then(function (newPropertyArray) {
$scope.AllProperties = newPropertyArray;
PropertyService.GetAllProperties().then(function (properties) {
$rootScope.MasterProperties = properties;
});
//wait a second until the current scope refresh is completed so the new width is available
$timeout(function () {
$rootScope.$broadcast("setting_changed", {
SettingName: LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER,
NewValue: $scope.Settings[LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER]
});
});
});
};
$scope.movePropertyDownOne = function (property) {
//console.log("movePropertyDownOne");
var currentPosition = parseInt(property.position, 10);
var nextPosition = currentPosition + 1;
//early escape if we're already at the bottom
if (nextPosition > $scope.AllProperties.length) {
return;
}
//spin through properties and move this one down and the one below it up
$.each($scope.AllProperties, function (index) {
if ($scope.AllProperties[index].position == currentPosition) {
$scope.AllProperties[index].position = nextPosition;
} else if ($scope.AllProperties[index].position == nextPosition) {
$scope.AllProperties[index].position = currentPosition;
}
});
//re-sort
var sortedProps = $scope.AllProperties.sort(function (a, b) {
var aPos = parseInt(a.position, 10);
var bPos = parseInt(b.position, 10);
return ((aPos < bPos) ? -1 : ((aPos > bPos) ? 1 : 0));
});
//save the changes
PropertyService.SaveOptionsChanges(sortedProps).then(function (newPropertyArray) {
$scope.AllProperties = newPropertyArray;
PropertyService.GetAllProperties().then(function (properties) {
$rootScope.MasterProperties = properties;
});
//wait a second until the current scope refresh is completed so the new width is available
$timeout(function () {
$rootScope.$broadcast("setting_changed", {
SettingName: LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER,
NewValue: $scope.Settings[LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER]
});
});
});
};
$scope.movePropertyToBottom = function (property) {
var propertyId = property.propertyID;
var currentPosition = parseInt(property.position, 10);
//early escape if we're already at the bottom
if (currentPosition === $scope.AllProperties.length) {
return;
}
//spin through properties and move this one to the bottom and all others up one
PropertyService.GetPropertiesByPosition().then(function (properties) {
var newPosition = 0, iPos;
for (iPos = 0; iPos < properties.length; iPos++) {
if (properties[iPos].propertyID === propertyId) {
properties[iPos].position = properties.length;
//console.log("moved " + properties[iPos].name + " to bottom");
} else {
properties[iPos].position = ++newPosition;
//console.log("moved " + properties[iPos].name + " up one to " + properties[iPos].position);
}
}
//re-sort
var sortedProps = properties.sort(function (a, b) {
var aPos = parseInt(a.position, 10);
var bPos = parseInt(b.position, 10);
return ((aPos < bPos) ? -1 : ((aPos > bPos) ? 1 : 0));
});
PropertyService.SaveOptionsChanges(sortedProps).then(function (newPropertyArray) {
$scope.AllProperties = newPropertyArray;
PropertyService.GetAllProperties().then(function (properties) {
$rootScope.MasterProperties = properties;
});
//wait a second until the current scope refresh is completed so the new width is available
$timeout(function () {
$rootScope.$broadcast("setting_changed", {
SettingName: LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER,
NewValue: $scope.Settings[LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER]
});
});
});
});
};
$scope.UpdateSetting = function (SettingName) {
//console.log("setting " + SettingName + " to " + $scope.Settings[SettingName]);
if (SettingName === 'NG_TRANSLATE_LANG_KEY') {
//pascalprecht.translate already has a mechanism for saving to the localStorage
$rootScope.changeLanguage($scope.Settings[SettingName]);
} else if (SettingName === "InquiryDefaultSort" || SettingName === "WFDefaultSort") {
var sortValue = [{ "Level": 0, "ColumnName": $scope.Settings[SettingName], "SortOrder": 0 }];
LocalStorageService.SetProperty(SettingName, JSON.stringify(sortValue), true);
} else if (SettingName === "maxSuppDocs" && !angular.isDefined($scope.Settings[SettingName])) {
$scope.Settings[SettingName] = 5;
} else {
LocalStorageService.SetProperty(SettingName, $scope.Settings[SettingName], true);
}
//wait a second until the current scope refresh is completed so the new setting is available
$timeout(function () {
$rootScope.$broadcast("setting_changed", {
SettingName: SettingName,
NewValue: $scope.Settings[SettingName]
});
});
};
$scope.UpdateQuickSearchRunFirstSetting = function () {
//console.log("setting 'quickSearchRunFirst' to " + $scope.Settings['quickSearchRunFirst'].Name);
LocalStorageService.SetProperty('quickSearchRunFirst', $scope.Settings['quickSearchRunFirst'].CustomInquiryID);
};
$scope.UpdateSystemPropertiesVisibleArray = function (systemProperty) {
if (!$.isArray($scope.Settings.systemPropertiesVisibleArray)) {
$scope.Settings.systemPropertiesVisibleArray = [];
}
var idx = $scope.Settings.systemPropertiesVisibleArray.indexOf(systemProperty);
if (idx > -1) {
//currently selected, so remove
$scope.Settings.systemPropertiesVisibleArray.splice(idx, 1);
}
else {
// not selected, so add
$scope.Settings.systemPropertiesVisibleArray.push(systemProperty);
}
LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.SYSTEMPROPERTIESVISIBLEARRAY, $scope.Settings.systemPropertiesVisibleArray);
//wait a second until the current scope refresh is completed so the new width is available
$timeout(function () {
$rootScope.$broadcast("setting_changed", {
SettingName: LocalStorageService.PropertyKeyEnum.SYSTEMPROPERTIESVISIBLEARRAY,
NewValue: $scope.Settings.systemPropertiesVisibleArray
});
});
};
$scope.UpdateViewerTabsVisibleArray = function (tab) {
if (!$.isArray($scope.Settings.visible_viewer_sections)) {
$scope.Settings.visible_viewer_sections = LocalStorageService.GetProperty(LocalStorageService.PropertyKeyEnum.VISIBLE_VIEWER_SECTIONS).split(",");
}
var idx = $scope.Settings.visible_viewer_sections.indexOf(tab);
if (idx > -1) {
//currently selected, so remove
$scope.Settings.visible_viewer_sections.splice(idx, 1);
}
else {
// not selected, so add
$scope.Settings.visible_viewer_sections.push(tab);
}
LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.VISIBLE_VIEWER_SECTIONS, $scope.Settings.visible_viewer_sections);
//wait a second until the current scope refresh is completed so the new width is available
$timeout(function () {
$rootScope.$broadcast("visible_viewer_sections_changed", {
NewValue: $scope.Settings.visible_viewer_sections
});
});
};
$scope.UpdateWFSystemPropertiesVisibleArray = function (systemProperty) {
if (!$.isArray($scope.Settings.wfResultsPropertiesVisibleArray)) {
$scope.Settings.wfResultsPropertiesVisibleArray = [];
}
var idx = $scope.Settings.wfResultsPropertiesVisibleArray.indexOf(systemProperty);
if (idx > -1) {
//currently selected, so remove
$scope.Settings.wfResultsPropertiesVisibleArray.splice(idx, 1);
}
else {
// not selected, so add
$scope.Settings.wfResultsPropertiesVisibleArray.push(systemProperty);
}
LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.WFSYSTEMPROPERTIESVISIBLEARRAY, $scope.Settings.wfResultsPropertiesVisibleArray);
//wait a second until the current scope refresh is completed so the new width is available
$timeout(function () {
$rootScope.$broadcast("setting_changed", {
SettingName: LocalStorageService.PropertyKeyEnum.WFSYSTEMPROPERTIESVISIBLEARRAY,
NewValue: $scope.Settings.wfResultsPropertiesVisibleArray
});
});
};
$scope.Reload = function () {
window.location.reload(true);
};
$scope.ClearSettings = function () {
LocalStorageService.ClearSettings();
window.location.reload(true);
};
$scope.RebuildColumnOrder = function () {
LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER, []);
PropertyService.GetPropertiesByPosition().then(function (properties) {
$scope.AllProperties = properties;
PropertyService.GetAllProperties().then(function (properties) {
$rootScope.MasterProperties = properties;
});
//wait a second until the current scope refresh is completed so the new width is available
$timeout(function () {
$rootScope.$broadcast("setting_changed", {
SettingName: LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER,
NewValue: $scope.Settings[LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER]
});
});
});
};
$scope.ResetCache = function (which) {
var userSpecificSuffix = "|" + LocalStorageService.GetProperty(LocalStorageService.PropertyKeyEnum.LOGINID) + "|" + LocalStorageService.GetProperty(LocalStorageService.PropertyKeyEnum.SERVICEURL);
switch (which) {
case "QuickSearches":
LocalStorageService.ResetProperty(LocalStorageService.PropertyKeyEnum.QUICKSEARCHES + userSpecificSuffix);
break;
case "AdvancedSearches":
LocalStorageService.ResetProperty(LocalStorageService.PropertyKeyEnum.SAVEDSEARCHES + userSpecificSuffix);
break;
case "Workflows":
LocalStorageService.ResetProperty(LocalStorageService.PropertyKeyEnum.WORKFLOWS + userSpecificSuffix);
break;
case "TopLevelFolders":
LocalStorageService.ResetProperty(LocalStorageService.PropertyKeyEnum.TOPLEVELFOLDERS + userSpecificSuffix);
break;
case "DocumentTypes":
LocalStorageService.ResetProperty(LocalStorageService.PropertyKeyEnum.DOCUMENTTYPES + userSpecificSuffix);
break;
}
BootstrapDialog.alert({
title: $translate.instant("RESETCACHE_SUCCESS_TITLE"),// 'Cached selection successfully reset.',
message: $translate.instant("RESETCACHE_SUCCESS_MESSAGE"),// 'Changes will take place after next login.',
type: BootstrapDialog.TYPE_SUCCESS
});
};
$scope.ShowSettingsDialog = function () {
init();
var modalInstance = $uibModal.open({
animation: false,
templateUrl: "tpl.SettingsDialog.html",
size: "lg",
scope: $scope,
backdropClass: 'modalBackDrop',
controller: ['$scope', '$uibModalInstance', function ($scope, $modalInstance) {
$scope.CloseDialog = function () {
$modalInstance.close();
};
}]
});
};
//#endregion PUBLIC METHODS.
// ---
// SCOPE WATCHES
// ---
// ---
// PRIVATE FUNCTIONS
// ---
//#region PRIVATE FUNCTIONS
function init() {
//get stored key/value pairs
$.each(LocalStorageService.PropertyKeyEnum, function (index, key) {
if (key === "InquiryDefaultSort" || key === "WFDefaultSort") {
var setting = LocalStorageService.GetProperty(key);
//console.log("setting: " + setting);
$scope.Settings[key] = setting[0].ColumnName;
} else {
$scope.Settings[key] = LocalStorageService.GetProperty(key);
}
});
PropertyService.GetPropertiesByPosition()
.then(function (properties) {
$scope.AllProperties = properties;
PropertyService.GetMasterPropertiesList(true).then(function (response) {
$scope.MasterProperties = response;
var highestPropertyId = _.max($scope.MasterProperties, function (property) { return parseInt(property.propertyID, 10); }).propertyID;
//get existing Property Ids
var existingIds = _.pluck($scope.AllProperties, "propertyID");
var maxPosition = _.max($scope.AllProperties, function (property) { return parseInt(property.position, 10); }).position;
//get all Property Ids
var allIds = _.pluck($scope.MasterProperties, "propertyID");
//missing Ids
var missingIds = _.difference(allIds, existingIds);
if (missingIds.length > 0) {
//add each new property into the array
$.each(missingIds, function (pIndex, id) {
var newProperty = _.find($scope.MasterProperties, function (p) { return p.propertyID === id; });
newProperty.position = ++maxPosition;
$scope.AllProperties.push(newProperty);
});
//re-sort
var sortedProps = $scope.AllProperties.sort(function (a, b) {
var aPos = parseInt(a.position, 10);
var bPos = parseInt(b.position, 10);
return ((aPos < bPos) ? -1 : ((aPos > bPos) ? 1 : 0));
});
//save the changes
PropertyService.SaveOptionsChanges(sortedProps).then(function () {
growl.info(missingIds.length + " Properties Added to Column Order List", { ttl: 5000, disableCountDown: false });
});
}
});
});
//get quicksearches and find the runfirst quicksearch
DocumentInquiryService.CustomInquiries().then(function (quickSearches) {
//{ "CustomInquiryID": 0, "Name": "none" }
$scope.AllQuickSearches = [];
//$scope.AllQuickSearches.push({ "CustomInquiryID": "none", "Name": "None" });
$translate('QUICKSEARCHRUNFIRST_NONE').then(function (translation) {
$scope.AllQuickSearches.push({ "CustomInquiryID": "none", "Name": translation });
if (quickSearches) {
$.each(quickSearches, function (index, search) {
$scope.AllQuickSearches.push(search);
});
}
var quickSearchRunFirstID = String($scope.Settings["quickSearchRunFirst"]);
$.each($scope.AllQuickSearches, function (index, search) {
if (String(search.CustomInquiryID) === quickSearchRunFirstID) {
$scope.Settings["quickSearchRunFirst"] = search;
}
});
});
});
}
//#endregion PRIVATE FUNCTIONS
// ---
// INITIALIZE AND TEARDOWN
// ---
$element.bind('click', $scope.ShowSettingsDialog);
$scope.$on("$destroy", function () {
//console.log("$destroy in notesPopup")
$element.unbind();
$scope.Settings = {};
$scope.AllProperties = [];
$scope.AllQuickSearches = [];
$scope.DynamicUIViewerTabs = [];
});
}]
};
}
})();
(function () {
'use strict';
angular.module('SmartForms').service('SmartFormsAPIService', ['$http', '$q', 'SessionFactory', 'LocalStorageService', 'PropertyService', smartFormsAPIServiceFN]);
function smartFormsAPIServiceFN($http, $q, SessionFactory, LocalStorageService, PropertyService) {
// ---
// PRIVATE VARIABLES
// ---
var __controller = "";
var __headers = {
'dynamicUIDefinitionId': "",
'documentId': 0,
'lang': "en-US"
};
var __stateModel = null;
return ({
//Settings and State
SetController: function (controller) { __controller = controller; },
SetDynamicUIDefinitionId: function (dynamicUIId) { __headers.dynamicUIDefinitionId = dynamicUIId; },
SetDocumentId: function (documentId) { __headers.documentId = documentId; },
GetDocumentId: function () { return __headers.documentId; },
SetLanguageAndCulture: function (culture) { __headers.lang = culture; },
SetState: function (state) { __stateModel = state; },
GetDynamicUIViewerTabs: getDynamicUIViewerTabs,
GetClientTabSmartForms: getClientTabSmartForms,
GetViewerTabSmartForms: getViewerTabSmartForms,
GetDynamicUIClientTabs: getDynamicUIClientTabs,
GetDynamicUI: getDynamicUI,
//public Methods
GetDynamicUIConfig: getDynamicUIConfig,
MenuButtonClick: menuButtonClick,
LeaveRow: leaveRow,
EnterRow: enterRow,
GetTopLevelFolders: getTopLevelFolders,
GetDocumentTypes: getDocumentTypes,
GetMasterProperties: getMasterProperties,
RunRemoteLookup: runRemoteLookup,
Validate: validate,
LoadFromTemplate: loadFromTemplate,
AddNewRow: addNewRow,
RemoveRow: removeRow,
GetDetailPage: getDetailPage,
GetAttachments: getAttachments,
GetAttachableDocuments: getAttachableDocuments,
AddAttachments: addAttachments,
OnHeaderValueChanged: onHeaderValueChanged,
OnDetailValueChanged: onDetailValueChanged,
OnFooterValueChanged: onFooterValueChanged,
OnTotalsValueChanged: onTotalsValueChanged,
OnSaveTemplate: onSaveTemplate,
OnDeleteTemplate: onDeleteTemplate,
GetTemplates: getTemplates,
RunDocumentProcessingInquiry: runDocumentProcessingInquiry,
});
// ---
// PUBLIC METHODS
// ---
function runDocumentProcessingInquiry() {
var defer = $q.defer();
var ExecuteProcessingInquiryRequestModel = $.extend(true, {}, arguments[0], __stateModel.GetBaseRequestModel());
//override the current document id with the one in the request
var tempHeaders = $.extend({},__headers);
tempHeaders.documentId = ExecuteProcessingInquiryRequestModel.DocumentID;
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/ExecuteProcessingInquiry",
data: ExecuteProcessingInquiryRequestModel,
headers: tempHeaders,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function getAttachableDocuments() {
var defer = $q.defer();
var RunAttachmentInquiryRequestModel = $.extend(true, {}, arguments[0], __stateModel.GetBaseRequestModel());
var request = $http({
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + "/Attachment/GetAttachableDocumentsList",
data: RunAttachmentInquiryRequestModel,
headers: __headers,
}).success(function (response) {
defer.resolve(response);
}).error(function (response, status) {
defer.reject({ message: response.Message });
})
return defer.promise;
}
function addAttachments() {
var defer = $q.defer();
var AttachDocumentRequestModel = __stateModel.GetBaseRequestModel();
//var args = arguments[0];
AttachDocumentRequestModel.Attachments = arguments[0];
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/AddAttachments",
data: AttachDocumentRequestModel,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function getClientTabSmartForms(tabId) {
var defer = $q.defer();
var request = $http({
method: "get",
url: SessionFactory.GetServiceUrl() + "SmartForms/GetClientTabSmartForms?tabId=" + tabId
}).success(function (response) {
defer.resolve(response);
}).error(function (response, status) {
defer.reject({ message: "Error Loading SmartForms List for Current Client Tab" });
})
return defer.promise;
}
function getViewerTabSmartForms(tabId, documentId) {
var defer = $q.defer();
var request = $http({
method: "get",
url: SessionFactory.GetServiceUrl() + "SmartForms/GetViewerTabSmartForms?tabId=" + tabId + "&documentId=" + documentId
}).success(function (response) {
defer.resolve(response);
}).error(function (response, status) {
defer.reject({ message: "Error Loading SmartForms List for Current Viewer Tab" });
})
return defer.promise;
}
function getDynamicUIClientTabs() {
var defer = $q.defer();
var request = $http({
method: "get",
url: SessionFactory.GetServiceUrl() + "SmartForms/ClientTabs"
}).success(function (response) {
defer.resolve(response.tabs);
}).error(function (response, status) {
defer.reject({ message: "Error Loading DynamicUI Client Tabs" });
})
return defer.promise;
}
function getDynamicUIViewerTabs() {
var defer = $q.defer();
var request = $http({
method: "get",
url: SessionFactory.GetServiceUrl() + "SmartForms/ViewerTabs"
}).success(function (response) {
defer.resolve(response.tabs);
}).error(function (response, status) {
defer.reject({ message: "Error Loading DynamicUI Viewer Tabs" });
})
return defer.promise;
}
function getDynamicUI(dynamicUIDefinitionId) {
var defer = $q.defer();
var request = $http({
method: "get",
url: SessionFactory.GetServiceUrl() + "SmartForms/GetDynamicUI?dynamicUIId=" + dynamicUIDefinitionId
}).success(function (response) {
defer.resolve(response);
}).error(function (response, status) {
defer.reject({ message: "Error Loading DynamicUI Layout" });
})
return defer.promise;
}
function getDynamicUIConfig() {
var defer = $q.defer();
var payLoad = {};
payLoad.Settings = LocalStorageService.GetProperty(LocalStorageService.PropertyKeyEnum.SMARTFORMSSETTINGS);
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/GetSmartFormConfig",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function leaveRow() {
var defer = $q.defer();
var payLoad = __stateModel.GetBaseRequestModel();
payLoad.RowId = arguments[0];
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnDetailRowLeave",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function enterRow() {
var defer = $q.defer();
var payLoad = __stateModel.GetBaseRequestModel();
var args = arguments[0];
payLoad.RowId = args[0];
payLoad.PreviousRowId = args[1];
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnDetailRowEnter",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function menuButtonClick() {
var defer = $q.defer();
var commandName = arguments[0][0];
var addtlParams = arguments[0][1];
var attachments = arguments[0][2];
var menuButtonClickRequestModel = __stateModel.GetBaseRequestModel();
menuButtonClickRequestModel.CommandName = commandName;
menuButtonClickRequestModel.Attachments = attachments;
if (angular.isDefined(addtlParams) && addtlParams !== null) {
menuButtonClickRequestModel.AdditionalParameter = addtlParams;
}
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/MenuButtonClick",
data: menuButtonClickRequestModel,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function loadFromTemplate() {
var defer = $q.defer();
var templateId = arguments[0];
var payLoad = __stateModel.GetBaseRequestModel();
payLoad.TemplateId = templateId;
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnLoadFromTemplate",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function addNewRow() {
var defer = $q.defer();
var payLoad = __stateModel.GetBaseRequestModel();
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnAddRowButtonClicked",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function removeRow() {
var defer = $q.defer();
var selectedRowGuid = arguments[0];
var payLoad = __stateModel.GetBaseRequestModel();
payLoad.RowId = selectedRowGuid;
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnRemoveRowButtonClicked",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function getDetailPage() {
var defer = $q.defer();
var pageNumber = arguments[0];
var payLoad = __stateModel.GetBaseRequestModel();
payLoad.DetailPageNumber = pageNumber;
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/GetDetailPage",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function getTopLevelFolders() {
var defer = $q.defer();
//get folders
var topLevelFolders = SessionFactory.GetTopLevelFolders();
//remap into correct shape for dynamic UI
var dynamicUILookupValues = $.map(topLevelFolders, function (folder) {
return {
DisplayValue: folder.folderTitle,
Value: folder.folderID,
Value2: folder.folderCode
}
});
defer.resolve(dynamicUILookupValues);
return defer.promise;
}
function getDocumentTypes() {
var defer = $q.defer();
//get document types
var docTypes = SessionFactory.GetDocumentTypes();
//remap into correct shape for dynamic UI
var dynamicUILookupValues = $.map(docTypes, function (docType) {
return {
DisplayValue: docType.documentTypeTitle,
Value: docType.documentTypeID,
Value2: ""
}
});
defer.resolve(dynamicUILookupValues);
return defer.promise;
}
function getMasterProperties() {
var defer = $q.defer();
//get master properties
PropertyService.GetAllProperties().then(function (properties) {
//remap into correct shape for dynamic UI
var dynamicUILookupValues = $.map(properties, function (property) {
return {
DisplayValue: property.prompt,
Value: property.propertyID,
Value2: ""
}
});
defer.resolve(dynamicUILookupValues);
});
return defer.promise;
}
function getAttachments() {
var defer = $q.defer();
var payLoad = __stateModel.GetBaseRequestModel();
$http({
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/GetAttachmentList",
data: payLoad,
headers: __headers,
}).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function onHeaderValueChanged() {
var defer = $q.defer();
var payLoad = __stateModel.GetBaseRequestModel();
payLoad.ElementToChange = arguments[0];
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnHeaderValueChanged",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function onDetailValueChanged() {
var defer = $q.defer();
var payLoad = __stateModel.GetBaseRequestModel();
payLoad.ElementToChange = arguments[0];
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnDetailValueChanged",
data: payLoad,
headers: __headers
};
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function onFooterValueChanged() {
var defer = $q.defer();
var payLoad = __stateModel.GetBaseRequestModel();
payLoad.ElementToChange = arguments[0];
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnFooterValueChanged",
data: payLoad,
headers: __headers
};
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function onTotalsValueChanged() {
var defer = $q.defer();
var payLoad = __stateModel.GetBaseRequestModel();
payLoad.ElementToChange = arguments[0];
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnTotalsValueChanged",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function onSaveTemplate() {
var defer = $q.defer();
var payLoad = __stateModel.GetBaseRequestModel();
var args = arguments[0];
payLoad.TemplateId = args[0];
payLoad.TemplateName = args[1];
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnSaveTemplate",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function onDeleteTemplate() {
var defer = $q.defer();
var payLoad = __stateModel.GetBaseRequestModel();
payLoad.TemplateId = arguments[0];
var ajaxOpts = {
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/OnDeleteTemplate",
data: payLoad,
headers: __headers,
}
$http(ajaxOpts).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
function getTemplates() {
var defer = $q.defer();
$http({
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + __controller + "/GetTemplates",
data: {},
headers: __headers,
}).then(function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
});
return defer.promise;
}
// ---
// PRIVATE METHODS
// ---
function validate(groupKey, fieldId) {
var layout = __stateModel.GetLayout();
var values = __stateModel.GetValues();
var layoutField = null;
var valueSet = null;
if (groupKey == values.Header.SectionId) {
valueSet = _.find(values.Header.Values, function (v) { return v.DynamicUIFieldId == fieldId; });
layoutField = _.find(layout.Header.Layout, function (v) { return v.DynamicUIFieldId == fieldId; });
} else {
//find the new row if is in fact a row in the detail section
var existingRow = _.find(values.Details.Rows, function (r) { return r.RowId == groupKey; });
if (angular.isDefined(existingRow)) {
layoutField = _.find(layout.Details.Layout, function (v) { return v.DynamicUIFieldId == fieldId; });
valueSet = _.find(existingRow.Values, function (v) { return v.DynamicUIFieldId == fieldId; });
}
}
if (layoutField == null || valueSet == null) {
return;
}
if (valueSet.Text == "" || layoutField.SystemLookupId == 0) {
return;
}
if (layoutField.ControlType != "DynamicLookup" && layoutField.ControlType != "DynamicDropDown") {
return;
}
var LookupRequestModel = {};
LookupRequestModel.GlobalGroupKey = values.Header.Values[0].GroupKey;
LookupRequestModel.ControlType = layoutField.ControlType;
LookupRequestModel.SystemLookupId = layoutField.SystemLookupId;
LookupRequestModel.Text = valueSet.Text;
LookupRequestModel.Value = valueSet.Value;
LookupRequestModel.Value2 = valueSet.Value2;
LookupRequestModel.AssignedName = layoutField.AssignedName;
LookupRequestModel.GroupKey = valueSet.GroupKey;
LookupRequestModel.DynamicUIFieldId = layoutField.DynamicUIFieldId;
LookupRequestModel.page = -1;
LookupRequestModel.pageSize = 5;
LookupRequestModel.OrderByColumnName = "";
LookupRequestModel.OrderByAscending = true;
LookupRequestModel.LookupFilters = [];
//append existing values
LookupRequestModel.Values = [];
LookupRequestModel.Values = $.merge(LookupRequestModel.Values, values.Header.Values);
LookupRequestModel.Values = $.merge(LookupRequestModel.Values, values.Footer.Values);
LookupRequestModel.Values = $.merge(LookupRequestModel.Values, values.Totals.Values);
if (valueSet.GroupKey != layout.Header.SectionId && valueSet.GroupKey != layout.Footer.SectionId && valueSet.GroupKey != layout.Totals.SectionId) {
//if we're here, it's a row that we're updating, so load the values for that row, too
var changingRow = _.find(values.Details.Rows, function (r) { return r.RowId == valueSet.GroupKey; });
if (angular.isDefined(changingRow)) {
LookupRequestModel.Values = $.merge(LookupRequestModel.Values, changingRow.Values);
}
}
//leave this Epicor override false by default
LookupRequestModel.DisableAutoGlobalGroupLookup = false;
var request = $http({
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + "Lookup/Validate",
data: LookupRequestModel
}).success(function (response) {
valueSet.IsValid = response;
}).error(function (response, status) {
console.log("failure", response);
valueSet.IsValid = false;
});
}
function runRemoteLookup() {
var defer = $q.defer();
var layout = __stateModel.GetLayout();
var values = __stateModel.GetValues();
var args = arguments[0];
var layoutField = args[0];
var valueSet = args[1];
var page = args[2];
var orderByColumnName = args[3];
var orderByAscending = args[4];
var filters = args[5];
var LookupRequestModel = {};
LookupRequestModel.GlobalGroupKey = values.Header.Values[0].GroupKey;
LookupRequestModel.ControlType = layoutField.ControlType;
LookupRequestModel.SystemLookupId = layoutField.SystemLookupId;
LookupRequestModel.Text = valueSet.Text;
LookupRequestModel.Value = valueSet.Value;
LookupRequestModel.Value2 = valueSet.Value2;
LookupRequestModel.AssignedName = layoutField.AssignedName;
LookupRequestModel.GroupKey = valueSet.GroupKey;
LookupRequestModel.DynamicUIFieldId = layoutField.DynamicUIFieldId;
LookupRequestModel.page = angular.isDefined(page) ? page : -1;
LookupRequestModel.pageSize = 18;
if (LookupRequestModel.ControlType == "DynamicDropDown") {
//np paging from dropdowns, so set to 100
LookupRequestModel.pageSize = 100;
}
LookupRequestModel.OrderByColumnName = angular.isDefined(orderByColumnName) ? orderByColumnName : "";
LookupRequestModel.OrderByAscending = angular.isDefined(orderByAscending) ? orderByAscending : true;
LookupRequestModel.LookupFilters = angular.isDefined(filters) ? filters : [];
//append existing values
LookupRequestModel.Values = [];
LookupRequestModel.Values = $.merge(LookupRequestModel.Values, values.Header.Values);
LookupRequestModel.Values = $.merge(LookupRequestModel.Values, values.Footer.Values);
LookupRequestModel.Values = $.merge(LookupRequestModel.Values, values.Totals.Values);
if (valueSet.GroupKey != layout.Header.SectionId && valueSet.GroupKey != layout.Footer.SectionId && valueSet.GroupKey != layout.Totals.SectionId) {
//if we're here, it's a row that we're updating, so load the values for that row, too
var changingRow = _.find(values.Details.Rows, function (r) { return r.RowId == valueSet.GroupKey; });
if (angular.isDefined(changingRow)) {
LookupRequestModel.Values = $.merge(LookupRequestModel.Values, changingRow.Values);
}
}
//leave this Epicor override false by default
LookupRequestModel.DisableAutoGlobalGroupLookup = false;
var request = $http({
method: "post",
url: SessionFactory.GetSmartFormsServiceURL() + "Lookup/DoLookup",
data: LookupRequestModel
}).success(function (response) {
defer.resolve(response);
}).error(function (response, status) {
defer.reject(response);
});
return defer.promise;
}
}
})();
(function () {
'use strict';
angular.module("SmartForms").constant('SmartFormsConstants', {
DynamicControlType: {
BooleanEdit: "BooleanEdit",
DateEdit: "DateEdit",
DynamicDropDown: "DynamicDropDown",
DynamicLabel: "DynamicLabel",
DynamicLookup: "DynamicLookup",
NumericEdit: "NumericEdit",
TotalElement: "TotalElement"
}
});
angular.module("SmartForms").service("StateService", ['$rootScope', '$q', 'SmartFormsAPIService', 'DoubleLinkedList', 'SerialPromiseQueue', '$timeout', 'SmartFormsConstants', 'growl', 'SmartFormsState', 'ResponseMessageHandler', 'modalService', '$translate', stateService]);
function stateService($rootScope, $q, SmartFormsAPIService, DoubleLinkedList, SerialPromiseQueue, $timeout, SmartFormsConstants, growl, SmartFormsState, ResponseMessageHandler, modalService, $translate) {
var __stateModel = null;
var __unsavedChangesExist = false;
var __currentRowId = null;
var __currentSectionId = null;
var __queuedSectionIdToFocus = null;
var __apiQueue = null;
var __attachments = [];
var __templates = [];
var __lookupManagerHotkey = "F3";
var __rawResponseData = null;
var __currentDefinitionId = null;
var __activeElementId = "";
var __currentDetailPageIndex = 0;
var __currentAttachmentSectionId = -1; //default to header
var __saveMethod = null;
return ({
Initialize: initialize,
//Properties
GetState: getState,
GetCurrentState: getState,
ClearState: function () {
if (__stateModel === null) {
return;
}
__stateModel.Clear();
__unsavedChangesExist = false;
__currentRowId = null;
__currentSectionId = null;
__currentAttachmentSectionId = -1; //default to header
__attachments = [];
__activeElementId = "";
$rootScope.$broadcast("SMARTFORMS.ATTACHMENTS.CHANGED");
$rootScope.$broadcast("SMARTFORMS.STATE.CLEARED");
},
GetCurrentRowId: function () { return __currentRowId; },
//GetCurrentSectionId: function () { return __currentSectionId; },
GetCurrentAttachmentSectionId: function () { return __currentAttachmentSectionId; },
GetValueSet: getValueSet,
IsButtonEnabled: IsButtonEnabled,
IsButtonVisible: IsButtonVisible,
GetClientTabSmartForms: getClientTabSmartForms,
GetViewerTabSmartForms: getViewerTabSmartForms,
GetAttachments: function () { return __attachments; },
GetTemplates: function () { return __templates; },
RowHasAttachment: function (rowId) {
var hasAttachment = false;
$.each(__stateModel.GetValues().Details.Rows, function (rowIndex, row) {
if (row.RowId == rowId) {
var rowAttachment = _.find(__attachments, function (attachment) { return attachment.sectionId == (rowIndex + (__currentDetailPageIndex * 50)); });
if (angular.isDefined(rowAttachment)) {
hasAttachment = true;
return true;
}
}
});
return hasAttachment;
},
GetLookupManagerHotkey: function () { return __lookupManagerHotkey; },
HasUnsavedChanges: function () { return __unsavedChangesExist; },
GetCurrentDefinitionId: function () { return __currentDefinitionId; },
GetLookupOptions: getLookupOptions,
SetActiveElement: focusField,
GetActiveElement: function () {
return __activeElementId;
},
IsFieldDirty: isFieldDirty,
IsStateValid: isStateValid,
IsOkToSave: function () {
var defer = $q.defer();
if (isStateValid() === true) {
defer.resolve(true);
} else {
modalService.showModal({}, {
headerText: "",
bodyText: $translate.instant("VIEWERSTAMPHOST_INVALIDFIELDSFOUND")
}).then(function (result) {
defer.reject(result);
}, function (response) {
console.log(response);
defer.reject(response);
});
}
return defer.promise;
},
GetResponsePropertyByName: function (propertyName) {
if (__rawResponseData && __rawResponseData !== null) {
return __rawResponseData[propertyName];
}
},
IsInErrorState: function() {
return __stateModel.IsInErrorState;
},
GetInstanceId: function () {
return __stateModel.GetValues().SmartFormIInstanceId;
},
RegisterNewAttachments: registerNewAttachments,
RemoveAttachment: removeAttachment,
GetAttachableDocuments: getAttachableDocuments,
GetDocumentId: function () {
return SmartFormsAPIService.GetDocumentId();
},
SetSaveMethod: function (method) {
__saveMethod = method;
},
SaveState: function () {
//attempt to find the correct save method by using hard-coded values
if (!__saveMethod) {
switch (SmartFormsAPIService.GetController()) {
case "DistributionStamp":
__saveMethod = "tlSave";
break;
case "DocumentCreation":
__saveMethod = "btnPreview";
break;
case "DocumentPageCreation":
__saveMethod = "btnPreview";
break;
case "DocumentProcessing":
__saveMethod = "btnSave";
break;
}
}
var defer = $q.defer();
if (__saveMethod) {
var burnSetting = __stateModel.GetSetting("showBurnWarning"); //save burn warning setting
this.IsOkToSave().then(function () {
__stateModel.UpdateSetting("showBurnWarning", false); //disable burn warning
return menuButtonClick(__saveMethod, null, false, true);
}).then(function (response) {
console.log("SaveState response", response);
__stateModel.UpdateSetting("showBurnWarning", burnSetting); //reset burn warning value
if (response.data.IsSuccess === true) {
defer.resolve(response);
} else {
defer.reject(response);
}
});
} else {
this.ClearState();
defer.resolve();
}
return defer.promise;
},
//User Actions
MenuButtonClick: menuButtonClick,
ProcessCommand: menuButtonClick,
LoadFromTemplate: loadFromTemplate,
AddNewRow: addNewRow,
RemoveRow: removeRow,
GetDetailPage: getDetailPage,
OnFieldChanged: onFieldChanged,
OnSaveTemplate: onSaveTemplate,
OnDeleteTemplate: onDeleteTemplate,
UpdateBurnWarning: function (settingValue) {
__stateModel.UpdateSetting("showBurnWarning", settingValue);
},
UpdateCustomSetting: function (settingName, settingValue) {
__stateModel.UpdateSetting(settingName, settingValue);
},
GetSetting: function (settingName) {
if (__stateModel === null) {
return false;
}
return __stateModel.GetSetting(settingName);
},
RunDocumentProcessingInquiry: runDocumentProcessingInquiry,
OpenTab: openTab,
onOpenTab: onOpenTab,
OpenAttachmentViewer: function (sectionIndex) {
if (!angular.isDefined(sectionIndex) || sectionIndex === null) {
sectionIndex = -1;
}
__currentAttachmentSectionId = sectionIndex;
$rootScope.$broadcast("attachmentviewer.open", {
"SectionId": __currentAttachmentSectionId
});
},
//Focus Events
FocusFirstHeaderField: focusFirstHeaderField,
FocusFirstFieldInDetailSection: focusFirstFieldInDetailSection,
FocusFirstDetailRowField: focusFirstDetailRowField,
FocusFirstFooterField: focusFirstFooterField,
//FocusPrevious: focusPrevious,
//FocusNext: focusNext,
FocusLast: focusLast,
FocusSection: focusSection,
LeaveRow: leaveRow,
FocusField: focusField,
});
//#region Public Methods
function initialize(dynamicUIId, documentId, controller) {
if (dynamicUIId == null || controller == null) {
throw "StateService is missing a valid dynamicUIId and/or controller";
}
__currentDefinitionId = dynamicUIId;
//define queue
__apiQueue = new SerialPromiseQueue();
//set up API Service
SmartFormsAPIService.SetController(controller);
SmartFormsAPIService.SetDynamicUIDefinitionId(dynamicUIId);
SmartFormsAPIService.SetDocumentId(documentId);
SmartFormsAPIService.SetLanguageAndCulture($rootScope.CurrentCulture);
//clear call queue and execute GetDynamicUIConfig request immediately
__apiQueue.add(SmartFormsAPIService.GetDynamicUIConfig, [], initCallback, failCallback, "GetDynamicUIConfig");
//watch for locale changes
$rootScope.$on('$localeChangeSuccess', function () {
SmartFormsAPIService.SetLanguageAndCulture($rootScope.CurrentCulture);
});
}
//#region Callbacks
function initCallback(response) {
//console.log("initCallback: " + response.data.StateGuid);
__rawResponseData = response.data;
__unsavedChangesExist = false;
__stateModel = new SmartFormsState(response.data);
//Set the State in the SmartFormsAPIService
SmartFormsAPIService.SetState(__stateModel);
//Set the State in the ResponseMessageHandler service
ResponseMessageHandler.SetState(__stateModel);
//define the lookupmanager hotkey
__lookupManagerHotkey = response.data.LookupManagerHotkey;
//build double linked list for navigation
loadNavigationList();
//Get any attachments
__apiQueue.add(SmartFormsAPIService.GetAttachments, [], function (response) {
__attachments = response.data.Items;
$.each(__stateModel.GetValues().Details.Rows, function (rowIndex, row) {
__stateModel.GetValues().Details.Rows[rowIndex].HasAttachment = false;
var rowAttachment = _.find(__attachments, function (attachment) { return attachment.sectionId == (rowIndex + (__currentDetailPageIndex * 50)); });
if (angular.isDefined(rowAttachment)) {
__stateModel.GetValues().Details.Rows[rowIndex].HasAttachment = true;
}
});
}, function () { }, "GetAttachments");
//Get any Templates
__apiQueue.add(SmartFormsAPIService.GetTemplates, [], function (response) {
__templates = response.data;
}, failCallback, "GetTemplates");
$rootScope.$broadcast("SMARTFORMS.DEFINITION.LOADED", { "Layout": __stateModel.GetLayout(), "Values": __stateModel.GetValues() });
}
function successCallback(state, changedFieldData) {
__stateModel.UpdateStateValues(state, false, changedFieldData);
//build double linked list for navigation
loadNavigationList();
$rootScope.$broadcast("SMARTFORMS.STATE.UPDATED", { "NewState": __stateModel.GetValues(), "IsSuccess": true });
}
function failCallback(response) {
if (__stateModel === null) {
return;
}
//new handlers for potentially invalid responses from the webserver (cloud qa was having issues that brought down the app)
if (!response || response === null) {
return;
}
if (!response.data || response.data === null) {
return;
}
if (!response.data.State || response.data.State === null) {
return;
}
//end new handlers for potentially invalid responses
__stateModel.UpdateStateValues(response.data.State, true);
$rootScope.$broadcast("SMARTFORMS.STATE.UPDATED", { "NewState": __stateModel.GetValues(), "IsSuccess": false });
}
//#endregion Callbacks
function getState() {
return __stateModel || null;
}
function getValueSet(parent, dynamicUIFieldId) {
return _.find(parent.Values, function (v) { return v.DynamicUIFieldId == dynamicUIFieldId; });
}
function IsButtonEnabled(buttonName) {
if (__stateModel === null) {
return false;
}
var button = _.find(__stateModel.GetValues().MenuButtons, function (button) { return button.CommandName == buttonName; });
if (button) {
return button.Enabled;
}
return false;
}
function IsButtonVisible(buttonName) {
if (__stateModel === null) {
return false;
}
var button = _.find(__stateModel.GetValues().MenuButtons, function (button) { return button.CommandName == buttonName; });
if (button) {
return button.Visible;
}
return false;
}
function getClientTabSmartForms(tabId) {
return SmartFormsAPIService.GetClientTabSmartForms(tabId);
}
function getViewerTabSmartForms(tabId, documentId) {
return SmartFormsAPIService.GetViewerTabSmartForms(tabId, documentId);
}
function getDynamicUILayoutsByTabId(tabId, documentId, host) {
if (angular.isDefined(host) === false) {
host = "CLIENT";
}
return SmartFormsAPIService.GetDynamicUILayoutsByTabId(tabId, documentId, host);
}
function focusSection(sectionId) {
var defer = $q.defer();
//can't have runtime errors here
if (!angular.isDefined(sectionId)) {
sectionId = "";
}
if (__currentSectionId == sectionId || __queuedSectionIdToFocus == sectionId) {
defer.resolve(true);
} else {
__queuedSectionIdToFocus = sectionId;
var currentValues = __stateModel.GetValues();
if (sectionId == currentValues.Header.SectionId) {
openTab("header", false);
__currentRowId = null;
__currentSectionId = currentValues.Header.SectionId;
__currentAttachmentSectionId = -1;
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
defer.resolve(true);
} else if (sectionId == currentValues.Footer.SectionId) {
openTab("footer", false);
__currentRowId = null;
__currentSectionId = currentValues.Footer.SectionId;
__currentAttachmentSectionId = -1;
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
defer.resolve(true);
} else if (sectionId == currentValues.Totals.SectionId) {
openTab("totals", false);
__currentRowId = null;
__currentSectionId = null;
__currentAttachmentSectionId = -1;
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
defer.resolve(true);
} else if (sectionId == "btn") {
openTab("details", false);
__currentSectionId = null;
__currentRowId = null;
__currentAttachmentSectionId = -1;
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
defer.resolve(true);
} else {
//find the new row if is in fact a row in the detail section
var existingRow = _.find(currentValues.Details.Rows, function (r) { return r.RowId == sectionId; });
if (angular.isDefined(existingRow)) {
let rowIndex = _.findIndex(currentValues.Details.Rows, function (r) { return r.RowId == sectionId; });
if (rowIndex > -1) {
__currentAttachmentSectionId = rowIndex + (__currentDetailPageIndex * 50);
}
}
if (angular.isDefined(existingRow)) {
openTab("details", false);
}
//don't bother with row leave events if the detail section is disabled, but still need to change the current row id
if (angular.isDefined(existingRow) && __stateModel.GetValues().Details.ReadOnly === true) {
__currentRowId = __currentSectionId = sectionId;
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
}
//if the entered sectionId is for a row and the sectionId is different than the current rowid, we need to "enter" the row
if (angular.isDefined(existingRow) && __currentRowId !== sectionId && __stateModel.GetValues().Details.ReadOnly === false) {
//does the __currentRowId belong to an existing detail row?
var currentRow = _.find(__stateModel.GetValues().Details.Rows, function (r) { return r.RowId == __currentRowId; });
var enterRowArgs = [];
enterRowArgs[0] = sectionId; //new row id
enterRowArgs[1] = angular.isDefined(currentRow) ? __currentRowId : ""; //if not a row, pass in empty. EnterRow will "leave" a row that's specified (saves a round-trip)
__apiQueue.add(SmartFormsAPIService.EnterRow, enterRowArgs, function (response) {
if (response.data.IsSuccess == true) {
__currentRowId = sectionId;
__currentSectionId = sectionId;
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
__rawResponseData = response.data;
successCallback(response.data.State);
} else {
failCallback(response);
}
//show any prompts/dialogs necessary
ResponseMessageHandler.ProcessResponse(response.data);
defer.resolve(response);
}, function (response) {
__currentRowId = null;
__currentSectionId = null;
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
failCallback(response);
defer.reject(response);
}, "EnterRow(" + sectionId + ")");
} else {
//just broadcast the change event
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
defer.resolve(true);
}
}
}
return defer.promise;
}
function leaveRow(sectionId) {
var defer = $q.defer();
if (sectionId === null) {
defer.resolve();
} else {
var values = __stateModel.GetValues();
if (!angular.isDefined(__stateModel) || __stateModel == null || values.Details.Rows.length == 0) {
__currentRowId = null;
__currentSectionId = null;
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
defer.resolve();
} else {
var rowToleave = _.find(values.Details.Rows, function (r) { return r.RowId == sectionId; });
if (angular.isDefined(rowToleave)) {
__apiQueue.add(SmartFormsAPIService.LeaveRow, sectionId, function (response) {
if (response.data.IsSuccess == true) {
__currentRowId = null;
__currentSectionId = null;
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
__rawResponseData = response.data;
successCallback(response.data.State);
} else {
failCallback(response);
}
defer.resolve(response);
}, function (response) {
__currentRowId = null;
__currentSectionId = null;
$rootScope.$broadcast("SMARTFORMS.CURRENTSECTIONCHANGED", { "SectionId": __currentSectionId });
failCallback(response);
defer.reject(response);
}, "LeaveRow(" + sectionId + ")");
} else {
defer.resolve();
}
}
}
return defer.promise;
}
function menuButtonClick(commandName, addtlArgs, unsavedChangesSetting, bResetState) {
var defer = $q.defer();
if (!angular.isDefined(bResetState)) {
bResetState = false;
}
var args = [];
args[0] = commandName;
args[1] = addtlArgs;
args[2] = __attachments;
//internal wrappe function to do some pre-validation
var execFn = function () {
var defer = $q.defer();
var methodArgs = arguments[0]; //have to pull this into a local variable because it'll fall out of scope in the promise callback below
var commandName = arguments[0][0];
//if this is the save method, make sure the state is valid
if (commandName === __saveMethod) {
if (isStateValid() === true) {
//leave the existing Detail Row (will do nothing if we're not on a detail row)
leaveRow().then(function () {
defer.resolve(SmartFormsAPIService.MenuButtonClick(methodArgs));
});
} else {
//something's invalid, so alert user
modalService.showModal({}, {
headerText: "",
bodyText: $translate.instant("VIEWERSTAMPHOST_INVALIDFIELDSFOUND")
});
defer.resolve(null);
}
} else {
//leave the existing Detail Row (will do nothing if we're not on a detail row)
leaveRow().then(function () {
defer.resolve(SmartFormsAPIService.MenuButtonClick(methodArgs));
});
}
return defer.promise;
};
__apiQueue.add(execFn, args, function (response) {
if (response === null) {
defer.resolve({ data: { IsSuccess: false } });
return;
}
if (response.data.IsSuccess === true) {
__rawResponseData = response.data;
successCallback(response.data.State);
if (bResetState) {
__unsavedChangesExist = false;
//Get any attachments
$timeout(function () {
__apiQueue.add(SmartFormsAPIService.GetAttachments, [], function (response) {
__attachments = response.data.Items;
$.each(__stateModel.GetValues().Details.Rows, function (rowIndex, row) {
var rowAttachment = _.find(__attachments, function (attachment) { return attachment.sectionId == rowIndex + (__currentDetailPageIndex * 50); });
__stateModel.GetValues().Details.Rows[rowIndex].HasAttachment = (angular.isDefined(rowAttachment)) ? true : false;
});
$rootScope.$broadcast("SMARTFORMS.ATTACHMENTS.CHANGED");
}, function () { }, "GetAttachments");
});
}
} else {
failCallback(response);
}
//show any prompts/dialogs necessary
ResponseMessageHandler.ProcessResponse(response.data).then(function () {
//if there's still a ResponseMessage in the state, re-do the request
//console.log(JSON.stringify(__stateModel.GetResponseMessage()));
if (__stateModel.GetResponseMessage() !== null) {
menuButtonClick(commandName, addtlArgs, unsavedChangesSetting, bResetState);
} else if (response.data.IsSuccess === true) {
__unsavedChangesExist = unsavedChangesSetting;
}
});
defer.resolve(response);
}, function (response) {
//console.error("menuButtonClick error path");
//failCallback(response);
//show any prompts/dialogs necessary
ResponseMessageHandler.ProcessResponse(response.data).then(function () {
//if there's still a ResponseMessage in the state, re-do the request
//console.log(JSON.stringify(__stateModel.GetResponseMessage()));
if (__stateModel.GetResponseMessage() !== null) {
menuButtonClick(commandName, addtlArgs, unsavedChangesSetting, bResetState);
} else {
//console.log("unsavedChangesSetting: " + unsavedChangesSetting);
//__unsavedChangesExist = unsavedChangesSetting;
}
});
defer.reject(response);
}, "MenuButtonClick");
return defer.promise;
}
function loadFromTemplate(templateId) {
var defer = $q.defer();
__apiQueue.add(SmartFormsAPIService.LoadFromTemplate, templateId, function (response) {
__rawResponseData = response.data;
successCallback(response.data.State);
__unsavedChangesExist = true;
defer.resolve(response);
}, function (response) {
failCallback(response);
defer.reject(response);
}, "LoadFromTemplate(" + templateId + ")");
return defer.promise;
}
function addNewRow() {
var defer = $q.defer();
__apiQueue.add(SmartFormsAPIService.AddNewRow, null, function (response) {
__rawResponseData = response.data;
successCallback(response.data.State);
var lastRowId = response.data.State.Details.Rows[response.data.State.Details.Rows.length - 1].RowId;
focusFirstDetailRowField(lastRowId);
__unsavedChangesExist = true;
defer.resolve(response);
}, function (response) {
failCallback(response);
defer.reject(response);
}, "AddNewRow");
return defer.promise;
}
function removeRow() {
var defer = $q.defer();
//ensure that there is a selected row
var selectedRow = _.find(__stateModel.GetValues().Details.Rows, function (r) { return r.RowId == __currentRowId; });
var rowIndex = _.findIndex(__stateModel.GetValues().Details.Rows, function (r) { return r.RowId == __currentRowId; });
if (!angular.isDefined(selectedRow)) {
growl.error("SMARTFORMS_NOROWSELECTEDTODELETE", { ttl: 5000, disableCountDown: true });
defer.resolve();
} else if (selectedRow.HasAttachment === true) {
growl.error("SMARTFORMS_CANTDELETEROWWITHATTACHMENTS", { ttl: 5000, disableCountDown: false });
defer.resolve();
} else {
__apiQueue.add(SmartFormsAPIService.RemoveRow, __currentRowId, function (response) {
//update indexes of attachments for rows low than the one that was deleted
if (__attachments) {
$.each(__attachments, function (attachmentIndex) {
if (__attachments[attachmentIndex].sectionId >= rowIndex) {
__attachments[attachmentIndex].sectionId--;
}
});
}
$timeout(function () {
$rootScope.$broadcast("SMARTFORMS.ATTACHMENTS.CHANGED");
});
__rawResponseData = response.data;
successCallback(response.data.State);
//try to load the previous row in the list
var nextRowToFocus = __stateModel.GetValues().Details.Rows[rowIndex - 1];
if (!nextRowToFocus) {
//previous row doesn't exist, so try to load the next
nextRowToFocus = __stateModel.GetValues().Details.Rows[rowIndex];
}
//if we found a row, focus it
if (nextRowToFocus && nextRowToFocus != null) {
focusFirstDetailRowField(nextRowToFocus.RowId);
__unsavedChangesExist = true;
}
defer.resolve(response);
}, function (response) {
failCallback(response);
defer.reject(response);
}, "RemoveRow(" + __currentRowId + ")");
}
return defer.promise;
}
function getDetailPage(page) {
var defer = $q.defer();
__apiQueue.add(SmartFormsAPIService.GetDetailPage, page, function (response) {
__rawResponseData = response.data;
__currentDetailPageIndex = page - 1;
//reset attachment flags
$.each(response.data.State.Details.Rows, function (rowIndex, row) {
response.data.State.Details.Rows[rowIndex].HasAttachment = false;
var rowAttachment = _.find(__attachments, function (attachment) { return attachment.sectionId == rowIndex + (__currentDetailPageIndex * 50); });
if (angular.isDefined(rowAttachment)) {
response.data.State.Details.Rows[rowIndex].HasAttachment = true;
}
});
successCallback(response.data.State);
__unsavedChangesExist = true;
defer.resolve(response);
}, function (response) {
failCallback(response);
defer.reject(response);
}, "GetDetailPage");
return defer.promise;
}
function onFieldChanged(fieldChangedArgs) {
var defer = $q.defer();
var fieldChangedPromise;
var currentValues = __stateModel.GetValues();
if (fieldChangedArgs.GroupKey === currentValues.Header.SectionId) {
fieldChangedPromise = SmartFormsAPIService.OnHeaderValueChanged;
} else if (fieldChangedArgs.GroupKey === currentValues.Footer.SectionId) {
fieldChangedPromise = SmartFormsAPIService.OnFooterValueChanged;
} else if (fieldChangedArgs.GroupKey === currentValues.Totals.SectionId) {
fieldChangedPromise = SmartFormsAPIService.OnTotalsValueChanged;
} else {
var row = _.find(currentValues.Details.Rows, function (r) { return r.RowId === fieldChangedArgs.GroupKey; });
if (angular.isDefined(row)) {
fieldChangedPromise = SmartFormsAPIService.OnDetailValueChanged;
}
}
if (angular.isDefined(fieldChangedPromise)) {
__apiQueue.add(fieldChangedPromise, fieldChangedArgs, function (response) {
if (response.data.IsSuccess === true) {
__rawResponseData = response.data;
successCallback(response.data.State, fieldChangedArgs);
__unsavedChangesExist = true;
} else {
failCallback(response);
}
//show any prompts/dialogs necessary
ResponseMessageHandler.ProcessResponse(response.data).then(function () {
//if there's still a ResponseMessage in the state, re-do the request
//console.log(JSON.stringify(__stateModel.GetResponseMessage()));
if (__stateModel.GetResponseMessage() !== null) {
onFieldChanged(fieldChangedArgs);
}
});
defer.resolve(response);
}, function (response) {
failCallback(response);
defer.reject(response);
}, "OnFieldChanged(" + fieldChangedArgs + ")");
}
return defer.promise;
}
function onSaveTemplate(templateId, templateName) {
var defer = $q.defer();
var args = [];
args[0] = templateId;
args[1] = templateName;
__apiQueue.add(SmartFormsAPIService.OnSaveTemplate, args, function (response) {
__templates = response.data;
defer.resolve(response);
}, function (response) {
defer.reject(response);
}, "OnSaveTemplate(" + templateName + ")");
return defer.promise;
}
function onDeleteTemplate(templateId) {
var defer = $q.defer();
__apiQueue.add(SmartFormsAPIService.OnDeleteTemplate, templateId, function (response) {
__templates = response.data;
defer.resolve(response);
}, function (response) {
defer.reject(response);
}, "OnDeleteTemplate(" + templateId + ")");
return defer.promise;
}
function validateCurrentField() {
var fieldData = __activeElementId.split("_");
SmartFormsAPIService.Validate(fieldData[0], fieldData[1]);
}
function focusFirstHeaderField() {
var firstHeaderField = DoubleLinkedList.GetFirstHeaderField();
if (__stateModel.GetValues().Header.Enabled === true && firstHeaderField !== null) {
focusField(firstHeaderField.groupKey, firstHeaderField.fieldId);
}
}
function focusFirstFooterField() {
if (__stateModel.GetValues().Header.Enabled === true) {
var firstFooterField = DoubleLinkedList.GetFirstFooterField();
focusField(firstFooterField.groupKey, firstFooterField.fieldId);
}
}
function focusLast() {
var lastField = DoubleLinkedList.GetLastField();
focusField(lastField.groupKey, lastField.fieldId);
}
//function focusPrevious(currentFieldId) {
// var targetNameParts = currentFieldId.split("_");
// var thisNode = DoubleLinkedList.GetByGroupKeyAndId(targetNameParts[0], targetNameParts[1]);
// focusField(thisNode.prev.groupKey, thisNode.prev.fieldId);
//}
//function focusNext(currentFieldId) {
// var targetNameParts = currentFieldId.split("_");
// var thisNode = DoubleLinkedList.GetByGroupKeyAndId(targetNameParts[0], targetNameParts[1]);
// focusField(thisNode.next.groupKey, thisNode.next.fieldId);
//}
function focusFirstDetailRowField(rowId) {
var firstRowField = DoubleLinkedList.GetFirstDetailRowField(rowId);
focusField(firstRowField.groupKey, firstRowField.fieldId);
}
function focusFirstFieldInDetailSection() {
if (__stateModel.GetValues().Details.Rows.length > 0 && __stateModel.GetValues().Details.ReadOnly === false) {
var firstRowId = __stateModel.GetValues().Details.Rows[0].RowId;
focusFirstDetailRowField(firstRowId);
}
}
function getLookupOptions(layout, valueSet, page, orderByColumnName, orderByAscending, filters) {
var defer = $q.defer();
var args = [];
args.push(layout);
args.push(valueSet);
args.push(page);
args.push(orderByColumnName);
args.push(orderByAscending);
args.push(filters);
__apiQueue.add(SmartFormsAPIService.RunRemoteLookup, args, function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
}, "getLookupOptions()");
return defer.promise;
}
function isFieldDirty(valueSet) {
var returnValue = false;
//find existing valueSet
var currentValues = __stateModel.GetValues();
var existingValue;
if (valueSet.GroupKey === currentValues.Header.SectionId) {
existingValue = _.find(currentValues.Header.Values, function (v) { return v.DynamicUIFieldId === valueSet.DynamicUIFieldId; });
} else if (valueSet.GroupKey === currentValues.Footer.SectionId) {
existingValue = _.find(currentValues.Footer.Values, function (v) { return v.DynamicUIFieldId === valueSet.DynamicUIFieldId; });
} else if (valueSet.GroupKey === currentValues.Totals.SectionId) {
existingValue = _.find(currentValues.Totals.Values, function (v) { return v.DynamicUIFieldId === valueSet.DynamicUIFieldId; });
} else {
var row = _.find(currentValues.Details.Rows, function (r) { return r.RowId === valueSet.GroupKey; });
if (angular.isDefined(row)) {
existingValue = _.find(row.Values, function(v) { return v.DynamicUIFieldId === valueSet.DynamicUIFieldId; });
}
}
if (!angular.isDefined(existingValue)) {
console.log("existing value for " + valueSet.GroupKey + "_" + valueSet.DynamicUIFieldId + " not found");
//throw "existing value for " + valueSet.GroupKey + "_" + valueSet.DynamicUIFieldId + " not found";
return false;
}
switch (existingValue.ControlType) {
case "DynamicLookup":
case "DynamicDropDown":
case "BooleanEdit":
var existingText = existingValue.Text || "";
var newValue = valueSet.Text || "";
return (existingText !== newValue);
case "DynamicLabel":
return false;
case "DateEdit":
var currentDateValue = moment(existingValue.Value).format('YYYY-MM-DD');
return (currentDateValue !== valueSet.Text);
case "NumericEdit":
return (parseFloat(existingValue.Value) !== parseFloat(valueSet.Text));
}
return false;
}
function isStateValid() {
var stateIsValid = true;
var currentValues = __stateModel.GetValues();
if (_.find(currentValues.Header.Values, function (f) { return f.IsValid === false; })) {
stateIsValid = false;
}
if (stateIsValid === true && currentValues.Details.Rows.length > 0) {
$.each(currentValues.Details.Rows, function (rowIndex) {
stateIsValid = !angular.isDefined(_.find(currentValues.Details.Rows[rowIndex].Values, function (f) { return f.IsValid === false; }));
if (stateIsValid === false) {
return true;
}
});
}
if (stateIsValid === true) {
if (_.find(currentValues.Footer.Values, function (f) { return f.IsValid === false; })) {
stateIsValid = false;
}
}
return stateIsValid;
}
function removeAttachment(attachment, newDocumentTypeId) {
var defer = $q.defer();
//just remove the unsaved attachment
__attachments = _.reject(__attachments, function (a) { return a.key == attachment.key; });
$timeout(function () {
$rootScope.$broadcast("SMARTFORMS.ATTACHMENTS.CHANGED");
});
defer.resolve();
return defer.promise;
}
function registerNewAttachments(attachmentsArray) {
var defer = $q.defer();
var documentAttachments = [];
//spin through attachments array and determine if this is a file attachment that we can handle without a service call
//or a document attachment which will need to go through the service in case it generates a new line
$.each(attachmentsArray, function (i, attachment) {
if (attachment.IsLooseFile === true) {
__attachments.push(attachment);
} else {
var AttachmentDataModel = {
sectionId: __currentSectionId,
DocumentId: attachment.key
};
documentAttachments.push(AttachmentDataModel);
}
});
//if there are document attachments, send the array to the service to handle
if (documentAttachments.length > 0) {
__apiQueue.add(SmartFormsAPIService.AddAttachments, documentAttachments, function (response) {
__rawResponseData = response;
successCallback(response.data.State);
if (documentAttachments[0].sectionId == __stateModel.GetValues().Header.SectionId && __stateModel.GetLayout().CanImportLineItemsFromExistingDoc === true) {
//new attachments at the header are new line items, so load the latest
var lastRowId = response.data.State.Details.Rows[response.data.State.Details.Rows.length - 1].RowId;
focusFirstDetailRowField(lastRowId);
}
__unsavedChangesExist = true;
$.each(response.data.Attachments, function (i, a) {
__attachments.push(a);
});
//if (__stateModel.GetLayout().CanImportLineItemsFromExistingDoc == true) {
// attachment.sectionId = response.data.State.Details.Rows.length - 1;
//}
//__attachments.push(attachment);
$timeout(function () {
$rootScope.$broadcast("SMARTFORMS.ATTACHMENTS.CHANGED");
});
defer.resolve(response);
}, function (response) {
defer.reject(response);
}, "AddAttachment");
} else {
$rootScope.$broadcast("SMARTFORMS.ATTACHMENTS.CHANGED");
defer.resolve();
}
return defer.promise;
}
function getAttachableDocuments(orderByColumnName, orderByDescending, page) {
var defer = $q.defer();
if (!angular.isDefined(orderByColumnName)) { orderByColumnName = "EntryDate"; }
if (!angular.isDefined(orderByDescending)) { orderByDescending = false; }
if (!angular.isDefined(page)) { page = 0; }
var RunAttachmentInquiryRequestModel = {};
RunAttachmentInquiryRequestModel.OrderBy = orderByColumnName;
RunAttachmentInquiryRequestModel.OrderByDescending = orderByDescending;
RunAttachmentInquiryRequestModel.Page = page;
RunAttachmentInquiryRequestModel.PageSize = 100;
//pass in document id of the attachments already added to the form
RunAttachmentInquiryRequestModel.ExcludedDocumentIds = [];
$.each(__attachments, function (i, a) {
if (a.IsLooseFile === false) {
RunAttachmentInquiryRequestModel.ExcludedDocumentIds.push(a.key);
}
});
__apiQueue.add(SmartFormsAPIService.GetAttachableDocuments, RunAttachmentInquiryRequestModel, function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
}, "GetAttachableDocuments()");
return defer.promise;
}
function runDocumentProcessingInquiry(request) {
var defer = $q.defer();
__apiQueue.add(SmartFormsAPIService.RunDocumentProcessingInquiry, request, function (response) {
defer.resolve(response);
}, function (response) {
defer.reject(response);
}, "RunDocumentProcessingInquiry()");
return defer.promise;
}
function openTab(tabName, focusFirstField) {
$rootScope.$broadcast("ON_OPEN_SMARTFORM_TAB", { "tabName": tabName });
var loadFirst = angular.isDefined(focusFirstField) ? (focusFirstField === true) : false;
if (loadFirst === true && tabName == "header") {
focusFirstHeaderField();
} else if (loadFirst === true && tabName == "details") {
focusFirstFieldInDetailSection();
} else if (loadFirst === true && tabName == "footer") {
focusFirstFooterField();
}
}
function onOpenTab($scope, handler) {
return $scope.$on("ON_OPEN_SMARTFORM_TAB", function (event, payload) {
// note that the handler is passed the domain parameters
handler(payload.tabName);
});
}
function saveState(smartFormIInstanceId) {
$rootScope.$broadcast("ON_SAVE_SMARTFORM_STATE", { "SmartFormIInstanceId": smartFormIInstanceId });
}
function onSaveState($scope, handler) {
return $scope.$on("ON_SAVE_SMARTFORM_STATE", function (event, payload) {
// note that the handler is passed the domain parameters
handler(payload.SmartFormIInstanceId);
});
}
//#endregion Public Methods
//#region Helper/private Methods
function loadNavigationList() {
var layout = __stateModel.GetLayout();
var values = __stateModel.GetValues();
//clear the linked list
DoubleLinkedList.clear();
//add header fields to linked List
$.each(layout.Header.Layout.sort(SortBySequence), function (index, field) {
var valueSet = _.find(values.Header.Values, function (v) { return v.DynamicUIFieldId == field.DynamicUIFieldId; });
//add each editable header field into the dll
if (!field.ReadOnly && valueSet.Enabled && field.Visible && field.ControlType !== SmartFormsConstants.DynamicControlType["DynamicLabel"]) {
DoubleLinkedList.add("header", layout.Header.SectionId, field.DynamicUIFieldId);
}
});
//add details fields to linked List
$.each(values.Details.Rows, function (rowindex, row) {
$.each(layout.Details.Layout, function (fieldindex, field) {
////build field
var valueSet = _.find(row.Values, function (vs) {
return vs.DynamicUIFieldId == field.DynamicUIFieldId;
});
//add to tab list if it's editable
if (valueSet.CanEdit === true) {
DoubleLinkedList.add("details", row.RowId, valueSet.DynamicUIFieldId);
}
});
});
//add buttons into dll
if (values.Details.CanAdd) {
DoubleLinkedList.add("details", "btn", "AddNewRow");
}
if (values.Details.CanRemove) {
DoubleLinkedList.add("details", "btn", "RemoveNewRow");
}
//add footer fields to linked List
$.each(layout.Footer.Layout.sort(SortBySequence), function (index, field) {
var valueSet = _.find(values.Footer.Values, function (v) { return v.DynamicUIFieldId == field.DynamicUIFieldId; });
//add each editable footer field into the dll
if (!field.ReadOnly && valueSet.Enabled && field.Visible && field.ControlType !== SmartFormsConstants.DynamicControlType["DynamicLabel"]) {
DoubleLinkedList.add("footer", layout.Footer.SectionId, field.DynamicUIFieldId);
}
});
}
function SortBySequence(a, b) {
var aName = a.Sequence;
var bName = b.Sequence;
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
function focusField(groupKey, fieldId) {
//console.log("focusField");
//console.log("element id", groupKey + "_" + fieldId);
//console.log("__activeElementId", __activeElementId);
if (__activeElementId == groupKey + "_" + fieldId) {
return;
}
validateCurrentField();
__activeElementId = groupKey + "_" + fieldId;
//console.log("finding", __activeElementId);
$timeout(function () {
var retryInterval = 0;
//console.log("retryInterval", retryInterval);
if ($("#" + __activeElementId).length === 0) {
var myVar = window.setInterval(function () {
if ($("#" + __activeElementId).length > 0) {
window.clearInterval(myVar);
//console.log("found and focused " + __activeElementId + " after " + retryInterval + " tries");
$("#" + __activeElementId).focus();
} else {
if (retryInterval++ > 10) {
//console.log("failed to find and focus " + __activeElementId + " in 10s");
window.clearInterval(myVar);
}
}
}, 100);
} else {
//console.log("found and focused " + __activeElementId);
$("#" + __activeElementId).focus().select();
}
});
focusSection(groupKey);
////console.log("focusing section", groupKey);
//focusSection(groupKey).then(function () {
// validateCurrentField();
// __activeElementId = groupKey + "_" + fieldId;
// //console.log("finding", __activeElementId);
// $timeout(function () {
// var retryInterval = 0;
// //console.log("retryInterval", retryInterval);
// if ($("#" + __activeElementId).length === 0) {
// var myVar = window.setInterval(function () {
// if ($("#" + __activeElementId).length > 0) {
// window.clearInterval(myVar);
// //console.log("found and focused " + __activeElementId + " after " + retryInterval + " tries");
// $("#" + __activeElementId).focus();
// } else {
// if (retryInterval++ > 10) {
// //console.log("failed to find and focus " + __activeElementId + " in 10s");
// window.clearInterval(myVar);
// }
// }
// }, 100);
// } else {
// //console.log("found and focused " + __activeElementId);
// $("#" + __activeElementId).focus().select();
// }
// });
//}, function () {
// validateCurrentField();
// __activeElementId = groupKey + "_" + fieldId;
// //console.log("found and focused " + __activeElementId);
// $("#" + __activeElementId).focus().select();
//});
}
//#endregion Helper/private Methods
}
})();
(function () {
'use strict';
angular.module('SmartForms').directive('attachmentViewer', ["$rootScope", "$timeout", "$interval", "$translate", "$compile", "StateService", "DocumentViewerService", "FileUploadService", "$uibModal", "LocalStorageService", "SessionFactory", "growl", "DocumentService", "$http", "LibraryFunctions", "$filter", attachmentViewer]);
function attachmentViewer($rootScope, $timeout, $interval, $translate, $compile, StateService, DocumentViewerService, FileUploadService, $uibModal, LocalStorageService, SessionFactory, growl, DocumentService, $http, LibraryFunctions, $filter) {
return {
restrict: 'A',
templateUrl: function (tElement, tAttrs) {
if (tAttrs) {
if (tAttrs.host === 'client') {
return "tpl.AttachmentViewer_ClientHost.html";
} else {
return "tpl.AttachmentViewer_ViewerHost.html";
}
}
},
replace: true,
scope: true,
controller: ['$scope', '$element', function ($scope, $element) {
//#region declarations
$scope.attachmentListCaption = $translate.instant("ATTACHMENTVIEWER_LISTCAPTION_GENERIC");
$scope.filterByAttachmentSection = true;
$scope.CurrentAttachment = null;
$scope.CurrentAttachmentPageIndex = 0;
$scope.DocumentMetadata = null;
$scope.attachmentCanvas = null;
$scope.backgroundImage_height = 0;
$scope.backgroundImage_width = 0;
$scope.CurrentZoom = "bestfit";
$scope.visibleAttachments = [];
$scope.Rows = [];
var __globalscaleX = 1;
var __globalscaleY = 1;
var __currentRotation = 0;
$scope.SmallView = $(".device-xs").is(":visible");
$scope.CanAttachExisting = false;
$scope.CanUpload = false;
$scope.attachmentWindowSelectedSectionId = parseInt(StateService.GetCurrentAttachmentSectionId(), 10);
//#endregion declarations
//#region event handlers
//watch for changes to the State
$scope.$on("SMARTFORMS.STATE.UPDATED", function (event, payload) {
calculateCanAttachExisting(StateService.GetState());
calculateCanUpload(StateService.GetState());
});
//watch for changes to the selected row
$scope.$on("SMARTFORMS.CURRENTSECTIONCHANGED", function (event, payload) {
//console.log("on SMARTFORMS.CURRENTSECTIONCHANGED in attachmentViewer");
$scope.attachmentWindowSelectedSectionId = StateService.GetCurrentAttachmentSectionId();
calculateCanAttachExisting(StateService.GetState());
calculateCanUpload(StateService.GetState());
});
$scope.attachments = StateService.GetAttachments();
$scope.$on("SMARTFORMS.ATTACHMENTS.CHANGED", function () {
$scope.attachments = StateService.GetAttachments();
if (angular.isDefined($scope.attachments) && $scope.attachments.length > 0) {
$scope.visibleAttachments = getFilteredAttachmentList();
if ($scope.CurrentAttachment === null && $scope.visibleAttachments.length > 0) {
viewAttachment($scope.visibleAttachments[0]);
} else if ($scope.CurrentAttachment !== null && $scope.visibleAttachments.length > 0) {
//make sure we're looking at the correct attachment
var selectedAttachment = _.find($scope.visibleAttachments, function (attachment) { return attachment.key === $scope.CurrentAttachment.key; });
viewAttachment(selectedAttachment);
}
} else {
$scope.attachments = [];
$scope.visibleAttachments = [];
$scope.CurrentAttachment = null;
$scope.DocumentMetadata = null;
$scope.CurrentAttachmentPageIndex = 0;
}
});
$scope.toggleFilter = function () {
$scope.filterByAttachmentSection = !$scope.filterByAttachmentSection;
};
$scope.$watchGroup(["attachmentWindowSelectedSectionId", "filterByAttachmentSection"], function () {
//console.log("filterByAttachmentSection", $scope.filterByAttachmentSection);
//console.log("attachmentWindowSelectedSectionId in attachmentViewer", $scope.attachmentWindowSelectedSectionId);
$scope.attachmentListCaption = getListCaption();
var importCaption = $translate.instant("ATTACHMENTVIEWER_ATTACH_BUTTON");// "Attach Existing Document";
if (StateService.GetState() !== null && StateService.GetState().GetLayout().CanImportLineItemsFromExistingDoc === true)
{
importCaption = $translate.instant("ATTACHMENTVIEWER_IMPORT_BUTTON");// "Import Existing Document";
}
if ($scope.attachmentWindowSelectedSectionId > -1) {
if (StateService.GetState() !== null && StateService.GetState().GetLayout().CanImportLineItemsFromExistingDoc === false) {
importCaption = $translate.instant("ATTACHMENTVIEWER_ATTACHATLINE_BUTTON", { "lineNumber": $scope.attachmentWindowSelectedSectionId + 1 }); //Attach a DocLink document to line {{lineNumber}}
} else {
importCaption = $translate.instant("ATTACHMENTVIEWER_ATTACH_BUTTON");// "Attach Existing Document";
}
} else {
importCaption = $translate.instant("ATTACHMENTVIEWER_ATTACH_BUTTON");// "Attach Existing Document";
}
$scope.AttachLabel = importCaption;
if (angular.isDefined($scope.attachments) === false || (angular.isDefined($scope.attachments) === true && $scope.attachments.length === 0)) {
$scope.attachments = StateService.GetAttachments();
}
if (angular.isDefined($scope.attachments)) {
$scope.visibleAttachments = getFilteredAttachmentList();
var firstSectionAttachment = _.find($scope.visibleAttachments, function (attachment) { return attachment.sectionId === $scope.attachmentWindowSelectedSectionId; });
if (angular.isDefined(firstSectionAttachment)) {
viewAttachment(firstSectionAttachment);
} else {
viewAttachment(null);
}
}
calculateCanAttachExisting(StateService.GetState());
});
//#endregion event handlers
//#region public methods
$scope.OpenAttachment = viewAttachment;
$scope.GoToFirstPage = function () {
$scope.SelectImage(0);
};
$scope.GoToLastPage = function () {
$scope.SelectImage($scope.DocumentMetadata.Pages.length - 1);
};
$scope.GoToPrevPage = function () {
$scope.pageLoading = true;
var currentPageIndex = $scope.DocumentMetadata.CurrentPage.Number - 1;
if (currentPageIndex > 0) {
$scope.SelectImage(currentPageIndex - 1);
}
};
$scope.GoToNextPage = function () {
$scope.pageLoading = true;
var currentPageIndex = $scope.DocumentMetadata.CurrentPage.Number - 1;
if (currentPageIndex < $scope.DocumentMetadata.Pages.length) {
$scope.SelectImage(currentPageIndex + 1);
}
};
$scope.SelectImage = function (pageIndex) {
//current page
$scope.DocumentMetadata.CurrentPage = $scope.DocumentMetadata.Pages[pageIndex];
if (!$scope.DocumentMetadata.CurrentPage) {
return;
}
$scope.CurrentAttachmentPageIndex = pageIndex;
//reset zoom and rotation
__globalscaleX = 1;
__globalscaleY = 1;
__currentRotation = 0;
//if the page hasn't been loaded, yet, load it
if (!$scope.DocumentMetadata.CurrentPage.PageSrc) {
if ($scope.CurrentAttachment.IsLooseFile === false) {
DocumentService.GetPageSrc($scope.CurrentAttachment.key, $scope.DocumentMetadata.CurrentPage.Number).then(function (data) {
$scope.DocumentMetadata.CurrentPage.PageSrc = data.PageSrc;
$scope.DocumentMetadata.CurrentPage.PageDPI = data.PageDPI;
$scope.DocumentMetadata.PageCount = data.PageCount;
//set the background image to the current page
loadDocumentImageData($scope.DocumentMetadata.CurrentPage);
});
} else {
FileUploadService.GetUploadFilePage($scope.CurrentAttachment.key, $scope.DocumentMetadata.CurrentPage.Number - 1).then(function (response) {
$scope.DocumentMetadata.CurrentPage.PageSrc = response.data.PageSrc;
$scope.DocumentMetadata.CurrentPage.PageDPI = response.data.PageDPI;
$scope.DocumentMetadata.PageCount = response.data.PageCount;
//set the background image to the current page
loadDocumentImageData($scope.DocumentMetadata.CurrentPage);
});
}
} else {
//set the background image to the current page
loadDocumentImageData($scope.DocumentMetadata.CurrentPage);
}
};
$scope.ZoomIn = function () {
zoom("in");
};
$scope.ZoomOut = function () {
zoom("out");
};
$scope.RotateLeft = function () {
rotate(-1);
};
$scope.RotateRight = function () {
rotate(1);
};
$scope.NavigateToNextRow = function () {
if ($scope.attachmentWindowSelectedSectionId < 0) {
$scope.attachmentWindowSelectedSectionId = 0;
} else if (($scope.attachmentWindowSelectedSectionId + 1) >= $scope.Rows.length) {
$scope.attachmentWindowSelectedSectionId = 0;
} else {
$scope.attachmentWindowSelectedSectionId++;
}
var row = $scope.Rows[$scope.attachmentWindowSelectedSectionId];
if (!row) {
$scope.attachmentWindowSelectedSectionId = 0;
row = $scope.Rows[$scope.attachmentWindowSelectedSectionId];
}
StateService.FocusSection(row.RowId);
};
$scope.RemoveAttachment = function (attachment) {
//if we're looking at the attachment we're deleting, clear out the scope variables so the viewer will load the first attachment if there is one
if ($scope.CurrentAttachment.key === attachment.key) {
$scope.CurrentAttachment = null;
$scope.DocumentMetadata = null;
$scope.CurrentAttachmentPageIndex = 0;
}
//can we just remove the attachment?
var bCanRemove = false;
if (attachment.IsLooseFile === true) {
bCanRemove = true; //unindexed attached file, so yes
} else if (attachment.IsLooseFile === false && attachment.DocTypeId !== StateService.GetState().GetLayout().AttachmentDocTypeId) {
bCanRemove = true; //pre-existing document that has not yet been indexed as the attachment doc type, so yes
}
if (bCanRemove === true) {
StateService.RemoveAttachment(attachment).then(function () {
//remove this attachment from the visible list (defensive because the attachmentWindowSelectedSectionId or filterByAttachmentSection might change concurrently and create a racing condition)
$scope.visibleAttachments = _.reject($scope.visibleAttachments, function (a) { return a.key === attachment.key; });
});
} else if (attachment.IsLooseFile === false && attachment.DocTypeId === StateService.GetState().GetLayout().AttachmentDocTypeId) {
//we can't just remove the attachment since it's a saved attachment that now exists as a DocLink document with the attachment file type.
//We need to prompt the user to change the document type
var metaDataFlags = 0;
metaDataFlags |= 1; //DocumentInfo
metaDataFlags |= 2; //OriginationInfo
metaDataFlags |= 4; //IndexProperties
$scope.document = null;
DocumentService.DocumentMetaData(attachment.key, metaDataFlags).then(function (metaData) {
$scope.document = {
DocumentInfo: metaData.DocumentInfo,
DLFolderID: metaData.DLFolderID,
DocumentTypeID: metaData.DocumentTypeId,
DocumentID: attachment.key,
PropertiesAreDirty: false
};
var reindexPopup = '' +
'' +
'
'; //+
//'