function controller($scope,$timeout,$state,$rootScope){var vm=this;/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&(angular.element("html").addClass("ismobile"),localStorage.setItem("ma-layout-status",1)),vm.sidebarToggle={left:!1,right:!1},localStorage.getItem("ma-layout-status")||localStorage.setItem("ma-layout-status",1),vm.layoutType=localStorage.getItem("ma-layout-status"),vm.$state=$state;var fullscreenStates=["map","dwg.view","document.viewPdf","bimFile.view","bimFile.viewBim","entityPermissionProfile.edit","entityPermissionProfile.create","namedSelection.edit","namedSelection.create","alarm.edit","alarm.create","planiasystem","databaseInfo","login","forgotPassword","bcfProject.create","bcfProject.edit","workingDaysOff.create","workingDaysOff.edit","bimProjects","mobileMenuProfile.edit","mobileMenuProfile.create","admin.dashboard","doorKeySystem.edit","doorKeySystem.create","doorKey.edit","doorKey.create","doorLock.edit","doorLock.create","doorKeyXUser.edit","doorKeyXUser.create"],ignoreOverflowStates=["map","dwg.view","document.viewPdf"],shouldUseFullscreen=function(params){if(params&¶ms.template)return!0;for(var i=0;i=0&&rect.left>=0&&rect.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&rect.right<=(window.innerWidth||document.documentElement.clientWidth)}function randomString(length){for(var result="",characters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",charactersLength=characters.length,i=0;i=0)return void $state.go(defaultState,defaultParams,{reload:!0});$window.history.back()},$rootScope.getEntityCaption=function(entity){if(!entity)return"";var id=entity.Id||entity.id||"",description=entity.Description||entity.description||"";return id?id+(description?" - "+description:""):description},$rootScope.$on("$stateChangeStart",function(event,to,toParams){var top=$modalStack.getTop();if(top&&!isAcceptTermsOfUseModalOpen&&$modalStack.dismiss(top.key),!to.publicPage&&!authService.getUserData().isAuthenticated){event.preventDefault();var returnTo=JSON.stringify({name:to.name,params:toParams});$state.go("login",{returnToState:returnTo,message:translationService.translate("web-notLoggedIn-Navigation-message","Du har ikke en aktiv innlogging, logg inn for å komme til ønsket side.")})}});var setHtmlTitleFromParams=function(to,toParams){var translatedStateName=translationService.getTranslationIfExists("web-topMenu-"+to.name,"");if(translatedStateName&&translatedStateName!==to.name)return void $rootScope.setHtmlTitleByText(translatedStateName);if(toParams.entityData){var translatedMenuItem=translationService.getTranslationIfExists("web-topMenu-"+toParams.entityData.prefix);if(translatedMenuItem)return void $rootScope.setHtmlTitleByText(translatedMenuItem)}$rootScope.setHtmlTitleByText("Plania - "+to.name)};$rootScope.setHtmlTitleByText=function(title){$rootScope.htmlTitle=title},$rootScope.setHtmlTitleByModel=function(model){$rootScope.setHtmlTitleByText(model?model.Caption:"")},$rootScope.$on("$stateChangeSuccess",function(ev,to,toParams,from,fromParams){window.scrollTo(0,0),from.name&&from.name!==to.name&&from.excludeFromHistory&&$window.history.replaceState({},"any",$location.absUrl()),$rootScope.isPublicPage=to.publicPage,to.name.indexOf(".edit")>-1?$rootScope.disableGlobalFiltering=!0:$rootScope.disableGlobalFiltering=!1,authService.getUserData().isAuthenticated&&signalRconfig.setEditPageListener(to,toParams,from,fromParams),setHtmlTitleFromParams(to,toParams)}),$window.history.scrollRestoration&&($window.history.scrollRestoration="manual"),authService.getUserData().isAuthenticated&&(signalR.setQs({fingerprint:config.fingerprint,guidUser:authService.getUserData().guidUser}),signalR.start());var translationModeListener=function(event){"l"===event.key&&(event.ctrlKey||event.metaKey)&&event.altKey&&$rootScope.hasEditAccess("LanguageXWebText")&&$rootScope.userInfo.isSystemAdministrator&&$rootScope.$apply(function(){$rootScope.translationMode=!$rootScope.translationMode,$rootScope.$broadcast($rootScope.events.translationMode)})},pasteUserNameTimestampShortcut=function(event){function getActiveElement(root){root||(root=document);var activeEl=root.activeElement;return activeEl?activeEl.shadowRoot?getActiveElement(activeEl.shadowRoot):activeEl:null}var activeElement=getActiveElement();if(activeElement&&event.ctrlKey&&"<"===event.key&&("input"===activeElement.tagName.toLowerCase()||"textarea"===activeElement.tagName.toLowerCase())){var text=$localStorage.userData.realName;$localStorage.userData.realName||(text=$localStorage.userData.userName),text+=" - ",text+=$filter("date")((new Date).toISOString(),"dd.MM.yyyy HH:mm:ss");var selectionStart=activeElement.selectionStart,currentText=activeElement.value,newCaretPos=selectionStart+text.length,nativeInputValueSetter=Object.getOwnPropertyDescriptor("textarea"===activeElement.tagName.toLowerCase()?window.HTMLTextAreaElement.prototype:window.HTMLInputElement.prototype,"value").set;if(activeElement.selectionStart!==activeElement.selectionEnd&&(currentText=currentText.substring(0,activeElement.selectionStart)+currentText.substring(activeElement.selectionEnd)),activeElement.maxLength>0){var availableLength=activeElement.maxLength-currentText.length;if(availableLength<=0)return;text=text.substring(0,availableLength)}var newText=currentText.substring(0,selectionStart)+text+currentText.substring(selectionStart);nativeInputValueSetter.call(activeElement,newText),activeElement.dispatchEvent(new Event("input",{bubbles:!0})),activeElement.setSelectionRange(newCaretPos,newCaretPos)}};document.addEventListener("keydown",translationModeListener),document.addEventListener("keydown",pasteUserNameTimestampShortcut),datepickerConfig.showWeeks=!1,datepickerPopupConfig.showButtonBar=!1,$templateCache.put("template/datepicker/day.html",'
{{::label.abbr}}
{{ weekNumbers[$index] }}
'),$templateCache.put("template/datepicker/month.html",'
'),$templateCache.put("template/datepicker/year.html",'
'),$templateCache.put("template/tabs/tabset.html",'
    '),$templateCache.put("template/carousel/carousel.html",''),window.isAngularLoaded=!0}var app=angular.module("Plania",["ngStorage","ngSanitize","ngTable","ngAnimate","ngFileUpload","ngTagsInput","ui.bootstrap","ui.bootstrap.contextMenu","ui.tree","ui.router","ui.tinymce","uiCropper","leaflet-directive","angular-loading-bar","localytics.directives","slick","Firestitch.angular-counter","nouislider","internationalPhoneNumber","angular-bind-html-compile"]);app.config(["$httpProvider","$locationProvider","cfpLoadingBarProvider","$tooltipProvider","$localStorageProvider","$sessionStorageProvider","$modalProvider","ipnConfig","$sceDelegateProvider","$compileProvider",function($httpProvider,$locationProvider,loadingBarConfig,tooltipProvider,localStorageProvider,sessionStorageProvider,$modalProvider,ipnConfig,$sceDelegateProvider,$compileProvider){$locationProvider.html5Mode(!0).hashPrefix("!"),$httpProvider.interceptors.push("authInterceptorService"),$httpProvider.interceptors.push("setSavingInterceptorService"),loadingBarConfig.includeBar=!1,$compileProvider.aHrefSanitizationWhitelist&&$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|webcal|local|file|data|blob|plania-app):/);var parser=new UAParser,result=parser.getResult();if(result.device&&("tablet"===result.device.type||"mobile"===result.device.type)){var options={trigger:"dontTrigger"};tooltipProvider.options(options)}var magicNumber=42,moveChars=function(key,n){for(var chars=key.toString().split(""),i=0;i"},{name:"dashboard.view",url:"/view/:guid?:menuGuid??filter",availableWebMenu:"Dashboard",filters:dashboardFilter,params:{editMode:!1},templateUrl:"app/dashboard/dashboard.html",controller:"DashboardController",reloadOnSearch:!0},{name:"dashboard.list",url:"/list",templateUrl:"app/dashboard/listDashboard.html",controller:"ListController",params:{entityData:apiData.webDashboard}},{name:"user",url:"/user",abstract:!0,template:""},{name:"user.list",availableWebMenu:"Brukerliste",filters:userListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/user/views/listUser.html",controller:"ListController",params:{entityData:apiData.user}},{name:"user.create",url:"/create",params:{menuGuid:""},templateUrl:"app/user/views/editUser.html",controller:"UserController",excludeFromHistory:!0},{name:"user.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/user/views/editUser.html",controller:"UserController"},{name:"webUserToken",url:"/webUserToken",abstract:!0,template:""},{name:"webUserToken.list",availableWebMenu:"InnloggetBrukerliste",filters:userListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/webUserToken/views/listWebUserToken.html",controller:"ListController",params:{entityData:apiData.webUserToken}},{name:"profile",url:"/profile",abstract:!0,template:""},{name:"profile.view",url:"/view", templateUrl:"app/profile/views/myProfile.html",controller:"MyProfileController"},{name:"profile.changePassword",url:"/changePassword",templateUrl:"app/profile/views/changePassword.html",controller:"ChangePasswordController",excludeFromHistory:!0},{name:"workOrder",url:"/workOrder",abstract:!0,template:""},{name:"workOrder.list",availableWebMenu:"Arbeidsordreliste",filters:workOrderListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/workOrder/views/listWorkOrder.html",controller:"ListController",params:{entityData:apiData.workOrder}},{name:"workOrder.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/workOrder/views/editWorkOrder.html",controller:"WorkOrderController"},{name:"workOrder.create",url:"/create?menuGuid",availableWebMenu:"Ny arbeidsordre",filters:newWorkOrderFilter,params:{showPersistantData:!1,menuGuid:null,guidEntityToCopy:null,entityData:apiData.workOrder},templateUrl:"app/workOrder/views/editWorkOrder.html",controller:"WorkOrderController",excludeFromHistory:!0},{name:"workOrderTemplate",url:"/workOrderTemplate",abstract:!0,template:""},{name:"workOrderTemplate.list",availableWebMenu:"Arbeidsordremal liste",filters:periodicTaskListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/periodicTask/views/listPeriodicTask.html",controller:"ListController",params:{entityData:apiData.workOrderTemplate}},{name:"workOrderTemplate.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/periodicTask/views/editPeriodicTask.html",controller:"PeriodicTaskController"},{name:"workOrderTemplate.create",url:"/create",params:{showPersistantData:!1,menuGuid:"",guidEntityToCopy:""},templateUrl:"app/periodicTask/views/editPeriodicTask.html",controller:"PeriodicTaskController",excludeFromHistory:!0},{name:"workOrderXResourceGroup",url:"/workOrderXResourceGroup",abstract:!0,template:""},{name:"workOrderXResourceGroup.list",availableWebMenu:"Timeføringsliste",url:"/list/:menuGuid??filter",templateUrl:"app/resourceGroup/views/listWorkOrderXResourceGroup.html",controller:"ListController",params:{entityData:apiData.workOrderXResourceGroup}},{name:"estate",url:"/estate",abstract:!0,template:""},{name:"estate.list",availableWebMenu:"Eiendomsliste",filters:estateListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/estate/views/listEstate.html",controller:"ListController",params:{entityData:apiData.estate}},{name:"estate.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/estate/views/editEstate.html",controller:"EstateController"},{name:"estate.create",url:"/create",params:{menuGuid:"",guidEntityToCopy:""},templateUrl:"app/estate/views/editEstate.html",controller:"EstateController",excludeFromHistory:!0},{name:"building",url:"/building",abstract:!0,template:""},{name:"building.list",availableWebMenu:"Byggliste",filters:buildingListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/building/views/listBuilding.html",controller:"ListController",params:{entityData:apiData.building}},{name:"building.edit",availableWebMenu:"Bygginformasjon",url:"/edit/:guid",params:{menuGuid:"",tab:""},templateUrl:"app/building/views/editBuilding.html",controller:"BuildingController"},{name:"building.create",url:"/create",params:{showPersistantData:!1,menuGuid:"",guidEntityToCopy:""},templateUrl:"app/building/views/editBuilding.html",controller:"BuildingController",excludeFromHistory:!0},{name:"buildingTemplate",url:"/buildingTemplate",abstract:!0,template:""},{name:"buildingTemplate.list",availableWebMenu:"Byggmal",filters:buildingTemplateListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/buildingTemplate/views/listBuildingTemplate.html",controller:"ListController",params:{entityData:apiData.buildingTemplate}},{name:"buildingTemplate.edit",url:"/edit/:guid",params:{menuGuid:"",tab:""},templateUrl:"app/buildingTemplate/views/editBuildingTemplate.html",controller:"BuildingTemplateController"},{name:"buildingTemplate.create",url:"/create",params:{showPersistantData:!1,menuGuid:"",guidEntityToCopy:""},templateUrl:"app/buildingTemplate/views/editBuildingTemplate.html",controller:"BuildingTemplateController",excludeFromHistory:!0},{name:"buildingPerson",url:"/buildingPerson",abstract:!0,template:""},{name:"buildingPerson.list",availableWebMenu:"Driftsansvarlig",filters:buildingPersonFilter,url:"/list/:menuGuid??filter",templateUrl:"app/buildingPerson/views/listBuildingPerson.html",controller:"ListController",params:{entityData:apiData.buildingPerson,modal:{templateUrl:"app/buildingPerson/views/editBuildingPerson.html",controller:"BuildingPersonController",modalParam:{isUpdate:!0}}}},{name:"buildingPerson.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/buildingPerson/views/editBuildingPerson.html",controller:"BuildingPersonController"},{name:"equipment",url:"/equipment",abstract:!0,template:""},{name:"equipment.list",availableWebMenu:"Anleggsliste",filters:equipmentListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/equipment/views/listEquipment.html",controller:"ListController",params:{entityData:apiData.equipment}},{name:"equipment.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/equipment/views/editEquipment.html",controller:"EquipmentController"},{name:"equipment.create",url:"/create",params:{showPersistantData:!1,menuGuid:"",guidEntityToCopy:""},templateUrl:"app/equipment/views/editEquipment.html",controller:"EquipmentController",excludeFromHistory:!0},{name:"equipment.dataacquisition",availableWebMenu:"Datafangst anleggsdokumentasjon",url:"/dataacquisition",templateUrl:"app/equipment/dataAcquisition/equipmentDataAcquisition.html",controller:"EquipmentDataAcquisitionController",params:{entityData:apiData.equipmentDataAcquisition}},{name:"component",url:"/component",abstract:!0,template:""},{name:"component.list",availableWebMenu:"Komponentliste",filters:buildingListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/component/views/listComponent.html",controller:"ListController",params:{entityData:apiData.component}},{name:"component.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/component/views/editComponent.html",controller:"ComponentController"},{name:"component.create",url:"/create",params:{showPersistantData:!1,menuGuid:""},templateUrl:"app/component/views/editComponent.html",controller:"ComponentController",excludeFromHistory:!0},{name:"person",url:"/person",abstract:!0,template:""},{name:"person.list",availableWebMenu:"Personliste",filters:personListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/person/views/listPerson.html",controller:"ListController",params:{entityData:apiData.person}},{name:"person.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/person/views/editPerson.html",controller:"PersonController"},{name:"person.create",url:"/create",params:{menuGuid:""},templateUrl:"app/person/views/editPerson.html",controller:"PersonController",excludeFromHistory:!0},{name:"supplier",url:"/supplier",abstract:!0,template:""},{name:"supplier.list",availableWebMenu:"Leverandørliste",filters:supplierListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/supplier/views/listSupplier.html",controller:"ListController",params:{entityData:apiData.supplier}},{name:"supplier.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/supplier/views/editSupplier.html",controller:"SupplierController"},{name:"supplier.create",url:"/create",params:{menuGuid:""},templateUrl:"app/supplier/views/editSupplier.html",controller:"SupplierController",excludeFromHistory:!0},{name:"supplierAgreement",url:"/supplierAgreement",abstract:!0,template:""},{name:"supplierAgreement.list",availableWebMenu:"LeverandørAvtaleliste",url:"/list/:menuGuid??filter",templateUrl:"app/supplierAgreement/views/listSupplierAgreement.html",controller:"ListController",params:{entityData:apiData.supplierAgreement}},{name:"supplierAgreement.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/supplierAgreement/views/editSupplierAgreement.html",controller:"SupplierAgreementController"},{name:"supplierAgreement.create",url:"/create",params:{menuGuid:""},templateUrl:"app/supplierAgreement/views/editSupplierAgreement.html",controller:"SupplierAgreementController",excludeFromHistory:!0},{name:"contactPerson",url:"/contactPerson",abstract:!0,template:""},{name:"contactPerson.list",availableWebMenu:"",url:"/list/:menuGuid??filter",templateUrl:"app/contactPerson/views/listContactPerson.html",controller:"ListController",params:{entityData:apiData.contactPerson}},{name:"contactPerson.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/contactPerson/views/editContactPerson.html",controller:"ContactPersonController"},{name:"contactPerson.create",url:"/create",params:{menuGuid:""},templateUrl:"app/contactPerson/views/editContactPerson.html",controller:"ContactPersonController",excludeFromHistory:!0},{name:"area",url:"/area",abstract:!0,template:""},{name:"area.list",availableWebMenu:"Romliste",filters:areaListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/area/views/listArea.html",controller:"ListController",params:{entityData:apiData.area}},{name:"area.edit",url:"/edit/:guid",params:{menuGuid:"",model:null},templateUrl:"app/area/views/editArea.html",controller:"AreaController"},{name:"area.create",url:"/create",params:{showPersistantData:!1,menuGuid:""},templateUrl:"app/area/views/editArea.html",controller:"AreaController",excludeFromHistory:!0},{name:"periodicTask",url:"/periodicTask",abstract:!0,template:""},{name:"periodicTask.list",availableWebMenu:"Periodisk rutineliste",filters:periodicTaskListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/periodicTask/views/listPeriodicTask.html",controller:"ListController",params:{entityData:apiData.periodicTask}},{name:"periodicTask.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/periodicTask/views/editPeriodicTask.html",controller:"PeriodicTaskController"},{name:"periodicTask.create",url:"/create",params:{showPersistantData:!1,menuGuid:"",guidEntityToCopy:""},templateUrl:"app/periodicTask/views/editPeriodicTask.html",controller:"PeriodicTaskController",excludeFromHistory:!0},{name:"periodicTaskTemplate",url:"/periodicTaskTemplate",abstract:!0,template:""},{name:"periodicTaskTemplate.list",availableWebMenu:"Periodisk malrutineliste",filters:periodicTaskListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/periodicTask/views/listPeriodicTask.html",controller:"ListController",params:{entityData:apiData.periodicTaskTemplate}},{name:"document",url:"/document",abstract:!0,template:""},{name:"document.list",availableWebMenu:"Dokumentliste",filters:documentListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/document/views/listDocument.html",controller:"ListController",params:{entityData:apiData.document}},{name:"document.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/document/views/editDocumentMetadata.html",controller:"EditDocumentController"},{name:"document.viewPdf",availableWebMenu:"PDF dokument",filters:viewPdfFilter,url:"/viewPdf/:menuGuid",templateUrl:"app/document/views/viewPdfDocument.html",controller:"ViewPdfDocumentController",excludeFromHistory:!0},{name:"document.dataAcquisitionMatrix",availableWebMenu:"Datafangst dokument informasjonstype matrise",filters:documentXEntityListFilter,url:"/dataacquisition/matrix/:menuGuid??filter",templateUrl:"app/document/dataAcquisition/documentDataAcquisitionMatrix.html",controller:"DocumentDataAcquisitionMatrixController",params:{entityData:apiData.documentDataAcquisitionMatrix}},{name:"document.dataAcquisitionList",availableWebMenu:"Datafangst dokument anlegg trestruktur",filters:documentXEntityListFilter,url:"/dataacquisition/listview/:menuGuid??filter",templateUrl:"app/document/dataAcquisition/documentDataAcquisitionListView.html",controller:"ListController",params:{entityData:apiData.documentDataAcquisitionListView}},{name:"document.dataAcquisitionUpload",url:"/dataacquisition/upload",templateUrl:"app/document/dataAcquisition/documentDataAcquisitionUpload.html",controller:"DocumentDataAcquisitionUploadController",params:{entityData:apiData.documentDataAcquisitionUpload}},{name:"documentXEntity",url:"/documentXEntity",abstract:!0,template:""},{name:"documentXEntity.list",availableWebMenu:"Dokument referanser",filters:documentXEntityListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/documentXEntity/views/listDocumentXEntity.html",controller:"ListController",params:{entityData:apiData.documentXEntity}},{name:"documentXEntity.archiveList",availableWebMenu:"Dokument arkivbehandling",filters:documentXEntityListFilter,url:"/documentArchiveList/:menuGuid??filter",templateUrl:"app/documentXEntity/documentArchive/archiveList.html",controller:"ArchiveListController",backNavigation:!0,params:{entityData:apiData.documentXEntity}},{name:"image",url:"/image",abstract:!0,template:""},{name:"image.list",availableWebMenu:"Bildeliste",filters:imageListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/image/views/listImage.html",controller:"ListController",params:{entityData:apiData.image}},{name:"imageXEntity",url:"/imageXEntity",abstract:!0,template:""},{name:"imageXEntity.list",availableWebMenu:"Bildereferanser",filters:imageXEntityListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/imageXEntity/views/listImageXEntity.html",controller:"ListController",params:{entityData:apiData.imageXEntity}},{name:"buildingSelection",url:"/buildingSelection",abstract:!0,template:""},{name:"buildingSelection.list",availableWebMenu:"Utvalgsliste",filters:buildingselectionListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/buildingSelection/views/listBuildingSelection.html",controller:"ListController",params:{entityData:apiData.buildingSelection}},{name:"buildingSelection.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/buildingSelection/views/buildingSelection.html",controller:"BuildingSelectionController"},{name:"buildingSelection.create",url:"/create",params:{menuGuid:""},templateUrl:"app/buildingSelection/views/buildingSelection.html",controller:"BuildingSelectionController",excludeFromHistory:!0},{name:"deviation",url:"/deviation",abstract:!0,template:""},{name:"deviation.list",availableWebMenu:"Avviksliste",filters:deviationListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/deviation/views/listDeviation.html",controller:"ListController",params:{entityData:apiData.deviation}},{name:"deviation.create",url:"/create/:menuGuid??filter",params:{entityData:apiData.deviation,menuGuid:""},templateUrl:"app/deviation/views/editDeviation.html",controller:"DeviationController",excludeFromHistory:!0,resolve:{$modalInstance:function(){return null}}},{name:"deviation.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/deviation/views/editDeviation.html",controller:"DeviationController",resolve:{$modalInstance:function(){return null}}},{name:"request",url:"/request",abstract:!0,template:""},{name:"request.list",availableWebMenu:"Meldingsliste",filters:requestListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/request/views/listRequest.html",controller:"ListController",params:{entityData:apiData.request}},{name:"request.create",availableWebMenu:"Ny Melding",filters:newRequestFilter,url:"/create/:menuGuid?",params:{entityData:apiData.request,menuGuid:"",showPersistantData:!1},excludeFromHistory:!0,templateUrl:"app/request/views/editRequest.html",controller:"RequestController"},{name:"request.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/request/views/editRequest.html",controller:"RequestController"},{name:"userXExternalLogin",url:"/userXExternalLogin",abstract:!0,template:""},{name:"userXExternalLogin.list",availableWebMenu:"Bruker/Ekstern innlogging liste",url:"/list/:menuGuid??filter",templateUrl:"app/userXExternalLogin/views/listUserXExternalLogin.html",controller:"ListController",params:{entityData:apiData.userXExternalLogin}},{name:"userXWebProfile",url:"/userXWebProfile",abstract:!0,template:""},{name:"userXWebProfile.list",availableWebMenu:"Brukerwebprofil liste",filters:userXWebProfileListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/user/views/listUserWebProfile.html",controller:"ListController",params:{entityData:apiData.userXWebProfile}},{name:"webProfile",url:"/webProfile",abstract:!0,template:""},{name:"webProfile.list",availableWebMenu:"Webprofil liste",filters:webProfileListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/webProfile/views/listWebProfile.html",controller:"ListController",params:{entityData:apiData.webProfile}},{name:"webProfile.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/webProfile/views/editWebProfile.html",controller:"WebProfileController"},{name:"webProfile.create",url:"/create",params:{menuGuid:""},templateUrl:"app/webProfile/views/editWebProfile.html",controller:"WebProfileController",excludeFromHistory:!0},{name:"webMenu",url:"/webMenu",abstract:!0,template:""},{name:"webMenu.list",availableWebMenu:"Webmenyliste",filters:webmenuListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/webMenu/views/listWebMenu.html",controller:"ListController",params:{entityData:apiData.webMenu}},{name:"webMenu.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/webMenu/views/editWebMenu.html",controller:"WebMenuController"},{name:"webMenu.create",url:"/create",params:{menuGuid:"",guidEntityToCopy:""},templateUrl:"app/webMenu/views/editWebMenu.html",controller:"WebMenuController",excludeFromHistory:!0},{name:"report",url:"/report",abstract:!0,template:""},{name:"report.view",availableWebMenu:"Rapport",filters:telerikReportFilter,url:"/view/:menuGuid??filter",templateUrl:"app/report/views/telerik.html",controller:"TelerikController"},{name:"report.print",url:"/print/:reportName?/:reportParams?",templateUrl:"app/report/views/telerik.html",controller:"PrintReportController",excludeFromHistory:!0},{name:"report.list",url:"/list/:menuGuid??filter",templateUrl:"app/report/views/listReport.html",controller:"ListController",params:{entityData:apiData.report}},{name:"navigation",url:"/navigation",abstract:!0,template:""},{name:"navigation.view",url:"/view",params:{menuGuid:""},template:""},{name:"map",url:"/map",abstract:!0,template:"",reloadOnSearch:!1},{name:"map.view",url:"/view",availableWebMenu:"Kart",filters:mapFilter,templateUrl:"app/map/views/map.html",controller:"MapController",params:{},reloadOnSearch:!1},{name:"gisEntity",url:"/gisEntity",abstract:!0,template:""},{name:"gisEntity.list",availableWebMenu:"",filters:deviationListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/map/views/listGisEntity.html",controller:"ListController",params:{entityData:apiData.gisEntity}},{name:"planiasystem",url:"/planiasystem",abstract:!0,template:""},{name:"planiasystem.ps",url:"/ps",template:""},{name:"admin",url:"/admin",abstract:!0,template:""},{name:"admin.dashboard",url:"/view",availableWebMenu:"Administrasjon",template:""},{name:"controlList",url:"/controlList",abstract:!0,template:""},{name:"controlList.list",availableWebMenu:"Kontrollister",filters:controlListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/controlList/views/listControlList.html",controller:"ListController",params:{entityData:apiData.controlList}},{name:"controlList.edit",url:"/edit/:guid",params:{menuGuid:"",tab:""},templateUrl:"app/controlList/views/editControlList.html",controller:"ControlListController"},{name:"controlList.create",url:"/create",params:{menuGuid:"",guidEntityToCopy:""},templateUrl:"app/controlList/views/editControlList.html",controller:"ControlListController",excludeFromHistory:!0},{name:"controlListItemAnswer",url:"/controlListItemAnswer",abstract:!0,template:""},{name:"controlListItemAnswer.list",availableWebMenu:"Kontrollistesvar",filters:controlListItemAnswerFilter,url:"/list/:menuGuid??filter",templateUrl:"app/controlList/views/listControlListItemAnswer.html",controller:"ListController",params:{entityData:apiData.controlListItemAnswer}},{name:"completedControlLists",url:"/completedControlLists",abstract:!0,template:""},{name:"completedControlLists.list",availableWebMenu:"Utfylte kontrollister",filters:controlListXEntityFilter,url:"/list/:menuGuid??filter",templateUrl:"app/controlList/views/listCompletedControlList.html",controller:"ListController",params:{entityData:apiData.controlListXEntity}},{name:"cleaning",url:"/cleaning",abstract:!0,template:""},{name:"cleaning.list",availableWebMenu:"Renholdsliste",filters:cleaningListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/cleaning/views/listCleaning.html",controller:"ListController",params:{entityData:apiData.areaXCleaningTask}},{name:"cleaning.area",url:"/area",abstract:!0,template:""},{name:"cleaning.area.list",availableWebMenu:"Romliste renhold",filters:areaListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/area/views/listArea.html",controller:"ListController",backNavigation:!0,params:{entityData:apiData.area}},{name:"cleaning.dwg",url:"/dwg",abstract:!0,template:""},{name:"cleaning.dwg.list",availableWebMenu:"Tegning renhold",filters:drawingFilter,url:"/list/:menuGuid??filter",templateUrl:"app/dwg/views/listDrawing.html",controller:"ListController",backNavigation:!0,params:{entityData:apiData.drawing}},{name:"cleaning.resourceGroup",url:"/resourceGroup",abstract:!0,template:""},{name:"cleaning.resourceGroup.list",url:"/list/:menuGuid??filter",templateUrl:"app/resourceGroup/views/listResourceGroup.html",controller:"ListController",params:{entityData:apiData.resourceGroup}},{name:"cleaningTask",url:"/cleaningTask",abstract:!0,template:""},{name:"cleaningTask.list",url:"/list/:menuGuid??filter",availableWebMenu:"Renholdsoppgaver",templateUrl:"app/cleaningTask/views/listCleaningTask.html",controller:"ListController",params:{entityData:apiData.cleaningTask}},{name:"cleaningTask.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/cleaningTask/views/cleaningTask.html",controller:"CleaningTaskController"},{name:"cleaningTask.create",url:"/create",params:{showPersistantData:!1,menuGuid:""},templateUrl:"app/cleaningTask/views/cleaningTaskWizard.html",controller:"CleaningTaskWizardController",excludeFromHistory:!0},{name:"cleaningQuality",url:"/cleaningQuality",abstract:!0,template:""},{name:"cleaningQuality.list",url:"/list/:menuGuid??filter",availableWebMenu:"Renholdskvaliteter",templateUrl:"app/cleaningQuality/views/listCleaningQuality.html",controller:"ListController",params:{entityData:apiData.cleaningQuality}},{name:"cleaningQuality.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/cleaningQuality/views/cleaningQuality.html",controller:"CleaningQualityController"},{name:"cleaningQuality.create",url:"/create",params:{menuGuid:""},templateUrl:"app/cleaningQuality/views/cleaningQuality.html",controller:"CleaningQualityController",excludeFromHistory:!0},{name:"cleaningQualityControl",url:"/cleaningQualityControl",abstract:!0,template:""},{name:"cleaningQualityControl.list",availableWebMenu:"INSTA-kontroll",filters:cleaningQualityControlListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/cleaningQualityControl/views/listCleaningQualityControl.html",controller:"ListController",params:{entityData:apiData.cleaningQualityControl}},{name:"cleaningQualityControl.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/cleaningQualityControl/views/cleaningQualityControl.html",controller:"CleaningQualityControlController"},{name:"cleaningQualityControl.create",url:"/create",params:{menuGuid:""},templateUrl:"app/cleaningQualityControl/views/cleaningQualityControl.html",controller:"CleaningQualityControlController",excludeFromHistory:!0},{name:"cleaningCompletion",url:"/cleaningCompletion",abstract:!0,template:""},{name:"cleaningCompletion.list",availableWebMenu:"Aktivitetsoversikt",url:"/list/:menuGuid??filter",templateUrl:"app/cleaningCompletion/views/listCleaningCompletion.html",controller:"ListController",params:{entityData:apiData.cleaningCompletion}},{name:"cleaningCompletion.overview",url:"/overview",templateUrl:"app/cleaningCompletion/views/cleaningCompletionOverview.html",controller:"CleaningCompletionOverviewController",params:{menuGuid:""}},{name:"dwg",url:"/dwg",abstract:!0,template:""},{name:"dwg.view",url:"/view/:guid",templateUrl:"app/dwg/views/dwg.html",controller:"DwgController",params:{theme:null,guidQualityControl:null,menuGuid:"",guidArea:null,selectedTheme:null}},{name:"dwg.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"dwg.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"dwg.list",availableWebMenu:"Tegning",filters:drawingFilter,url:"/list/:menuGuid??filter",templateUrl:"app/dwg/views/listDrawing.html",controller:"ListController",params:{entityData:apiData.drawing}},{name:"bimFile",url:"/bimFile",abstract:!0,template:""},{name:"bimFile.edit",url:"/edit/:guid",templateUrl:"app/bimFile/views/editBimFile.html",controller:"BimFileController"},{name:"bimFile.list",url:"/list/:menuGuid??filter",availableWebMenu:"Bim filliste",templateUrl:"app/bimFile/views/listBimFile.html",controller:"ListController",params:{entityData:apiData.bimFile}},{name:"bimFile.viewBim",url:"/viewBim?guidEstate&guidRequest&guidBimProject&guidBuilding&guidArea&guidBimFile&guidEquipment&nonsReferencePath",template:"",reloadOnSearch:!1,params:{entityData:apiData.bimFile,guidEstate:null,guidBimProject:null,guidBuilding:null,guidArea:null,guidBimFile:null,guidEquipment:null,nonsReferencePath:null,guidRequest:null}},{name:"bimProjects",url:"/bimProjects",template:""},{name:"bcfProject",url:"/bcfProject",abstract:!0,template:""},{name:"bcfProject.list",availableWebMenu:"Bcf prosjekt liste",url:"/list/:menuGuid??filter",templateUrl:"app/bcfProject/views/listBcfProject.html",controller:"ListController",params:{entityData:apiData.bcfProject}},{name:"bcfProject.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"bcfProject.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"usergroup",url:"/usergroup",abstract:!0,template:""},{name:"usergroup.list",availableWebMenu:"Brukergruppe",filters:userListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/usergroup/views/listusergroups.html",controller:"ListController",params:{entityData:apiData.userGroup}},{name:"usergroup.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/usergroup/views/editUserGroup.html",controller:"UserGroupController"},{name:"usergroup.create",url:"/create",params:{menuGuid:""},templateUrl:"app/usergroup/views/editUserGroup.html",controller:"UserGroupController",excludeFromHistory:!0},{name:"dataImport",url:"/dataImport",abstract:!0,template:""},{name:"dataImport.list",availableWebMenu:"Dataimport",url:"/list/:menuGuid??filter",templateUrl:"app/dataImport/views/listDataImport.html",controller:"ListController",params:{entityData:apiData.dataImport}},{name:"dataImport.create",url:"/create",params:{menuGuid:"",guidEntityToCopy:""},templateUrl:"app/dataImport/views/createDataImport.html",controller:"CreateDataImportController"},{name:"dataImport.edit",url:"/edit/:guid",params:{menuGuid:"",guidEntityToCopy:""},templateUrl:"app/dataImport/views/editDataImport.html",controller:"DataImportController"},{name:"dataImport.bim",url:"/bim/edit/:guid",params:{menuGuid:"",guidEntityToCopy:""},templateUrl:"app/dataImport/views/editBimDataImport.html",controller:"DataBimImportController"},{name:"dataOwner",url:"/dataOwner",abstract:!0,template:""},{name:"dataOwner.list",url:"/list/:menuGuid??filter",availableWebMenu:"Klient",filters:dataOwnerListFilter,templateUrl:"app/dataOwner/views/listDataOwner.html",controller:"ListController",params:{entityData:apiData.dataOwner}},{name:"dataOwner.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/dataOwner/views/editDataOwner.html",controller:"DataOwnerController"},{name:"dataOwner.create",url:"/create",params:{menuGuid:""},templateUrl:"app/dataOwner/views/editDataOwner.html",controller:"DataOwnerController",excludeFromHistory:!0},{name:"generalOptions",url:"/generalOptions",templateUrl:"app/generalOptions/views/generalOptions.html",controller:"GeneralOptionsController"},{name:"registeredFields",url:"/registeredFields",templateUrl:"app/registeredFields/registeredFields.html",controller:"RegisteredFieldsController"},{name:"entityPermissionProfile",url:"/entityPermissionProfile",abstract:!0,template:""},{name:"entityPermissionProfile.list",url:"/list/:menuGuid??filter",templateUrl:"app/entityPermissionProfile/listEntityPermissionProfile.html",controller:"ListController",params:{entityData:apiData.entityPermissionProfile}},{name:"entityPermissionProfile.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"entityPermissionProfile.create",url:"/create",params:{menuGuid:"",guidEntityToCopy:""},template:"",excludeFromHistory:!0},{name:"translation",url:"/translation",abstract:!0,template:""},{name:"translation.list",url:"/list/:menuGuid??filter",availableWebMenu:"Oversettelser",filters:translationListFilter,templateUrl:"app/translation/views/listTranslations.html",controller:"TranslationListController",params:{entityData:apiData.translate}},{name:"translation.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/translation/views/editTranslation.html",controller:"TranslationController"},{name:"log",url:"/log",abstract:!0,template:""},{name:"log.list",url:"/list/:menuGuid??filter",availableWebMenu:"Log",filters:dataOwnerListFilter,templateUrl:"app/log/views/listLog.html",controller:"ListController",params:{entityData:apiData.log}},{name:"log.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/log/views/editLog.html",controller:"LogController",excludeFromHistory:!0},{name:"conditionType",url:"/conditionType",abstract:!0,template:""},{name:"conditionType.list",url:"/list/:menuGuid??filter",templateUrl:"app/conditionType/views/listConditionType.html",controller:"ListController",params:{entityData:apiData.conditionType}},{name:"conditionType.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/conditionType/views/editConditionType.html",controller:"ConditionTypeController"},{name:"conditionType.create",url:"/create",params:{menuGuid:""},templateUrl:"app/conditionType/views/editConditionType.html",controller:"ConditionTypeController",excludeFromHistory:!0},{name:"deviationType",url:"/deviationType",abstract:!0,template:""},{name:"deviationType.list",url:"/list/:menuGuid??filter",templateUrl:"app/deviationType/views/listDeviationType.html",controller:"ListController",params:{entityData:apiData.deviationType}},{name:"deviationType.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/deviationType/views/editDeviationType.html",controller:"DeviationTypeController"},{name:"deviationType.create",url:"/create",params:{menuGuid:""},templateUrl:"app/deviationType/views/editDeviationType.html",controller:"DeviationTypeController",excludeFromHistory:!0},{name:"activityGroup",url:"/activityGroup",abstract:!0,template:""},{name:"activityGroup.list",url:"/list/:menuGuid??filter", templateUrl:"app/activityGroup/views/listActivityGroup.html",controller:"ListController",params:{entityData:apiData.activityGroup}},{name:"activityGroup.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"activityGroup.create",url:"/create",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController",excludeFromHistory:!0},{name:"personRole",url:"/personRole",abstract:!0,template:""},{name:"personRole.list",url:"/list/:menuGuid??filter",templateUrl:"app/personRole/views/listPersonRole.html",controller:"ListController",params:{entityData:apiData.personRole}},{name:"personRole.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/personRole/views/editPersonRole.html",controller:"PersonRoleController"},{name:"personRole.create",url:"/create",params:{menuGuid:""},templateUrl:"app/personRole/views/editPersonRole.html",controller:"PersonRoleController",excludeFromHistory:!0},{name:"priority",url:"/priority",abstract:!0,template:""},{name:"priority.list",url:"/list/:menuGuid??filter",templateUrl:"app/priority/views/listPriority.html",controller:"ListController",params:{entityData:apiData.priority}},{name:"priority.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/priority/views/priority.html",controller:"PriorityController"},{name:"priority.create",url:"/create",params:{menuGuid:""},templateUrl:"app/priority/views/priority.html",controller:"PriorityController",excludeFromHistory:!0},{name:"project",url:"/project",abstract:!0,template:""},{name:"project.list",availableWebMenu:"Prosjektliste",filters:projectListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/project/views/listProject.html",controller:"ListController",params:{entityData:apiData.project}},{name:"project.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/project/views/project.html",controller:"ProjectController"},{name:"project.editPhase",url:"/phase/edit/:guid",params:{menuGuid:""},templateUrl:"app/project/views/projectPhaseSetup.html",controller:"ProjectPhaseSetupController",excludeFromHistory:!0},{name:"project.create",url:"/create",params:{menuGuid:""},templateUrl:"app/project/views/createProject.html",controller:"CreateProjectController",excludeFromHistory:!0},{name:"projectTemplate",url:"/projectTemplate",abstract:!0,template:""},{name:"projectTemplate.list",availableWebMenu:"Prosjektmalliste",filters:projectListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/projectTemplate/views/listProjectTemplate.html",controller:"ListController",params:{entityData:apiData.projectTemplate}},{name:"projectTemplate.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/project/views/project.html",controller:"ProjectController"},{name:"projectTemplate.create",url:"/create",params:{menuGuid:""},templateUrl:"app/projectTemplate/views/createProjectTemplate.html",controller:"CreateProjectTemplateController",excludeFromHistory:!0},{name:"projectCategory",url:"/projectCategory",abstract:!0,template:""},{name:"projectCategory.list",url:"/list/:menuGuid??filter",templateUrl:"app/projectCategory/views/listProjectCategory.html",controller:"ListController",params:{entityData:apiData.projectCategory}},{name:"projectCategory.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"projectCategory.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"equipmentCategory",url:"/equipmentCategory",abstract:!0,template:""},{name:"equipmentCategory.list",url:"/list/:menuGuid??filter",templateUrl:"app/equipmentCategory/views/listEquipmentCategory.html",controller:"ListController",params:{entityData:apiData.equipmentCategory}},{name:"equipmentCategory.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"equipmentCategory.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"buildingCategory",url:"/buildingCategory",abstract:!0,template:""},{name:"buildingCategory.list",url:"/list/:menuGuid??filter",templateUrl:"app/buildingCategory/views/listBuildingCategory.html",controller:"ListController",params:{entityData:apiData.buildingCategory}},{name:"buildingCategory.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"buildingCategory.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"estateCategory",url:"/estateCategory",abstract:!0,template:""},{name:"estateCategory.list",url:"/list/:menuGuid??filter",templateUrl:"app/estateCategory/views/listEstateCategory.html",controller:"ListController",params:{entityData:apiData.estateCategory}},{name:"estateCategory.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"estateCategory.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"areaCategory",url:"/areaCategory",abstract:!0,template:""},{name:"areaCategory.list",url:"/list/:menuGuid??filter",templateUrl:"app/areaCategory/views/listAreaCategory.html",controller:"ListController",params:{entityData:apiData.areaCategory}},{name:"areaCategory.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"areaCategory.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"componentCategory",url:"/componentCategory",abstract:!0,template:""},{name:"componentCategory.list",url:"/list/:menuGuid??filter",templateUrl:"app/componentCategory/views/listComponentCategory.html",controller:"ListController",params:{entityData:apiData.componentCategory}},{name:"componentCategory.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"componentCategory.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"activityCategory",url:"/activityCategory",abstract:!0,template:""},{name:"activityCategory.list",url:"/list/:menuGuid??filter",templateUrl:"app/activityCategory/views/listActivityCategory.html",controller:"ListController",params:{entityData:apiData.activityCategory}},{name:"activityCategory.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"activityCategory.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"projectType",url:"/projectType",abstract:!0,template:""},{name:"projectType.list",url:"/list/:menuGuid??filter",templateUrl:"app/projectType/views/listProjectType.html",controller:"ListController",params:{entityData:apiData.projectType}},{name:"projectType.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"projectType.create",url:"/create",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController",excludeFromHistory:!0},{name:"purchaseOrder",url:"/purchaseOrder",abstract:!0,template:""},{name:"purchaseOrder.list",availableWebMenu:"Bestillingsliste",filters:purchaseOrderFilter,url:"/list/:menuGuid??filter",templateUrl:"app/purchaseOrder/views/listPurchaseOrder.html",controller:"ListController",params:{entityData:apiData.purchaseOrder}},{name:"purchaseOrder.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/purchaseOrder/views/purchaseOrder.html",controller:"PurchaseOrderController"},{name:"purchaseOrder.create",url:"/create",params:{menuGuid:""},templateUrl:"app/purchaseOrder/views/purchaseOrder.html",controller:"PurchaseOrderController",excludeFromHistory:!0},{name:"purchaseOrderForm",url:"/purchaseOrderForm",abstract:!0,template:""},{name:"purchaseOrderForm.list",url:"/list/:menuGuid??filter",templateUrl:"app/purchaseOrderForm/views/listPurchaseOrderForm.html",controller:"ListController",params:{entityData:apiData.purchaseOrderForm}},{name:"purchaseOrderForm.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/purchaseOrderForm/views/purchaseOrderForm.html",controller:"PurchaseOrderFormController"},{name:"purchaseOrderForm.create",url:"/create",params:{menuGuid:""},templateUrl:"app/purchaseOrderForm/views/purchaseOrderForm.html",controller:"PurchaseOrderFormController",excludeFromHistory:!0},{name:"purchaseOrderItem",url:"/purchaseOrderItem",abstract:!0,template:""},{name:"purchaseOrderItem.list",url:"/list/:menuGuid??filter",templateUrl:"app/purchaseOrder/views/listPurchaseOrderItem.html",controller:"ListController",params:{entityData:apiData.purchaseOrderItem}},{name:"purchaseOrderItem.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/purchaseOrder/views/purchaseOrderItem.html",controller:"PurchaseOrderItemController"},{name:"purchaseOrderItem.create",url:"/create",params:{menuGuid:""},templateUrl:"app/purchaseOrder/views/purchaseOrderItem.html",controller:"PurchaseOrderItemController",excludeFromHistory:!0},{name:"deliveryTerm",url:"/deliveryTerm",abstract:!0,template:""},{name:"deliveryTerm.list",url:"/list/:menuGuid??filter",templateUrl:"app/deliveryTerm/views/listDeliveryTerm.html",controller:"ListController",params:{entityData:apiData.deliveryTerm}},{name:"consequenceType",url:"/consequenceType",abstract:!0,template:""},{name:"consequenceType.list",url:"/list/:menuGuid??filter",templateUrl:"app/consequenceType/views/listConsequenceType.html",controller:"ListController",params:{entityData:apiData.consequenceType}},{name:"consequenceType.edit",url:"/edit/:guid",params:{menuGuid:"",hasDescription:!0},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"consequenceType.create",url:"/create",params:{menuGuid:"",hasDescription:!0},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController",excludeFromHistory:!0},{name:"consequence",url:"/consequence",abstract:!0,template:""},{name:"consequence.list",url:"/list/:menuGuid??filter",templateUrl:"app/consequence/views/listConsequence.html",controller:"ListController",params:{entityData:apiData.consequence}},{name:"consequence.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/consequence/views/editConsequence.html",controller:"ConsequenceController"},{name:"consequence.create",url:"/create",params:{menuGuid:""},templateUrl:"app/consequence/views/editConsequence.html",controller:"ConsequenceController",excludeFromHistory:!0},{name:"cylinderType",url:"/cylinderType",abstract:!0,template:""},{name:"cylinderType.list",url:"/list/:menuGuid??filter",templateUrl:"app/common/views/simpleListWrapper.html",controller:"ListController",params:{entityData:apiData.cylinderType}},{name:"cylinderType.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"cylinderType.create",url:"/create",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController",excludeFromHistory:!0},{name:"hourType",url:"/hourType",abstract:!0,template:""},{name:"hourType.list",url:"/list/:menuGuid??filter",templateUrl:"app/hourType/views/listHourType.html",controller:"ListController",params:{entityData:apiData.hourType}},{name:"hourType.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/hourType/views/editHourType.html",controller:"HourTypeController"},{name:"hourType.create",url:"/create",params:{menuGuid:""},templateUrl:"app/hourType/views/editHourType.html",controller:"HourTypeController",excludeFromHistory:!0},{name:"alarm",url:"/alarm",abstract:!0,template:""},{name:"alarm.list",url:"/list/:menuGuid??filter",templateUrl:"app/alarm/listAlarm.html",controller:"ListController",params:{entityData:apiData.alarm}},{name:"alarm.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"alarm.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"alarmLog",url:"/alarmLog",abstract:!0,template:""},{name:"alarmLog.list",url:"/list/:menuGuid??filter",templateUrl:"app/alarmLog/views/listAlarmLog.html",controller:"ListController",params:{entityData:apiData.alarmLog}},{name:"alarmLog.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/alarmLog/views/alarmLog.html",controller:"AlarmLogController"},{name:"alarmLog.create",url:"/create",params:{menuGuid:""},templateUrl:"app/alarmLog/views/alarmLog.html",controller:"AlarmLogController",excludeFromHistory:!0},{name:"account",url:"/account",abstract:!0,template:""},{name:"account.list",availableWebMenu:"Konto liste",url:"/list/:menuGuid??filter",templateUrl:"app/account/views/listAccount.html",controller:"ListController",params:{entityData:apiData.account}},{name:"account.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/account/views/editAccount.html",controller:"AccountController"},{name:"account.create",url:"/create",params:{menuGuid:""},templateUrl:"app/account/views/editAccount.html",controller:"AccountController",excludeFromHistory:!0},{name:"costCenter",url:"/costCenter",abstract:!0,template:""},{name:"costCenter.list",availableWebMenu:"Koststedliste",url:"/list/:menuGuid??filter",templateUrl:"app/costCenter/views/listCostCenter.html",controller:"ListController",params:{entityData:apiData.costCenter}},{name:"costCenter.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/costCenter/views/editCostCenter.html",controller:"SimpleGenericFormController"},{name:"costCenter.create",url:"/create",params:{menuGuid:""},templateUrl:"app/costCenter/views/editCostCenter.html",controller:"SimpleGenericFormController",excludeFromHistory:!0},{name:"department",url:"/department",abstract:!0,template:""},{name:"department.list",availableWebMenu:"Avdelingsliste",url:"/list/:menuGuid??filter",templateUrl:"app/department/views/listDepartment.html",controller:"ListController",params:{entityData:apiData.department}},{name:"department.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/department/views/editDepartment.html",controller:"DepartmentController"},{name:"department.create",url:"/create",params:{menuGuid:""},templateUrl:"app/department/views/editDepartment.html",controller:"DepartmentController",excludeFromHistory:!0},{name:"standardText",url:"/standardText",abstract:!0,template:""},{name:"standardText.list",url:"/list/:menuGuid??filter",templateUrl:"app/standardText/views/listStandardText.html",controller:"ListController",params:{entityData:apiData.standardText}},{name:"standardText.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/standardText/views/editStandardText.html",controller:"StandardTextController"},{name:"standardText.create",url:"/create",params:{menuGuid:""},templateUrl:"app/standardText/views/editStandardText.html",controller:"StandardTextController",excludeFromHistory:!0},{name:"contract",url:"/contract",abstract:!0,template:""},{name:"contract.list",availableWebMenu:"Kontraktlisteliste",filters:contractFilter,url:"/list/:menuGuid??filter",templateUrl:"app/contract/views/listContract.html",controller:"ListController",params:{entityData:apiData.contract}},{name:"contract.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/contract/views/editContract.html",controller:"ContractController"},{name:"contract.create",url:"/contract",params:{menuGuid:""},templateUrl:"app/contract/views/editContract.html",controller:"ContractController",excludeFromHistory:!0},{name:"housingContract",url:"/housingContract",abstract:!0,template:""},{name:"housingContract.list",filters:contractFilter,url:"/list/:menuGuid??filter",templateUrl:"app/contract/views/listHousingContract.html",controller:"ListController",backNavigation:!0,params:{entityData:apiData.housingContract}},{name:"housingContract.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/contract/views/editHousingContract.html",controller:"HousingContractController",backNavigation:!0},{name:"housingContract.create",url:"/contract",params:{menuGuid:""},templateUrl:"app/contract/views/editHousingContract.html",controller:"HousingContractController",backNavigation:!1,excludeFromHistory:!0},{name:"reinvoicingContract",url:"/reinvoicingContract",abstract:!0,template:""},{name:"reinvoicingContract.list",availableWebMenu:"Avtaleliste Viderefakturering",filters:contractFilter,url:"/list/:menuGuid??filter",templateUrl:"app/contract/views/listReinvoicingContract.html",controller:"ListController",backNavigation:!0,params:{entityData:apiData.reinvoicingContract}},{name:"reinvoicingContract.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/contract/views/editReinvoicingContract.html",controller:"ContractController",backNavigation:!0},{name:"reinvoicingContract.create",url:"/create",params:{menuGuid:""},templateUrl:"app/contract/views/editReinvoicingContract.html",controller:"ContractController",backNavigation:!1,excludeFromHistory:!0},{name:"contractItem",url:"/contractItem",abstract:!0,template:""},{name:"contractItem.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/contract/views/editContractItem.html",controller:"ContractItemController"},{name:"contractItem.create",url:"/contractItem",params:{menuGuid:""},templateUrl:"app/contractItem/views/editContractItem.html",controller:"ContractItemController",excludeFromHistory:!0},{name:"contractCategory",url:"/contractCategory",abstract:!0,template:""},{name:"contractCategory.list",availableWebMenu:"Kontrakt kategori liste",filters:contractFilter,url:"/list/:menuGuid??filter",templateUrl:"app/contractCategory/views/listContractCategory.html",controller:"ListController",params:{entityData:apiData.contractCategory}},{name:"contractCategory.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"contractCategory.create",url:"/contractCategory",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"contractType",url:"/contractType",abstract:!0,template:""},{name:"contractType.list",availableWebMenu:"Kontrakt type liste",filters:contractFilter,url:"/list/:menuGuid??filter",templateUrl:"app/contractType/views/listContractType.html",controller:"ListController",params:{entityData:apiData.contractType}},{name:"contractType.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/contractType/views/editContractType.html",controller:"ContractTypeController"},{name:"contractType.create",url:"/contractType",params:{menuGuid:""},templateUrl:"app/contractType/views/editContractType.html",controller:"ContractTypeController",excludeFromHistory:!0},{name:"invoicingTerm",url:"/invoicingTerm",abstract:!0,template:""},{name:"invoicingTerm.list",url:"/list/:menuGuid??filter",templateUrl:"app/invoicingTerm/views/listInvoicingTerm.html",controller:"ListController",params:{entityData:apiData.invoicingTerm}},{name:"invoicingTerm.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/invoicingTerm/views/editInvoicingTerm.html",controller:"InvoicingTermController"},{name:"invoicingTerm.create",url:"/create",params:{menuGuid:""},templateUrl:"app/invoicingTerm/views/editInvoicingTerm.html",controller:"InvoicingTermController",excludeFromHistory:!0},{name:"integrationData",url:"/integrationData",abstract:!0,template:""},{name:"integrationData.list",url:"/list/:menuGuid??filter",templateUrl:"app/integrationData/views/listIntegrationData.html",controller:"ListController",params:{entityData:apiData.integrationData}},{name:"integrationData.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/integrationData/views/editIntegrationData.html",controller:"IntegrationDataController"},{name:"paymentTerm",url:"/paymentTerm",abstract:!0,template:""},{name:"paymentTerm.list",url:"/list/:menuGuid??filter",templateUrl:"app/paymentTerm/views/listPaymentTerm.html",controller:"ListController",params:{entityData:apiData.paymentTerm}},{name:"paymentTerm.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/paymentTerm/views/editPaymentTerm.html",controller:"PaymentTermController"},{name:"paymentTerm.create",url:"/create",params:{menuGuid:""},templateUrl:"app/paymentTerm/views/editPaymentTerm.html",controller:"PaymentTermController",excludeFromHistory:!0},{name:"paymentOrderForm",url:"/paymentOrderForm",abstract:!0,template:""},{name:"paymentOrderForm.list",url:"/list/:menuGuid??filter",templateUrl:"app/paymentOrderForm/views/listpaymentOrderForm.html",controller:"ListController",params:{entityData:apiData.paymentOrderForm}},{name:"paymentOrderForm.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/paymentOrderForm/views/editPaymentOrderForm.html",controller:"PaymentOrderFormController"},{name:"paymentOrderForm.create",url:"/create",params:{menuGuid:""},templateUrl:"app/paymentOrderForm/views/editPaymentOrderForm.html",controller:"PaymentOrderFormController",excludeFromHistory:!0},{name:"customer",url:"/customer",abstract:!0,template:""},{name:"customer.list",availableWebMenu:"Kundeliste",filters:customerFilter,url:"/list/:menuGuid??filter",templateUrl:"app/customer/views/listCustomer.html",controller:"ListController",params:{entityData:apiData.customer}},{name:"customer.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"customer.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"customer.anonymizationDashboard",url:"/anonymizationDashboard",templateUrl:"app/customer/anonymization/dashboard/anonymizationDashboard.html",controller:"AnonymizationDashboardController"},{name:"customer.anonymizationConfiguration",url:"/anonymizationConfiguration",templateUrl:"app/customer/anonymization/configuration/anonymizationConfiguration.html",controller:"AnonymizationConfigurationController"},{name:"housingCustomer",url:"/housingCustomer",abstract:!0,template:""},{name:"housingCustomer.list",availableWebMenu:"Leietakerliste",filters:customerFilter,url:"/list/:menuGuid??filter",templateUrl:"app/customer/views/listHousingCustomer.html",controller:"ListController",params:{entityData:apiData.housingCustomer}},{name:"housingCustomer.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"housingCustomer.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"article",url:"/article",abstract:!0,template:""},{name:"article.list",availableWebMenu:"Artikkelliste",filters:articleListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/article/views/listArticle.html",controller:"ListController",params:{entityData:apiData.article}},{name:"article.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/article/views/editArticle.html",controller:"ArticleController"},{name:"article.create",url:"/create",params:{menuGuid:""},templateUrl:"app/article/views/editArticle.html",controller:"ArticleController",excludeFromHistory:!0},{name:"resourceGroup",url:"/resourceGroup",abstract:!0,template:""},{name:"resourceGroup.list",availableWebMenu:"Liste av ressursgrupper",url:"/list/:menuGuid??filter",templateUrl:"app/resourceGroup/views/listResourceGroup.html",controller:"ListController",params:{entityData:apiData.resourceGroup}},{name:"resourceGroup.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/resourceGroup/views/editResourceGroup.html",controller:"ResourceGroupController"},{name:"resourceGroup.create",url:"/create",params:{menuGuid:""},templateUrl:"app/resourceGroup/views/editResourceGroup.html",controller:"ResourceGroupController",excludeFromHistory:!0},{name:"condition",url:"/condition",abstract:!0,template:""},{name:"condition.list",availableWebMenu:"Tiltaksliste",filters:conditionListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/condition/views/listConditions.html",controller:"ListController",params:{entityData:apiData.condition}},{name:"condition.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/condition/views/editCondition.html",controller:"ConditionController",resolve:{$modalInstance:function(){return null}}},{name:"condition.create",url:"/create",params:{menuGuid:"",guidEntityToCopy:""},templateUrl:"app/condition/views/editCondition.html",controller:"ConditionController",excludeFromHistory:!0,resolve:{$modalInstance:function(){return null}}},{name:"accounting",url:"/accounting",abstract:!0,template:""},{name:"accounting.list",url:"/list/:menuGuid??filter",templateUrl:"app/accounting/views/listAccounting.html",controller:"ListAccountingController",params:{entityData:apiData.accounting}},{name:"namedSelection",url:"/namedSelection",abstract:!0,template:""},{name:"namedSelection.list",url:"/list/:menuGuid??filter",templateUrl:"app/namedSelection/listNamedSelection.html",controller:"ListController",params:{entityData:apiData.namedSelection}},{name:"namedSelection.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"namedSelection.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"equipmentOperatingHours",url:"/equipmentOperatingHours",abstract:!0,template:""},{name:"equipmentOperatingHours.list",availableWebMenu:"Driftstimer",filters:documentXEntityListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/equipmentOperatingHours/views/listEquipmentOperatingHours.html",controller:"ListController",params:{entityData:apiData.equipmentOperatingHours}},{name:"equipmentOperatingHourType",url:"/equipmentOperatingHourType",abstract:!0,template:""},{name:"equipmentOperatingHourType.list",availableWebMenu:"Driftstimetype liste",url:"/list/:menuGuid??filter",templateUrl:"app/equipmentOperatingHourType/views/listEquipmentOperatingHourType.html",controller:"ListController",params:{entityData:apiData.equipmentOperatingHourType}},{name:"equipmentOperatingHourType.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"equipmentOperatingHourType.create",url:"/create",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController",excludeFromHistory:!0},{name:"maintenancePlan",url:"/maintenancePlan??filter",availableWebMenu:"Vedlikeholdsplan",params:{menuGuid:""},templateUrl:"app/maintenancePlan/maintenancePlan.html",controller:"MaintenancePlanController"},{name:"cost",url:"/cost",abstract:!0,template:""},{name:"cost.list",availableWebMenu:"Kostnadsliste",filters:costListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/cost/views/listCosts.html",controller:"ListController",params:{entityData:apiData.cost}},{name:"cost.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/cost/views/cost.html",controller:"CostController"},{name:"cost.create",url:"/create",params:{showPersistantData:!1,menuGuid:""},templateUrl:"app/cost/views/cost.html",controller:"CostController",excludeFromHistory:!0},{name:"budget",url:"/budget",abstract:!0,template:""},{name:"budget.list",availableWebMenu:"Budsjettliste",filters:budgetListFilter,url:"/list/:menuGuid??filter",templateUrl:"app/budget/views/listBudget.html",controller:"ListController",params:{entityData:apiData.budget}},{name:"budget.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/budget/views/budget.html",controller:"BudgetController"},{name:"budget.create",url:"/create",params:{menuGuid:""},templateUrl:"app/budget/views/budget.html",controller:"BudgetController",excludeFromHistory:!0},{name:"documentCategory",url:"/documentCategory",abstract:!0,template:""},{name:"documentCategory.list",url:"/list/:menuGuid??filter",templateUrl:"app/documentCategory/views/listDocumentCategory.html",controller:"ListController",params:{entityData:apiData.documentCategory}},{name:"documentCategory.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"documentCategory.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"documentType",url:"/documentType",abstract:!0,template:""},{name:"documentType.list",url:"/list/:menuGuid??filter",templateUrl:"app/documentType/views/listDocumentType.html",controller:"ListController",params:{entityData:apiData.documentType}},{name:"documentType.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"documentType.create",url:"/create",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController",excludeFromHistory:!0},{name:"region",url:"/region",abstract:!0,template:""},{name:"region.list",url:"/list/:menuGuid??filter",templateUrl:"app/common/views/simpleListWrapper.html",controller:"ListController",params:{entityData:apiData.region}},{name:"region.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"region.create",url:"/create",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController",excludeFromHistory:!0},{name:"customerGroup",url:"/customerGroup",abstract:!0,template:""},{name:"customerGroup.list",url:"/list/:menuGuid??filter",templateUrl:"app/common/views/simpleListWrapper.html",controller:"ListController",params:{entityData:apiData.customerGroup}},{name:"customerGroup.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"customerGroup.create",url:"/create",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController",excludeFromHistory:!0},{name:"customerCategory",url:"/customerCategory",abstract:!0,template:""},{name:"customerCategory.list",availableWebMenu:"Kundekategorier",url:"/list/:menuGuid??filter",templateUrl:"app/common/views/simpleListWrapper.html",controller:"ListController",params:{entityData:apiData.customerCategory}},{name:"customerCategory.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"customerCategory.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"customerLineOfBusiness",url:"/customerLineOfBusiness",abstract:!0,template:""},{name:"customerLineOfBusiness.list",availableWebMenu:"Bransje (kunde)",url:"/list/:menuGuid??filter",templateUrl:"app/common/views/simpleListWrapper.html",controller:"ListController",params:{entityData:apiData.customerLineOfBusiness}},{name:"customerLineOfBusiness.edit",url:"/edit/:guid",params:{menuGuid:""}, templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"customerLineOfBusiness.create",url:"/create",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController",excludeFromHistory:!0},{name:"sparePart",url:"/sparePart",abstract:!0,template:""},{name:"sparePart.list",availableWebMenu:"Reservedeler",filters:sparePartFilter,url:"/list/:menuGuid??filter",templateUrl:"app/sparePart/views/listSpareParts.html",controller:"ListController",params:{entityData:apiData.sparePart}},{name:"sparePart.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/sparePart/views/editSpareParts.html",controller:"SparePartsController"},{name:"sparePart.create",url:"/create",params:{menuGuid:""},templateUrl:"app/sparePart/views/editSpareParts.html",controller:"SparePartsController",excludeFromHistory:!0},{name:"sparePartCounting",url:"/sparePartCounting",abstract:!0,template:""},{name:"sparePartCounting.list",availableWebMenu:"Varetellinger",filters:sparePartCountingFilter,url:"/list/:menuGuid??filter",templateUrl:"app/sparePartCounting/views/listSparePartCountings.html",controller:"ListController",params:{entityData:apiData.sparePartCounting}},{name:"sparePartCounting.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/sparePartCounting/views/sparePartCounting.html",controller:"SparePartCountingController"},{name:"sparePartCounting.create",url:"/create",params:{menuGuid:""},templateUrl:"app/sparePartCounting/views/sparePartCounting.html",controller:"SparePartCountingController",excludeFromHistory:!0},{name:"sparePartCountingItem",url:"/sparePartCountingItem",abstract:!0,template:""},{name:"sparePartCountingItem.list",availableWebMenu:"Lageravvik",url:"/list/:menuGuid??filter",templateUrl:"app/sparePartCountingItem/views/listSparePartCountingItems.html",controller:"ListController",params:{entityData:apiData.sparePartCountingItem}},{name:"sparePartWithdrawal",url:"/sparePartWithdrawal",abstract:!0,template:""},{name:"sparePartWithdrawal.list",availableWebMenu:"Uttakshistorikk",filters:sparePartWithdrawalFilter,url:"/list/:menuGuid??filter",templateUrl:"app/sparePartWithdrawal/views/listSparePartWithdrawal.html",controller:"ListController",params:{entityData:apiData.sparePartWithdrawal}},{name:"sparePartWithdrawal.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/sparePartWithdrawal/views/sparePartWithdrawal.html",controller:"SparePartWithdrawalController"},{name:"sparePartWithdrawal.create",url:"/create",params:{menuGuid:""},templateUrl:"app/sparePartWithdrawal/views/sparePartWithdrawal.html",controller:"SparePartWithdrawalController",excludeFromHistory:!0},{name:"mobileMenuProfile",url:"/mobileMenuProfile",abstract:!0,template:""},{name:"mobileMenuProfile.list",url:"/list/:menuGuid??filter",templateUrl:"app/mobileMenuProfile/views/listMobileMenuProfile.html",controller:"ListController",params:{entityData:apiData.mobileMenuProfile}},{name:"mobileMenuProfile.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"mobileMenuProfile.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"housing",url:"/housing",abstract:!0,template:""},{name:"housing.list",availableWebMenu:"Boligliste",filters:housingFilter,url:"/list/:menuGuid??filter",templateUrl:"app/housing/views/listHousing.html",controller:"ListController",params:{entityData:apiData.housing}},{name:"housing.edit",url:"/edit/:guid",params:{menuGuid:"",model:null},templateUrl:"app/housing/views/editHousing.html",controller:"HousingController"},{name:"housing.create",url:"/create",params:{guidEntityToCopy:"",menuGuid:""},templateUrl:"app/housing/views/editHousing.html",controller:"HousingController",excludeFromHistory:!0},{name:"cause",url:"/cause",abstract:!0,template:""},{name:"cause.list",availableWebMenu:"Årsaksliste",filters:housingFilter,url:"/list/:menuGuid??filter",templateUrl:"app/cause/views/listCause.html",controller:"ListController",params:{entityData:apiData.cause}},{name:"cause.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/cause/views/cause.html",controller:"CauseController"},{name:"cause.create",url:"/create",params:{menuGuid:""},templateUrl:"app/cause/views/cause.html",controller:"CauseController",excludeFromHistory:!0},{name:"apiClient",url:"/apiClient",abstract:!0,template:""},{name:"apiClient.list",url:"/list/:menuGuid??filter",templateUrl:"app/apiClient/views/listApiClients.html",controller:"ListController",params:{entityData:apiData.apiClient}},{name:"apiClient.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/apiClient/views/editApiClient.html",controller:"ApiClientController"},{name:"apiClient.create",url:"/create",params:{menuGuid:"",guidEntityToCopy:""},templateUrl:"app/apiClient/views/editApiClient.html",controller:"ApiClientController",excludeFromHistory:!0},{name:"apiRequestLog",url:"/apiRequestLog",abstract:!0,template:""},{name:"apiRequestLog.list",availableWebMenu:"API log",url:"/list/:menuGuid??filter",templateUrl:"app/apiRequestLog/views/listApiRequestLog.html",controller:"ListController",params:{entityData:apiData.apiRequestLog}},{name:"apiRequestLog.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/apiRequestLog/views/editApiRequestLog.html",controller:"ApiRequestLogController"},{name:"scheduledJob",url:"/scheduledJob",abstract:!0,template:""},{name:"scheduledJob.list",availableWebMenu:"Bakgrunnsjobber",url:"/list/:menuGuid??filter",templateUrl:"app/scheduledJob/views/listScheduledJobs.html",controller:"ListController",params:{entityData:apiData.scheduledJob}},{name:"scheduledJob.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/scheduledJob/views/editScheduledJob.html",controller:"ScheduledJobController"},{name:"scheduledJob.create",url:"/create",params:{menuGuid:"",guidEntityToCopy:"",scheduledJobModel:!1},templateUrl:"app/scheduledJob/views/editScheduledJob.html",controller:"ScheduledJobController",excludeFromHistory:!0},{name:"scheduledJobExecution",url:"/scheduledJobExecution",abstract:!0,template:""},{name:"scheduledJobExecution.list",availableWebMenu:"Utførte bakgrunnsjobber",url:"/list/:menuGuid??filter",templateUrl:"app/scheduledJobExecution/views/listScheduledJobExecutions.html",controller:"ListController",params:{entityData:apiData.scheduledJobExecution}},{name:"scheduledJobExecution.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/scheduledJobExecution/views/editScheduledJobExecution.html",controller:"ScheduledJobExecutionController",excludeFromHistory:!0},{name:"emailTemplate",url:"/emailTemplate",abstract:!0,template:""},{name:"emailTemplate.list",url:"/list/:menuGuid??filter",templateUrl:"app/emailTemplate/views/listEmailTemplate.html",controller:"ListController",params:{entityData:apiData.emailTemplate}},{name:"emailTemplate.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/emailTemplate/views/editEmailTemplate.html",controller:"EmailTemplateController",excludeFromHistory:!0},{name:"emailTemplate.create",url:"/create",params:{menuGuid:""},templateUrl:"app/emailTemplate/views/editEmailTemplate.html",controller:"EmailTemplateController",excludeFromHistory:!0},{name:"cacheInfo",url:"/cacheInfo",abstract:!0,template:""},{name:"cacheInfo.list",url:"/list",templateUrl:"app/cacheInfo/views/cacheInfo.html",controller:"CacheInfoController"},{name:"entityLink",url:"/entityLink",abstract:!0,template:""},{name:"entityLink.list",url:"/list/:menuGuid??filter",templateUrl:"app/entityLink/views/listEntityLink.html",controller:"ListController",params:{entityData:apiData.entityLink}},{name:"entityLink.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/entityLink/views/editEntityLink.html",controller:"EntityLinkController"},{name:"entityLink.create",url:"/create",params:{menuGuid:""},templateUrl:"app/entityLink/views/editEntityLink.html",controller:"EntityLinkController",excludeFromHistory:!0},{name:"entityCounter",url:"/entityCounter",abstract:!0,template:""},{name:"entityCounter.list",url:"/list/:menuGuid??filter",templateUrl:"app/entityCounter/views/listEntityCounter.html",controller:"ListController",params:{entityData:apiData.entityCounter,modal:{templateUrl:"app/entityCounter/views/entityCounterModal.html",controller:"EntityCounterModalController"}}},{name:"entityTask",url:"/entityTask",abstract:!0,template:""},{name:"entityTask.list",availableWebMenu:"Handlinger",url:"/list/:menuGuid??filter",templateUrl:"app/entityTask/views/listEntityTask.html",controller:"ListController",params:{entityData:apiData.entityTask}},{name:"entityTask.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/entityTask/views/editEntityTask.html",controller:"EntityTaskController"},{name:"referenceType",url:"/referenceType",abstract:!0,template:""},{name:"referenceType.list",availableWebMenu:"Referanser",url:"/list/:menuGuid??filter",templateUrl:"app/referenceType/views/listReferenceType.html",controller:"ListController",params:{entityData:apiData.referenceType}},{name:"referenceType.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/referenceType/views/editReferenceType.html",controller:"ReferenceTypeController"},{name:"referenceType.create",url:"/create",params:{menuGuid:""},templateUrl:"app/referenceType/views/editReferenceType.html",controller:"ReferenceTypeController",excludeFromHistory:!0},{name:"weblistView",url:"/weblistView",abstract:!0,template:""},{name:"weblistView.list",availableWebMenu:"Liste av skjermlister",url:"/list/:menuGuid??filter",templateUrl:"app/webListView/views/listWebListView.html",controller:"ListController",params:{entityData:apiData.webListView}},{name:"weblistView.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/webListView/views/editWebListView.html",controller:"WebListViewController"},{name:"userProfile",url:"/userProfile",abstract:!0,template:""},{name:"userProfile.list",availableWebMenu:"Brukerprofil",url:"/list/:menuGuid??filter",templateUrl:"app/userProfile/views/listUserProfile.html",controller:"ListController",params:{entityData:apiData.userProfile}},{name:"smsProvider",url:"/smsProvider",templateUrl:"app/smsProvider/smsProvider.html",controller:"SmsProviderController"},{name:"branding",url:"/branding",templateUrl:"app/branding/views/editBranding.html",controller:"BrandingController"},{name:"operationalMessage",url:"/operationalMessage",abstract:!0,template:""},{name:"operationalMessage.list",availableWebMenu:"Driftsmeldinger",url:"/list/:menuGuid??filter",templateUrl:"app/operationalMessage/views/listOperationalMessage.html",controller:"ListController",params:{entityData:apiData.operationalMessage,modal:{templateUrl:"app/operationalMessage/views/operationalMessageModal.html",controller:"OperationalMessageModalController"}}},{name:"doorKeySystem",url:"/doorKeySystem",abstract:!0,template:""},{name:"doorKeySystem.list",availableWebMenu:"Låssystemer",url:"/list/:menuGuid??filter",templateUrl:"app/doorKeySystem/views/listDoorKeySystem.html",controller:"ListController",params:{entityData:apiData.doorKeySystem}},{name:"doorKeySystem.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"doorKeySystem.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"doorKey",url:"/doorKey",abstract:!0,template:""},{name:"doorKey.list",availableWebMenu:"Nøkler",url:"/list/:menuGuid??filter",templateUrl:"app/doorKeySystem/views/listDoorKey.html",controller:"ListController",params:{entityData:apiData.doorKey}},{name:"doorKey.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"doorKey.create",url:"/create?guidDoorKeySystem",params:{menuGuid:"",guidDoorKeySystem:null},template:"",excludeFromHistory:!0},{name:"doorLock",url:"/doorLock",abstract:!0,template:""},{name:"doorLock.list",availableWebMenu:"Sylindre",url:"/list/:menuGuid??filter",templateUrl:"app/doorKeySystem/views/listDoorLock.html",controller:"ListController",params:{entityData:apiData.doorLock}},{name:"doorLock.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"doorLock.create",url:"/create?guidDoorKeySystem",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"doorKeyXUser",url:"/doorKeyXUser",abstract:!0,template:""},{name:"doorKeyXUser.list",availableWebMenu:"Utleveringer",url:"/list/:menuGuid??filter",templateUrl:"app/doorKeySystem/views/listDoorKeyXUser.html",controller:"ListController",params:{entityData:apiData.doorKeyXUser}},{name:"doorKeyXUser.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"doorLockXArea",url:"/doorLockXArea",abstract:!0,template:""},{name:"doorLockXArea.list",availableWebMenu:"Sylinder/areal",url:"/list/:menuGuid??filter",templateUrl:"app/doorKeySystem/views/listDoorLockXArea.html",controller:"ListController",params:{entityData:apiData.doorLockXArea}},{name:"doorKeyXDoorLock",url:"/doorKeyXDoorLock",abstract:!0,template:""},{name:"doorKeyXDoorLock.list",availableWebMenu:"Nøkkel/sylinder",url:"/list/:menuGuid??filter",templateUrl:"app/doorKeySystem/views/listDoorKeyXDoorLock.html",controller:"ListController",params:{entityData:apiData.doorKeyXDoorLock}},{name:"doorKeyTransaction",url:"/doorKeyTransaction",abstract:!0,template:""},{name:"doorKeyTransaction.list",availableWebMenu:"Nøkkeltransaksjoner",url:"/list/:menuGuid??filter",templateUrl:"app/doorKeySystem/views/listDoorKeyTransaction.html",controller:"ListController",params:{entityData:apiData.doorKeyTransaction}},{name:"databaseInfo",url:"/databaseInfo",template:""},{name:"installationValidation",url:"/installationValidation",template:""},{name:"workingDaysOff",url:"/workingDaysOff",abstract:!0,template:""},{name:"workingDaysOff.list",availableWebMenu:"Liste av fridager",url:"/list/:menuGuid??filter",templateUrl:"app/workingDaysOff/views/listWorkingDaysOff.html",controller:"ListController",params:{entityData:apiData.workingDaysOff}},{name:"workingDaysOff.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"workingDaysOff.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"changeSet",url:"/changeSet",abstract:!0,template:""},{name:"changeSet.list",availableWebMenu:"Endringsett",url:"/list/:menuGuid??filter",templateUrl:"app/changeSet/views/listChangeSet.html",controller:"ListController",params:{entityData:apiData.changeSet,modal:{templateUrl:"app/changeSet/views/changeSetModal.html",controller:"ChangeSetModalController"}}},{name:"externalLoginProvider",url:"/externalLoginProvider",abstract:!0,template:""},{name:"externalLoginProvider.list",url:"/list",template:""},{name:"externalLoginProvider.edit",url:"/edit/:guid",params:{menuGuid:""},template:""},{name:"externalLoginProvider.create",url:"/create",params:{menuGuid:""},template:"",excludeFromHistory:!0},{name:"userXUserNotification",url:"/userXUserNotification",abstract:!0,template:""},{name:"userXUserNotification.list",url:"/list",templateUrl:"app/userXUserNotification/views/listUserXUserNotification.html",controller:"ListController",params:{entityData:apiData.userXUserNotification}}]}var app=angular.module("Plania");app.config(["$stateProvider","$urlRouterProvider","$urlMatcherFactoryProvider",routeConfigurator]),app.value("states",{list:getStates()}),app.value("apiData",getApiData())}(),function(){function listController($scope,repository,$stateParams,states,ngTableParams,$modal,translationService,dwgThemeService,menuService,$localStorage,$rootScope){$scope.model={Guid:$stateParams.guid},$scope.update="webMenu.edit"===$scope.navigation.current.name,$scope.operators=["=","<>",">","<",">=","<=","in","contains","startsWith"],$scope.operands=[{key:"og",value:"and"},{key:"eller",value:"or"}],$scope.hasModule=$rootScope.hasModule;var urls=[],listViews=[],planiaStandardId="Plania Standard",updateWebListViews=function(){if($scope.showWebListView=$scope.ddSelectSelected&&$scope.ddSelectSelected.params&&$scope.ddSelectSelected.params.entityData&&$scope.ddSelectSelected.params.entityData.availableForListView,$scope.showWebListView){var contextId=$scope.ddSelectSelected.params.entityData.contextId||"List-"+$scope.ddSelectSelected.params.entityData.prefix;$scope.webListViews=_.filter(listViews,function(row){return row.Prefix===$scope.ddSelectSelected.params.entityData.prefix&&row.ContextId===contextId}),$scope.webListViews.unshift({Id:planiaStandardId}),$scope.webListViews.unshift({Guid:"00000000-0000-0000-0000-000000000000",Id:translationService.translate("web-webmenu-weblistview-userDefault","Bruk aktiv bruker sin listevisning")}),$scope.filters.selectedWebListView&&($scope.selectedWebListView=_.find($scope.webListViews,function(row){return row.Guid===$scope.filters.selectedWebListView.Guid})),$scope.selectedWebListView&&$scope.selectedWebListView.Guid||($scope.selectedWebListView&&$scope.selectedWebListView.Id===planiaStandardId?$scope.selectedWebListView=_.find($scope.webListViews,function(row){return row.Id===planiaStandardId}):$scope.selectedWebListView=$scope.webListViews[0])}};repository.GetPaginated(repository.apiData.webListView.url,0,1e4,{},{Prefix:-1,PropertyFilter:[{Property:"IsPublicView",Operator:"=",Value:"1"}]}).then(function(result){listViews=_.map(result.List,function(r){return{Guid:r.Guid,Id:r.Id,Prefix:r.EntityName,ContextId:r.ContextId}}),updateWebListViews()}),states.list.forEach(function(row){row.availableWebMenu&&urls.push(row)}),urls=_.filter(states.list,function(row){if(!$localStorage.generalOptions.DataAcquisitionWebMenus&&!$scope.hasModule("DataAcquisition")){if("document.dataAcquisitionMatrix"===row.name)return!1;if("document.dataAcquisitionList"===row.name)return!1}if(row.availableWebMenu)return!0}),urls=_.sortBy(urls,"availableWebMenu"),$scope.showWebListView=!1,$scope.webListViews=[],$scope.selectedWebListView={},$scope.ddSelectOptions=urls,$scope.dropdowns={},$scope.selectedDropdown={},$scope.prefillColumns=[],$scope.keywords=repository.filterKeyWords,$scope.prefillKeywords=repository.prefillKeyWords;var updateAccess=function(){$scope.update?($scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.WebMenu,!1),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.WebMenu,!1)):($scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.WebMenu),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.WebMenu))};updateAccess();var getDashboardNames=function(key){repository.GetPaginated(repository.apiData.webDashboard.url,0,1e3,{},{}).then(function(result){$scope.dropdowns[key]=[],result.List.forEach(function(row){$scope.dropdowns[key].push({name:row.Caption,key:key,value:row.Guid})}),$scope.selectedDropdown[key]=$scope.dropdowns[key][0]})},getReportNames=function(key){var filter={PropertyFilter:[{Property:"ReportType",Operator:"<>",Value:"4"}]},columns=["Id","Name"];repository.GetPaginated(repository.apiData.report.url,0,-1,{},filter,null,JSON.stringify(columns)).then(function(result){$scope.dropdowns[key]=[],result.List.forEach(function(row){$scope.dropdowns[key].push({name:row.Name||row.Id,key:key,value:row.Id})}),$scope.selectedDropdown[key]=$scope.dropdowns[key][0]})};$scope.filterDropdownChange=function(selected){$scope.filters[selected.key]=selected.name};var getDrawingLoggedInDropdown=function(){$scope.filters.GetLoggedInCleanerDrawing||($scope.filters.GetLoggedInCleanerDrawing="false"),$scope.dropdowns.GetLoggedInCleanerDrawing=[],$scope.dropdowns.GetLoggedInCleanerDrawing.push({name:"true",key:"GetLoggedInCleanerDrawing",value:"true"}),$scope.dropdowns.GetLoggedInCleanerDrawing.push({name:"false",key:"GetLoggedInCleanerDrawing",value:"false"}),"true"===$scope.filters.GetLoggedInCleanerDrawing?$scope.selectedDropdown.GetLoggedInCleanerDrawing=$scope.dropdowns.GetLoggedInCleanerDrawing[0]:$scope.selectedDropdown.GetLoggedInCleanerDrawing=$scope.dropdowns.GetLoggedInCleanerDrawing[1]},getCleaningLoggedInDropdown=function(){$scope.dropdowns.GetLoggedInCleanerCleaning=[],$scope.dropdowns.GetLoggedInCleanerCleaning.push({name:"true",key:"GetLoggedInCleanerCleaning",value:"true"}),$scope.dropdowns.GetLoggedInCleanerCleaning.push({name:"false",key:"GetLoggedInCleanerCleaning",value:"false"}),"true"===$scope.filters.GetLoggedInCleanerCleaning?$scope.selectedDropdown.GetLoggedInCleanerCleaning=$scope.dropdowns.GetLoggedInCleanerCleaning[0]:$scope.selectedDropdown.GetLoggedInCleanerCleaning=$scope.dropdowns.GetLoggedInCleanerCleaning[1]},getAvailableDwgThemes=function(){var availableThemes=_.map(dwgThemeService.getAvailableThemes(),function(o){return{name:o.label,key:"selectedTheme",value:o.value}});$scope.dropdowns.selectedTheme=availableThemes},cleanupDropdown=function(){$scope.dropdowns={}};$scope.$watch("ddSelectSelected",function(newValue,oldValue){if(!(newValue===oldValue&&$scope.prefillColumns.length>0)&&newValue)if(cleanupDropdown(),"report.view"===newValue.name&&getReportNames(newValue.filters[0].key),"dashboard.view"===newValue.name&&getDashboardNames(newValue.filters[0].key),"dwg.list"===newValue.name&&(getDrawingLoggedInDropdown(),getAvailableDwgThemes()),"cleaning.list"===newValue.name&&getCleaningLoggedInDropdown(),newValue.params&&newValue.params.entityData){var locale=translationService.getLocale();repository.getWithUrlParameter(repository.apiData.webColumns.url,"domainModel="+newValue.params.entityData.prefix+"&locale="+locale).then(function(result){$scope.prefillColumns=result,"Document"===newValue.params.entityData.prefix&&repository.getWithUrlParameter(repository.apiData.webColumns.url,"domainModel=DocumentXEntity&locale="+locale).then(function(result){result.forEach(function(item){$scope.prefillColumns.push(item)})})}),updateWebListViews()}else $scope.showWebListView=!1,$scope.prefillColumns=[],$scope.filters.Prefill=[]}),$scope.filters={},$scope.filters.PropertyFilter=[],$scope.filters.Prefill=[],$scope.webprofileColumns=[{Position:1,Title:translationService.translate("web-webprofile-id"),Property:"WebProfile.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-supplier-description"),Property:"WebProfile.Description",PropertyType:"string"}],$scope.update?(repository.getSingle(repository.apiData.webMenu.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess(),$scope.filters=JSON.parse($scope.model.Reference)||{},$scope.filters.PropertyFilter||($scope.filters.PropertyFilter=[]),$scope.filters.Prefill||($scope.filters.Prefill=[]);var url=_.filter(urls,{name:response.Data.Context});url&&url[0]&&($scope.ddSelectSelected=url[0],"report.view"===url[0].name&&getReportNames(url[0].filters[0].key),"dashboard.view"===url[0].name&&getDashboardNames(url[0].filters[0].key),"dwg.list"===url[0].name&&(getDrawingLoggedInDropdown(),getAvailableDwgThemes()),"cleaning.list"===url[0].name&&getCleaningLoggedInDropdown(),updateWebListViews())}),$scope.profileTable=new ngTableParams({page:1,count:25,sorting:{IndexPosition:"asc"},filter:{PropertyFilter:[{Property:"GuidWebMenu",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[],getData:function($defer,params){var columns=[];$scope.webprofileColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.webProfileWebMenu.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.profileTable.settings().total=result.TotalCount,$scope.profileTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})):($scope.ddSelectSelected=urls[0],updateWebListViews(),$stateParams.guidEntityToCopy&&repository.getSingle(repository.apiData.webMenu.url,$stateParams.guidEntityToCopy).then(function(response){delete response.Data.Guid,$scope.model=response.Data,$scope.model.Name+="-N",$scope.filters=JSON.parse($scope.model.Reference)||{},$scope.filters.PropertyFilter||($scope.filters.PropertyFilter=[]),$scope.filters.Prefill||($scope.filters.Prefill=[]);var url=_.filter(urls,{name:response.Data.Context});url&&url[0]&&($scope.ddSelectSelected=url[0],"report.view"===url[0].name&&getReportNames(url[0].filters[0].key),"dashboard.view"===url[0].name&&getDashboardNames(url[0].filters[0].key),"dwg.list"===url[0].name&&(getDrawingLoggedInDropdown(),getAvailableDwgThemes()),"cleaning.list"===url[0].name&&getCleaningLoggedInDropdown())})),$scope.updateMenu=function(destination){$scope.filters.PropertyFilter=_.filter($scope.filters.PropertyFilter,function(item){return""!==item.Property}),$scope.filters.Prefill.forEach(function(prefill){delete prefill.data}),$scope.selectedWebListView&&($scope.filters.selectedWebListView=$scope.selectedWebListView),$scope.model.Reference=angular.toJson($scope.filters),$scope.model.Context=$scope.ddSelectSelected.name;var success=function(result){repository.growl($scope.update?"Meny har blitt oppdatert":"Meny har blitt opprettet","success");var guid=$scope.update?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),menuService.getShortcuts(),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){repository.growl(error,"danger")};$scope.update?repository.updateSingle(repository.apiData.webMenu.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.webMenu.url,$scope.model).then(success).catch(error)},$scope.deleteWebMenu=function(destination){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-webmenu-message","Webmenyen og referanser vil bli slettet fra plania!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-webmenu-button-confirm","Ja, fjern webmenyen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.webMenu.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-webmenu-success","Webmenyen ble fjernet!"),result,"success"),$scope.goBack(destination,{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.addProfile=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Legg til web profil",url:repository.apiData.webProfile.url,columns:[{Title:translationService.translate("web-webProfile-id"),Property:"Id",PropertyType:"string"},{Title:translationService.translate("web-webProfile-description"),Property:"Description",PropertyType:"string"}],useObjects:!1}}}}).result.then(function(guids){var model=[],index=$scope.profileTable.data.length;guids.forEach(function(guid){model.push({GuidWebMenu:$scope.model.Guid,GuidWebProfile:guid,IndexPosition:index++})}),repository.createMultiple(repository.apiData.webProfileWebMenu.url,model).then(function(result){$scope.profileTable.reload(),menuService.getShortcuts()})},function(){})},$scope.removeProfile=function(webProfileWebMenu){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-webmenu-webprofile-message","Menyprofilen vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-webmenu-webprofile-button-confirm","Ja, fjern menyprofilen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.webProfileWebMenu.url,webProfileWebMenu.Guid).then(function(result){swal(translationService.translate("web-swal-webmenu-webprofile-success","Menyprofilen ble fjernet!"),result,"success"),repository.growl("menyProfilen har blitt fjernet","success"),$scope.profileTable.reload(),menuService.getShortcuts()})})},$scope.changedPrefillProperty=function(prefill){prefill.Value=null;var prefillColumn=_.find($scope.prefillColumns,function(o){return o.Property===prefill.Property});prefill.PropertyType=prefillColumn.PropertyType,prefill.IsExpandable=prefillColumn.IsExpandable,"bool"===prefill.PropertyType&&(prefill.Value=!0)},$scope.changedAutoCompleteValue=function(value){value||(value={})},$scope.getTypeOf=function(value){return null===value&&(value={}),typeof value},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"activitycategory":return $scope.model.Context.startsWith("request.")?{PropertyFilter:[{Property:"UseInRequest",Operator:"=",Value:"true"},{Property:"IsAbstract",Operator:"=",Value:"0"}]}:$scope.model.Context.startsWith("workOrder.")?{PropertyFilter:[{Property:"UseInWorkOrder",Operator:"=",Value:"true"},{Property:"IsAbstract",Operator:"=",Value:"0"}]}:filter}return filter},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("WebMenuController",["$scope","Repository","$stateParams","states","ngTableParams","$modal","TranslationService","DwgThemeService","MenuService","$localStorage","$rootScope",listController])}(),function(){function controller($scope,repository,$stateParams,$modal,ngTableParams,translationService,listService){$scope.isUpdate="account.edit"===$scope.navigation.current.name,$scope.activateAutocomplete=!1,$scope.model={},$scope.getPropertyValue=function(entity,field){return listService.GetPropertyValue(entity,field)};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Account,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Account,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Account),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Account)};if($scope.isUpdate){var columns=["DataOwner.Dimension1"];repository.getMainModel(repository.apiData.account.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.reload=!0,updateAccess(),getCardTables()},function(error){repository.growl(error,"danger")})}else $scope.model.Type=0,$scope.model.VatCode=0;$scope.accountXAccountingDimensionColumns=[],$scope.accountXAccountingDimensionColumns.AddColumn=function(translationId,defaultText,property,propertyType){return this.push({Position:this.length,Title:translationService.translate(translationId,defaultText),Property:property,PropertyType:propertyType}), this},$scope.accountXAccountingDimensionColumns.AddColumn("web-accounting-id","Id","Accounting.Id","string").AddColumn("web-accounting-description","Beskrivelse","Accounting.Description","string");var getCardTables=function(){$scope.accountXAccountingDimensionTable=new ngTableParams({page:1,count:10,sorting:{"Accounting.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidAccount",Operator:"=",Value:$scope.model.Guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];$scope.accountXAccountingDimensionColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.accountAccounting.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.loadingAccounting=!1,$scope.accountXAccountingDimensionTable.settings().total=result.TotalCount,$scope.accountXAccountingDimensionTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){$scope.loadingAccounting=!1,repository.growl(error,"danger")})}})};$scope.addAccounting=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:translationService.translate("web-account-accountXAccounting-addAccounting-title","Velg dimensjonsverdier"),columns:[{Title:translationService.translate("web-accountingDimension-id","Id"),Property:"Id"},{Title:translationService.translate("web-accountingDimension-description","Beskrivelse"),Property:"Description"}],useObjects:!0,url:repository.apiData.accounting.url,sorting:{Id:"asc"},filter:{PropertyFilter:[{Property:"DimensionNumber",Operator:"=",Value:"0"}]},alreadySavedGuids:function(){var selectedGuids=[];return $scope.accountXAccountingDimensionTable.data.forEach(function(entity){selectedGuids.push(entity.GuidAccounting)}),selectedGuids}()}}}}).result.then(function(selectedEntities){var arrayOfAccountXAccountingDimensions=[];selectedEntities.forEach(function(entity){arrayOfAccountXAccountingDimensions.push({GuidAccount:$scope.model.Guid,GuidAccounting:entity.Guid})}),repository.createMultiple(repository.apiData.accountAccounting.url,arrayOfAccountXAccountingDimensions).then(function(result){repository.growl(translationService.translate("web-account-accountXAccounting-addAccounting-success","Dimensjonsverdier har blitt lagt til kontoen"),"success"),$scope.accountXAccountingDimensionTable.reload()},function(error){repository.growl(error,"danger")})})},$scope.removeAccounting=function(accounting){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-accountXAccounting-message","Dimensjonen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-supplier-accountXAccounting-button-confirm","Ja, fjern dimensjonen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.accountAccounting.url,accounting.Guid).then(function(result){swal(translationService.translate("web-swal-supplier-accountXAccounting-success","Dimensjonen ble fjernet!"),result,"success"),$scope.accountXAccountingDimensionTable.reload()})})},$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-account-success","Konto har blitt oppdatert."):translationService.translate("create-account-success","Konto har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.account.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.account.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-account-message","Konto vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-account-button-confirm","Ja, fjern konto"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.account.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-account-success","Konto ble fjernet!"),result,"success"),$scope.goBack("account.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("AccountController",["$scope","Repository","$stateParams","$modal","ngTableParams","TranslationService","ListService",controller])}(),function(){function controller($scope,repository,modalParams,modalInstance,translationService,$modal,ngTableParams,listService){$scope.isUpdate=!!modalParams.dim,$scope.childDimensionTitle=modalParams.childDimensionTitle,modalParams.DimensionNumber>=0?$scope.model={DimensionNumber:modalParams.DimensionNumber}:modalParams.dim&&($scope.model={Guid:modalParams.dim.Guid,Id:modalParams.dim.Id,Description:modalParams.dim.Description,DimensionNumber:modalParams.dim.DimensionNumber}),$scope.isLastDimension=modalParams.isLastDimension,$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.accountingXAccountingDimensionColumns=[],$scope.accountingXAccountingDimensionColumns.AddColumn=function(translationId,defaultText,property,propertyType){return this.push({Position:this.length,Title:translationService.translate(translationId,defaultText),Property:property,PropertyType:propertyType}),this},$scope.accountingXAccountingDimensionColumns.AddColumn("web-accounting-id","Id","ChildAccounting.Id","string").AddColumn("web-accounting-description","Beskrivelse","ChildAccounting.Description","string"),function(){!modalParams.isLastDimension&&$scope.model.Guid&&($scope.accountingXAccountingDimensionTable=new ngTableParams({page:1,count:10,sorting:{"ChildAccounting.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidParentAccounting",Operator:"=",Value:$scope.model.Guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];$scope.accountingXAccountingDimensionColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.accountingXAccounting.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.loadingAccounting=!1,$scope.accountingXAccountingDimensionTable.settings().total=result.TotalCount,$scope.accountingXAccountingDimensionTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){$scope.loadingAccounting=!1,repository.growl(error,"danger")})}}))}(),$scope.addAccounting=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:translationService.translate("web-accounting-addChildAccounting","Velg dimensjoner"),columns:[{Title:translationService.translate("web-accounting-id","Id"),Property:"Id"},{Title:translationService.translate("web-accounting-description","Beskrivelse"),Property:"Description"}],useObjects:!0,url:repository.apiData.accounting.url,sorting:{Id:"asc"},filter:{PropertyFilter:[{Property:"DimensionNumber",Operator:"=",Value:$scope.model.DimensionNumber+1}]},alreadySavedGuids:function(){var selectedGuids=[];return $scope.accountingXAccountingDimensionTable&&$scope.accountingXAccountingDimensionTable.data.forEach(function(entity){selectedGuids.push(entity.GuidChildAccounting)}),selectedGuids}()}}}}).result.then(function(selectedEntities){var arrayOfAccountingXAccountingDimensions=[];selectedEntities.forEach(function(entity){arrayOfAccountingXAccountingDimensions.push({GuidParentAccounting:$scope.model.Guid,GuidChildAccounting:entity.Guid})}),repository.createMultiple(repository.apiData.accountingXAccounting.url,arrayOfAccountingXAccountingDimensions).then(function(result){repository.growl("Dimensjon(er) har blitt lagt til på dimensjon","success"),$scope.accountingXAccountingDimensionTable.reload()})})},$scope.removeAccounting=function(accounting){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-accountingXAccounting-message","Dimensjonen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-supplier-accountingXAccounting-button-confirm","Ja, fjern dimensjonen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.accountingXAccounting.url,accounting.Guid).then(function(result){swal(translationService.translate("web-swal-supplier-accountingXAccounting-success","Dimensjonen ble fjernet!"),result,"success"),$scope.accountingXAccountingDimensionTable.reload()})})},$scope.saveAccounting=function(){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-accounting-success","Dimensjon har blitt oppdatert."):translationService.translate("create-accounting-success","Dimensjon har blitt opprettet."),"success"),modalInstance.close(result)},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.accounting.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.accounting.url,$scope.model).then(success,error)},$scope.cancel=function(){modalInstance.dismiss("Avbryt")}}angular.module("Plania").controller("AccountingModalController",["$scope","Repository","modalParams","$modalInstance","TranslationService","$modal","ngTableParams","ListService",controller])}(),function(){function controller($scope,repository,$rootScope,accountingService){$scope.modelDto={};var getDataOwner=function(){repository.getSingle(repository.apiData.dataOwner.url,repository.commonService.getFilterData().selectedDataOwner.Guid).then(function(response){$scope.modelDto.dataOwner=response.Data},function(error){repository.growl(error,"danger")})};$scope.dataOwner?$scope.modelDto.dataOwner=$scope.dataOwner:getDataOwner();var accountingWatchers={},removeWatcher=function(dimNum){void 0===dimNum?[0,1,2,3,4].forEach(function(dimNum){removeWatcher(dimNum)}):(accountingWatchers["Accounting"+dimNum]&&accountingWatchers["Accounting"+dimNum](),accountingWatchers["AccountingDimension"+dimNum]&&accountingWatchers["AccountingDimension"+dimNum](),delete accountingWatchers["Accounting"+dimNum],delete accountingWatchers["AccountingDimension"+dimNum])};$scope.onGetValidityRules=function(originalValidityRules){return accountingService.onGetValidityRules($scope.modelDto.dataOwner,originalValidityRules)},$scope.onAccountSelect=function(account){accountingService.onAccountSelect($scope.model,account)},[0,1,2,3,4].forEach(function(dimNum){$scope["onAccounting"+dimNum+"Select"]=function(accounting){removeWatcher(),accountingService["onAccounting"+dimNum+"Select"]($scope.model,accounting)}}),$scope.autoCompleteFilter=function(filterName){return accountingService.autoCompleteFilter($scope.model,filterName)},$scope.$on($rootScope.events.newSelection,function(){$scope.$parent&&!$scope.$parent.isUpdate&&getDataOwner()}),[0,1,2,3,4].forEach(function(dimNum){accountingWatchers["Accounting"+dimNum]=$scope.$watch("model.Accounting"+dimNum,function(newVal){!$scope.modelDto["Accounting"+dimNum]&&newVal&&($scope.modelDto["Accounting"+dimNum]=newVal,removeWatcher(dimNum))})})}angular.module("Plania").directive("accountingSection",function(){return{restrict:"E",scope:{model:"=ngModel",dataOwner:"=dataOwner",prefix:"=prefix",viewMode:"=viewMode",activateAutocomplete:"=activateAutocomplete",restrictEdit:"=restrictEdit",isFieldEnabled:"=isFieldEnabled",useTwoColumns:"=useTwoColumns",useVerticalFields:"=useVerticalFields",editMode:"=editMode"},controller:["$scope","Repository","$rootScope","AccountingService",controller],templateUrl:"app/accounting/views/accountingSection.html"}})}(),function(){function factory(){var service={};return service.isMandatory=function(dataOwner,accountingColumnProperty,parentEntity){if(!dataOwner||!dataOwner.Guid)return!1;if("GuidDepartment"===accountingColumnProperty)return"Budget"===parentEntity?dataOwner.DepartmentBudget:dataOwner.DepartmentCost;if(accountingColumnProperty.startsWith("GuidAccounting")){var lastDimensionValue="Budget"===parentEntity?dataOwner.LastDimensionBudget:dataOwner.LastDimensionCost;if(angular.isDefined(lastDimensionValue))return lastDimensionValue>=parseInt(accountingColumnProperty.slice(-1))}return!1},service.onGetValidityRules=function(dataOwner,originalValidityRules){if(!service.isMandatory(dataOwner,originalValidityRules.DomainFieldName,originalValidityRules.EntityType))return originalValidityRules;var validityRules=_.clone(originalValidityRules);return validityRules.Mandatory=!0,validityRules},service.onAccountSelect=function(model,account){model&&"object"==typeof model&&(account?model.GuidAccount=account.Guid:delete model.GuidAccount,model.GuidAccounting0&&account.AccountXAccountings&&account.AccountXAccountings.length&&!_.find(account.AccountXAccountings,{GuidAccounting:model.GuidAccounting0})&&(delete model.GuidAccounting0,delete model.GuidAccounting1,delete model.GuidAccounting2,delete model.GuidAccounting3,delete model.GuidAccounting4,delete model.Accounting0,delete model.Accounting1,delete model.Accounting2,delete model.Accounting3,delete model.Accounting4))},[0,1,2,3,4].forEach(function(dimNum){service["onAccounting"+dimNum+"Select"]=function(model,accounting){if(model&&"object"==typeof model&&(accounting?model["GuidAccounting"+dimNum]=accounting.Guid:delete model["GuidAccounting"+dimNum],4!==dimNum)){var childDimProperty="GuidAccounting1";if(model[childDimProperty]&&accounting.ChildAccountingAccountingXAccountings&&accounting.ChildAccountingAccountingXAccountings.length&&!_.find(accounting.ChildAccountingAccountingXAccountings,{GuidChildAccounting:model[childDimProperty]}))for(var index=dimNum+1;index<=4;)delete model["GuidAccounting"+index],delete model["Accounting"+index],index++}}}),service.autoCompleteFilter=function(model,filterName){var filter={};switch(filterName){case"accounting0":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:0,Operator:"="}],model&&"object"==typeof model&&(filter.GuidParentAccount=model.GuidAccount),filter;case"accounting1":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:1,Operator:"="}],model&&"object"==typeof model&&(filter.GuidParentAccounting=model.GuidAccounting0),filter;case"accounting2":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:2,Operator:"="}],model&&"object"==typeof model&&(filter.GuidParentAccounting=model.GuidAccounting1),filter;case"accounting3":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:3,Operator:"="}],model&&"object"==typeof model&&(filter.GuidParentAccounting=model.GuidAccounting2),filter;case"accounting4":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:4,Operator:"="}],model&&"object"==typeof model&&(filter.GuidParentAccounting=model.GuidAccounting3),filter;default:return filter}},service}angular.module("Plania").factory("AccountingService",factory)}(),function(){angular.module("Plania").controller("ListAccountingController",["$scope","Repository","TranslationService","$modal",function($scope,repository,translationService,$modal){$scope.dimensions=[],function(){$scope.restrictEdit=!$scope.hasEditAccess(repository.apiData.accounting.prefix),$scope.restrictDelete=!$scope.hasDeleteAccess(repository.apiData.accounting.prefix)}();var columns=["Id","Description","DimensionNumber","DataOwner.Dimension1","DataOwner.Dimension2","DataOwner.Dimension3","DataOwner.Dimension4","DataOwner.Dimension5"],getItems=function(){$scope.dimensions=[];var filter={};repository.GetPaginated(repository.apiData.accounting.url,0,-1,{Id:"asc"},filter,null,JSON.stringify(columns)).then(function(result){var dimensions=[],accountings=result.List;accountings=accountings.filter(function(accounting){return accounting.DataOwner&&accounting.DataOwner["Dimension"+(accounting.DimensionNumber+1)]&&accounting.DataOwner["Dimension"+(accounting.DimensionNumber+1)].length>0}),accountings.forEach(function(dimension){var existingDimension=_.find(dimensions,function(dim){return dim.dimensionNumber===dimension.DimensionNumber});existingDimension?existingDimension.data.push(dimension):dimensions.push({dimensionNumber:dimension.DimensionNumber,dimensionTitle:dimension.DataOwner["Dimension"+(dimension.DimensionNumber+1)],data:[dimension]})}),$scope.dimensions=_.sortBy(dimensions,function(dim){return dim.dimensionNumber})})};getItems(),$scope.addAccounting=function(dimensionNumber){$modal.open({templateUrl:"app/accounting/views/editAccounting.html",controller:"AccountingModalController",resolve:{modalParams:function(){return{DimensionNumber:dimensionNumber}}}}).result.then(function(responseResult){getItems()})},$scope.updateAccounting=function(dim){for(var childDimensionTitle="",i=0;i<$scope.dimensions.length;i++)if($scope.dimensions[i].dimensionNumber===dim.DimensionNumber+1){childDimensionTitle=$scope.dimensions[i].dimensionTitle;break}$modal.open({templateUrl:"app/accounting/views/editAccounting.html",controller:"AccountingModalController",resolve:{modalParams:function(){return{dim:dim,isLastDimension:!_.some($scope.dimensions,{dimensionNumber:dim.DimensionNumber+1}),childDimensionTitle:childDimensionTitle}}}}).result.then(function(responseResult){getItems()})},$scope.removeAccounting=function(guid){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-accounting-message","Dimensjon vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-accounting-button-confirm","Ja, fjern dimensjon!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.accounting.url,guid).then(function(result){swal(translationService.translate("web-swal-accounting-success","Dimensjonen ble fjernet!"),result,"success"),getItems()})})},$scope.contextMenuOptions=function(dimension){var options=[];return $scope.restrictEdit||options.push({html:' '+translationService.translate("web-accounting-contextMenu-dimension-edit","Rediger dimensjonsverdi")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.updateAccounting(dimension)}}),$scope.restrictDelete||options.push({html:' '+translationService.translate("web-accounting-contextMenu-dimension-delete","Slett dimensjonsverdi")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.removeAccounting(dimension.Guid)}}),options}}])}(),function(){function controller($scope,$modalInstance,modalParams,repository,ngTableParams){$scope.modalParams=modalParams,$scope.items=new ngTableParams({page:1,count:20,filter:{searchString:""},sorting:$scope.defaultSort?$scope.defaultSort:{id:"asc"}},{total:0,counts:[10,20,50],paginationMaxBlocks:5,getData:function($defer,params){var searchString=params.filter().searchString;searchString&&repository.getWithUrlParameter(repository.apiData.address.endpoint.search,"searchString="+searchString+"&page="+(params.page()-1)+"&pageSize="+params.count()).then(function(result){params.total(result.TotalCount),result.List&&$defer.resolve(result.List)})}}),$scope.ok=function(item){$modalInstance.close(item)},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("AddressSearchController",["$scope","$modalInstance","modalParams","Repository","ngTableParams",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,$sce,$filter){$scope.isUpdate="alarmLog.edit"===$scope.navigation.current.name,$scope.isUpdate&&repository.getSingle(repository.apiData.alarmLog.url,$stateParams.guid).then(function(response){$scope.model=response.Data},function(error){repository.growl(error,"danger")}),$scope.isHtml=function(string){return!string||/<[a-z][\s\S]*>/i.test(string)},$scope.getNumberOfAttachments=function(){return $scope.model?$scope.model.Attachments?$scope.model.Attachments.split(",").length:0:null},$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-alarmLog-success","Alarm loggen har blitt oppdatert."):translationService.translate("create-alarmLog-success","Alarm loggen har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.alarmLog.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.alarmLog.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-alarmLog-message","Alarm loggen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-alarmLog-button-confirm","Ja, fjern Alarm loggen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.alarmLog.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-alarmLog-success","Alarm loggen ble fjernet!"),result,"success"),$scope.goBack("alarmLog.list",{menuGuid:$scope.navigation.params.menuGuid})})})}}angular.module("Plania").controller("AlarmLogController",["$scope","Repository","$stateParams","TranslationService","$sce","$filter",controller])}(),function(){function controller($scope,translationService,repository,$modal,$stateParams,ngTableParams,listService){$scope.isUpdate=$stateParams.guid,$scope.isUpdate?repository.getSingle(repository.apiData.apiClient.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess()},function(error){repository.growl(error,"danger")}):$scope.model={RefreshTokenLifetime:6e3,AccessTokenLifetime:65};var updateAccess=function(){$scope.isUpdate?($scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.ApiClient,!1),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ApiClient,!1)):$scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.ApiClient)};updateAccess(),$scope.update=function(destination,model){var modelToSave=model||$scope.model,success=function(result){repository.growl("API klienten har blitt "+($scope.isUpdate?"oppdatert.":"opprettet."),"success");var guid=$scope.isUpdate?modelToSave.Guid:result.Guid;$scope.goBack(destination,{guid:guid})},error=function(error){repository.growl(error,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.apiClient.url,modelToSave).then(success).catch(error):repository.createSingle(repository.apiData.apiClient.url,modelToSave).then(success).catch(error)},$scope.changePassword=function(){$modal.open({templateUrl:"app/common/modal/views/changePasswordModal.html",controller:"ChangePasswordModalController",size:"sm",resolve:{params:function(){return{user:{}}}}}).result.then(function(newPassword){newPassword&&($scope.model.Secret=newPassword,$scope.update("apiClient.edit"))})},$scope.delete=function(destination,model){var toSave=angular.copy(model);toSave.IsDeactivated=!0,swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-api-client-delete-message","API klienten vil bli slettet"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-api-client-delete-button-confirm","Ja, slett API klienten!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.update(destination,toSave)})}}angular.module("Plania").controller("ApiClientController",["$scope","TranslationService","Repository","$modal","$stateParams","ngTableParams","ListService",controller])}(),function(){function controller($scope,repository,$stateParams){$scope.model={Guid:$stateParams.guid};var columns=["EntityTask.Id","EntityTask.Description","ScheduledJob.Id","ScheduledJob.Description","UserCreatedBy.RealName"],isJson=function(text){try{return JSON.parse(text),!0}catch(ex){return!1}},tryParse=function(text){if(!isJson(text))return null;var parsed=JSON.parse(text);return parsed.Content&&isJson(parsed.Content)&&(parsed.Content=JSON.parse(parsed.Content)),parsed};repository.getMainModel(repository.apiData.apiRequestLog.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.model&&$scope.model.Request&&($scope.parsedRequest=tryParse($scope.model.Request)),$scope.model&&$scope.model.Response&&($scope.parsedResponse=tryParse($scope.model.Response))},function(error){repository.growl(error,"danger")})}angular.module("Plania").controller("ApiRequestLogController",["$scope","Repository","$stateParams",controller])}(),function(){function controller($scope,$modalInstance,parentParams,repository,ngTableParams,$filter){var oldCount=0;if(parentParams.AddComponents){var countsArray=[];$scope.componentsTable=new ngTableParams({page:1,count:10,sorting:{id:"asc"},filter:{}},{total:0,counts:countsArray,getData:function($defer,params){$scope.isLoading=!0,repository.GetPaginated(repository.apiData.component.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(["Id","Description"])).then(function(result){result.totalCount>10&&(countsArray.push(10),countsArray.push(20),countsArray.push(50)),$scope.isLoading=!1,params.total(result.TotalCount);var sortedResult=params.sorting()?$filter("orderBy")(result.List,params.orderBy()):result.List;$defer.resolve(sortedResult)},function(error){repository.growl(error,"danger")})}});var selectedComponents=[];$scope.addComponent=function(guid){if(_.contains(selectedComponents,guid))for(var i=0;i '+text+"",isHref:!0}};$scope.componentInfo=new function(){var me=this;this.items=[],this.search={},this.columns=[{Position:1,Title:translationService.translate("web-component-id"),Property:"Component.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-component-description"),Property:"Component.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-componentCategory-description"),Property:"Component.ComponentCategory.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-componentxequipment-quantity","Antall"),Property:"Quantity",PropertyType:"string"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:25,sorting:{"Component.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidArea",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],paginationMaxBlocks:6,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("Note"),columns.push("Component.Guid"),columns.push("Component.GuidImage"),repository.GetPaginated(repository.apiData.componentArea.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.items=result.List,me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}))},this.add=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Legg til komponent",url:repository.apiData.component.url,columns:[{Title:translationService.translate("web-component-id"),Property:"Id",PropertyType:"string"},{Title:translationService.translate("web-component-description"),Property:"Description",PropertyType:"string"}],filter:{FilterModel:{Condition:"and",Rules:[{Property:"ComponentXAreas.GuidArea",Operator:"<>",Value:$scope.model.Guid,CollectionOperator:"all"}]}},useObjects:!1}}}}).result.then(function(guids){var model=[];guids.forEach(function(guid){model.push({GuidArea:$scope.model.Guid,GuidComponent:guid})}),repository.createMultiple(repository.apiData.componentArea.url,model).then(function(result){me.table.reload()},function(){me.table.reload()})})},this.update=function(item){me.canEdit(item)&&$modal.open({templateUrl:"app/area/views/editComponentArea.html",controller:"AreaComponentController",resolve:{params:function(){return{component:item,AddComponents:!1}}}}).result.then(function(){me.table.reload()})},this.remove=function(item){me.canDelete(item)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-equipment-component-message","Komponenten vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-equipment-component-button-confirm","Ja, fjern komponenten!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.componentArea.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-equipment-component-success","Komponenten ble fjernet!"),result,"success"),me.table.reload()})})},this.contextMenuOptions=function(item){var options=[];return $scope.hasReadAccess("Component")&&options.push(getMenuLink($scope.navigation.href("component.edit",{guid:item.GuidComponent}),"fa-arrow-right fa-hc-fw fa-hc-lg",translationService.translate("web-area-componentXAreaContextMenu-viewComponent","Gå til komponent"))),me.canEdit(item)&&options.push({html:' '+translationService.translate("web-button-edit","Rediger")+"",click:function(){me.update(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-button-delete","Slett")+"",click:function(){me.remove(item)}}),options},this.canEdit=function(item){return item&&$scope.hasEditAccess("ComponentXArea")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("ComponentXArea")},me.initTable()}}}angular.module("Plania").directive("areaEquipmentDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",reloads:"=reloads",update:"=update",currentTab:"=currentTab"},controller:["$scope","Repository","TranslationService","$rootScope","$timeout","NgTableParams","$modal","$localStorage",controller],templateUrl:"app/area/views/areaEquipment.html"}})}(),function(){function controller($scope,$timeout,$rootScope){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasEditAccess=$rootScope.hasEditAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.update&&($scope.hasPageLoaded="image"===$scope.currentTab,!$scope.hasPageLoaded))var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"image"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)})}angular.module("Plania").directive("areaImageDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",currentTab:"=currentTab",update:"=update"},controller:["$scope","$timeout","$rootScope",controller],templateUrl:"app/area/views/areaImage.html"}})}(),function(){function controller($scope,ngTableParams,repository,translationService,$modal,$rootScope,listService,$timeout,areaService,$localStorage){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasEditAccess=$rootScope.hasEditAccess,$scope.hasModule=$rootScope.hasModule,$scope.userInfo=$rootScope.userInfo,$scope.customization=$rootScope.customization,$scope.generalOptions=$localStorage.generalOptions,$scope.imageApiUrl=$rootScope.imageApiUrl,$scope.navigation=$rootScope.navigation,$scope.isDynamicPropertiesCollapsed=!1,$scope.isDocumentsCollapsed=!0,$scope.viewMode=$scope.update,$scope.hasPageLoaded="info"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"info"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)});$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},areaService.enrichScopeWithFormFunctions($scope),$scope.update&&($scope.isPaused=function(task){var today=moment().startOf("day");return task.PausedFromDate&&task.PausedToDate&&today.isBetween(task.PausedFromDate,task.PausedToDate,"days","[]")},$scope.getPropertyValue=function(item,column){return item.Prefix===repository.commonService.prefix.AreaXCleaningTask&&"IsPaused"===column.Property?$scope.isPaused(item)?translationService.translate("web-areaxcleaningtask-pausedStatusColumn-paused","Pauset"):translationService.translate("web-areaxcleaningtask-pausedStatusColumn-active","Aktiv"):listService.GetPropertyValue(item,column)},$scope.personColumns=[{Position:1,Title:translationService.translate("web-person-firstname"),Property:"FirstName",PropertyType:"string"},{Position:2,Title:translationService.translate("web-person-lastname"),Property:"LastName",PropertyType:"string"},{Position:3,Title:translationService.translate("web-person-email"),Property:"Email",PropertyType:"string"},{Position:4,Title:translationService.translate("web-person-position"),Property:"Position",PropertyType:"string"},{Position:5,Title:translationService.translate("web-person-telephonework"),Property:"TelephoneWork",PropertyType:"string"},{Position:6,Title:translationService.translate("web-person-cellphone"),Property:"Cellphone",PropertyType:"string"}],$scope.cleaningTaskInfo=new function(){var me=this;this.isLoading=!1,this.columns=[{Position:2,Title:translationService.translate("web-areaxcleaningtask-cleaningTask-id","Renholdsoppgave"),Property:"CleaningTask.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-areaxcleaningtask-ResourceGroup-id","Renholdsteam"),Property:"ResourceGroup.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-areaxcleaningtask-AverageCleaningPerYear","Minutter neste år"),Property:"AverageCleaningPerYear",PropertyType:"number"},{Position:5,Title:translationService.translate("web-areaxcleaningtask-Recurrence","Gjentakelsesregel"),Property:"Recurrence",PropertyType:"recurrence"},{Position:6,Title:translationService.translate("web-areaxcleaningtask-NextCleaningDate","Utføres"),Property:"NextCleaningDate",PropertyType:"date"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{"CleaningTask.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidArea",Operator:"=",Value:$scope.model.Guid}],CleaningStatus:"Undefined"}},{total:0,counts:[10,20,50],filterDelay:10,paginationMaxBlocks:6,getData:function($defer,params){me.isLoading=!0;var columns=[];me.columns.forEach(function(col){"IsPaused"!==col.Property&&columns.push(col.Property)}),columns.push("PausedFromDate"),columns.push("PausedToDate"),repository.GetPaginated(repository.apiData.areaXCleaningTask.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.isLoading=!1,me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500;var hasPausedTask=!1;result.List.forEach(function(task){$scope.isPaused(task)&&(hasPausedTask=!0)}),hasPausedTask?"IsPaused"!==me.columns[0].Property&&me.columns.unshift({Position:1,SortingDisabled:!0,Title:translationService.translate("web-areaxcleaningtask-pausedStatusColumn","Status"),Property:"IsPaused"}):"IsPaused"===me.columns[0].Property&&me.columns.shift(),$defer.resolve(result.List)},function(error){me.isLoading=!1,repository.showError(error)})}}))},this.add=function(){$modal.open({templateUrl:"app/cleaningTask/views/cleaningTaskWizardModal.html",controller:"CleaningTaskWizardModalController",resolve:{modalParams:function(){return{columns:[{Title:translationService.translate("web-cleaningTask-id"),Property:"Id"},{Title:translationService.translate("web-CleaningTask-estimatedtime"),Property:"EstimatedTime"}],url:repository.apiData.cleaningTask.url,sorting:{Id:"asc"},filter:{},area:$scope.model}}}}).result.then(function(result){var cleaningTask=result.cleaningTask,recurrenceRule=result.recurrenceRule,attributeValues=result.attributeValues,areaXCleaningTasks=[{GuidCleaningTask:cleaningTask.Guid,RecurrenceRule:recurrenceRule,GuidArea:$scope.model.Guid,AttributeValues:attributeValues}];repository.createMultiple(repository.apiData.areaXCleaningTask.url,areaXCleaningTasks).then(function(result){me.table.reload()},function(error){repository.showError(error)})})},this.update=function(item){me.canEdit(item)&&$modal.open({templateUrl:"app/area/views/EditAreaXCleaningTaskModal.html",controller:"AreaXCleaningTaskController",resolve:{modalParams:function(){return{Guid:item.Guid}}}}).result.then(function(result){repository.growl(result,"info"),me.table.reload()})},this.remove=function(item){me.canDelete(item)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-area-cleaningtask-message","Renholdsoppgaven vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-area-cleaningtask-button-confirm","Ja, fjern renholdsoppgaven"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.areaXCleaningTask.url,"","guids="+JSON.stringify([item.Guid])).then(function(result){swal(translationService.translate("web-swal-area-cleaningTask-success","Renholdsoppgaven ble fjernet!"),result,"success"),repository.growl("Renholdsoppgaven har blitt fjernet","success"),me.table.reload()})})},this.pause=function(item){$modal.open({templateUrl:"app/area/views/editAreaXCleaningTaskStartDateModal.html",controller:"AreaXCleaningTaskController",size:"md",resolve:{modalParams:function(){return{Guid:item.Guid,SuggestedPause:{From:new Date,To:(new Date).setDate((new Date).getDate()+1)}}}}}).result.then(function(result){repository.growl(result,"info"),me.table.reload()})},this.contextMenuOptions=function(item){var options=[];if(item.CleaningTask&&"ExitCleaning"!==item.CleaningTask.CleaningType&&"InfectionCleaning"!==item.CleaningTask.CleaningType){var text=$scope.isPaused(item)?translationService.translate("web-areaXCleaningTask-cleaningTaskMenuOptions-setCleaningPauseDate-isPaused","Start renhold"):translationService.translate("web-areaXCleaningTask-cleaningTaskMenuOptions-setCleaningPauseDate-isNotPaused","Sett renhold på pause");options.push({html:' '+text+"",click:function(){me.pause(item)}})}return me.canEdit(item)&&options.push({html:' '+translationService.translate("web-areaXCleaningTask-cleaningTaskMenuOptions-edit","Rediger")+"",click:function(){me.update(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-areaXCleaningTask-cleaningTaskMenuOptions-delete","Slett")+"",click:function(){me.remove(item)}}),options},this.canEdit=function(item){return item&&$scope.hasEditAccess("AreaXCleaningTask")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("AreaXCleaningTask")},me.initTable()},$scope.addPerson=function(){var filter={},columns=[];columns.push({Title:translationService.translate("web-area-person-firstName","Fornavn"),Property:"FirstName"}),columns.push({Title:translationService.translate("web-area-person-lastName","Etternavn"),Property:"LastName"}),columns.push({Title:translationService.translate("web-area-person-area-id","Areal Id"),Property:"Area.Id"}),columns.push({Title:translationService.translate("web-area-person-area-description","Arealbeskrivelse"),Property:"Area.Description"}),$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Velg personer",columns:columns,useObjects:!1,url:repository.apiData.person.url,sorting:{FirstName:"asc"},filter:filter}}}}).result.then(function(selectedEntities){if(selectedEntities){var changeList=[];selectedEntities.forEach(function(entity){changeList.push({Guid:entity,GuidArea:$scope.model.Guid})}),repository.patch(repository.apiData.person.url,null,changeList).then(function(response){_.every(response,function(response){return response.IsSuccess})?repository.growl(translationService.translate("web-area-person-connection-success","Personene har blitt lagt til arealet"),"success"):repository.growl(translationService.translate("web-area-person-connection-failed","En eller flere personer ble ikke lagt til arealet"),"danger"),$scope.reloads.persons=!$scope.reloads.persons},function(error){repository.showError(error)})}})},$scope.$watchCollection("model.Images",function(){if($scope.model&&$scope.model.Images&&Array.isArray($scope.model.Images)){var defaultImage=$scope.model.Images.find(function(img){return img.IsDefault});defaultImage?$scope.model.GuidDefaultImage=defaultImage.Guid:delete $scope.model.GuidDefaultImage}}))}angular.module("Plania").directive("areaInfoDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",reloads:"=reloads",reloadDocumentTable:"=reloadDocumentTable",update:"=update",activateAutocomplete:"=activateAutocomplete",currentTab:"=currentTab",formReference:"="},controller:["$scope","ngTableParams","Repository","TranslationService","$modal","$rootScope","ListService","$timeout","AreaService","$localStorage",controller],templateUrl:"app/area/views/areaInfo.html"}})}(),function(){function controller($scope,repository,translationService,$rootScope,$timeout){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.update){if($scope.hasPageLoaded="maintenance"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"maintenance"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)});$scope.workOrderColumns=[{Position:1,Title:translationService.translate("web-workorder-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-workorder-type"),Property:"Type",PropertyType:"string"},{Position:3,Title:translationService.translate("web-workorder-description"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-equipment-resourcegroup-description","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidResourceGroup",AutocompleteService:"resourceGroup"},{Position:5,Title:translationService.translate("web-workorder-startdate"),Property:"StartDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-workorder-enddate"),Property:"EndDate",PropertyType:"date"}],$scope.createWorkOrder=function(){repository.persistedData.setPersistedData("workOrder.create",{guidEstate:$scope.model.Building.Estate.Guid,estate:$scope.model.Building.Estate.Caption,guidBuilding:$scope.model.GuidBuilding,building:$scope.model.Building?$scope.model.Building.Caption:"",guidArea:$scope.model.Guid,area:$scope.model.Id+" - "+$scope.model.Description,fromArea:!0}),$scope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})}}}angular.module("Plania").directive("areaMaintenanceDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",reloads:"=reloads",update:"=update",currentTab:"=currentTab"},controller:["$scope","Repository","TranslationService","$rootScope","$timeout",controller],templateUrl:"app/area/views/areaMaintenance.html"}})}(),function(){function areaService(repository,$q,$modal,translationService,$rootScope){var service={};return service.enrichScopeWithFormFunctions=function($scope){$scope.getProgressType=function(){return $scope.model.RealCapacity<=$scope.model.CalculatedCapacity?"success":"danger"},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidDrawing=""),$scope.model.Address=building.Address,$scope.model.GuidBuilding=building.Guid},$scope.onDrawingSelect=function(drawing){if(!drawing)return void($scope.model.GuidDrawing="");$scope.model.GuidDrawing=drawing.Guid,$scope.model.GuidBuilding=drawing.GuidBuilding},$scope.onAreaCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidAreaCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidAreaCategory=category.Guid},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"person":return filter.PropertyFilter=[{Property:"DoesCleaningTasks",Value:1,Operator:"="}],$scope.model.GuidCleaningTeam&&filter.PropertyFilter.push({Property:"GuidResourceGroup",Value:$scope.model.GuidCleaningTeam,Operator:"="}),filter;case"resourceGroup":return filter.PropertyFilter=[{Property:"DoesCleaningTasks",Value:1,Operator:"="}],filter;case"drawing":return{GuidBuilding:$scope.model.GuidBuilding};case"areaCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}}},service.getActiveCustomer=function(guidArea,skipModal){var deferred=$q.defer();if(!guidArea||!$rootScope.hasReadAccess("Customer"))return $.Deferred().resolve(null).promise();var filter={GuidArea:guidArea,AreaContext:"ActiveHousing"},customerColumns=[];return repository.GetPaginated(repository.apiData.customer.url,0,1,null,filter,"",JSON.stringify(customerColumns)).then(function(result){if(1===result.TotalCount)return void deferred.resolve(result.List[0]);!skipModal&&result.TotalCount>1?$modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"md",resolve:{modalParams:function(){return{url:repository.apiData.customer.url,sorting:{Id:"asc"},title:translationService.translate("web-area-getActiveCustomer-title","Velg kunde"),filter:filter,columns:[{title:translationService.translate("web-customer-description"),property:"Description"}]}}}}).result.then(function(item){deferred.resolve(item)},function(){deferred.resolve(null)}):deferred.resolve(null)},function(error){deferred.reject(error)}),deferred.promise},service}angular.module("Plania").factory("AreaService",["Repository","$q","$modal","TranslationService","$rootScope",areaService])}(),function(){function controller($scope,repository,modalParams,$modalInstance,$filter,enumService,translationService){$scope.model={},$scope.model.CleaningTask={},$scope.model.Area={};var columns=["Area.Id","Area.Description","ResourceGroup.Id","Person.FirstName","Person.LastName","CleaningTask.Id","CleaningTask.CleaningType"];repository.getSingle(repository.apiData.areaXCleaningTask.url,modalParams.Guid,JSON.stringify(columns)).then(function(result){$scope.model=result.Data,$scope.model.Person&&($scope.person=$scope.model.Person.FirstName+" - "+$scope.model.Person.LastName),$scope.isUpdatePause=$scope.model.PausedFromDate&&$scope.model.PausedToDate,!$scope.isUpdatePause&&modalParams.SuggestedPause&&($scope.model.PausedFromDate=modalParams.SuggestedPause.From,$scope.model.PausedToDate=modalParams.SuggestedPause.To)}),$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"person":return filter.PropertyFilter=[{Property:"DoesCleaningTasks",Value:1,Operator:"="}],$scope.model.GuidCleaningTeam&&filter.PropertyFilter.push({Property:"GuidResourceGroup",Value:$scope.model.GuidCleaningTeam,Operator:"="}),filter;case"resourceGroup":return filter.PropertyFilter=[{Property:"DoesCleaningTasks",Value:1,Operator:"="}],filter}},$scope.ok=function(){var toSave=angular.copy($scope.model);delete toSave.Recurrence,delete toSave.Area,toSave.PausedToDate&&(toSave.PausedToDate=new Date(toSave.PausedToDate).toISOString()),toSave.PausedFromDate&&(toSave.PausedFromDate=new Date(toSave.PausedFromDate).toISOString()),toSave.RecurrenceRule&&toSave.RecurrenceRule.Unit&&enumService.setTimeUnitOnRecurrence(toSave.RecurrenceRule),toSave.AttributeValues.forEach(function(attribute){"Date"===attribute.ValueType&&"string"!=typeof attribute.DateValue&&attribute.DateValue&&(attribute.DateValue=attribute.DateValue.toISOString())}),repository.updateSingle(repository.apiData.areaXCleaningTask.url,toSave).then(function(result){$modalInstance.close("Renholdsoppgaven har blitt oppdatert.")},function(error){repository.growl(error,"danger")})},$scope.removePause=function(){$scope.model.PausedFromDate=null,$scope.model.PausedToDate=null,$scope.model.PausedReason=null,repository.updateSingle(repository.apiData.areaXCleaningTask.url,$scope.model).then(function(result){$modalInstance.close("Renholdsoppgaven har blitt oppdatert.")},function(error){repository.growl(error,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("cancel")}}angular.module("Plania").controller("AreaXCleaningTaskController",["$scope","Repository","modalParams","$modalInstance","$filter","EnumService","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,enumService){$scope.isUpdate="article.edit"===$scope.navigation.current.name,$scope.modelDto={},$scope.model={},$scope.viewMode=!!$scope.isUpdate,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.prefix=repository.commonService.prefix.Article,$scope.units=enumService.getUnits(),$scope.getUnitValue=function(value){var returnValue=_.find($scope.units,function(o){return o.value===value});return returnValue?returnValue.translatedValue:"-"};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Article,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Article,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Article),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Article)};if($scope.autoCompleteFilter=function(filterName){return{}},$scope.isUpdate){var columns=["Account.Id","Account.Description","CostCenter.Id","CostCenter.Description","Department.Id","Department.Description","Accounting0.Id","Accounting0.Description","Accounting1.Id","Accounting1.Description","Accounting2.Id","Accounting2.Description","Accounting3.Id","Accounting3.Description","Accounting4.Id","Accounting4.Description"];repository.getMainModel(repository.apiData.article.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.model.isDisabled=!!$scope.model.DisabledFromDate,$scope.reload=!0,updateAccess()},function(error){repository.growl(error,"danger")})}else{var article=$scope.model;article.PriceAdjustmentType="Undefined",article.Type="Undefined"}$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-article-success","Artikkel har blitt oppdatert."):translationService.translate("create-article-success","Artikkel har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){ "string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?(delete $scope.modelDto,delete $scope.model.Account,delete $scope.model.Department,delete $scope.model.CostCenter,delete $scope.model.Accounting0,delete $scope.model.Accounting1,delete $scope.model.Accounting2,delete $scope.model.Accounting3,delete $scope.model.Accounting4,repository.updateSingle(repository.apiData.article.url,$scope.model).then(success,error)):repository.createSingle(repository.apiData.article.url,$scope.model).then(success,error)},$scope.cancel=function(){$scope.goBack("article.list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-article-message","Artikkel vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-article-button-confirm","Ja, fjern artikkel"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.article.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-article-success","Artikkel ble fjernet!"),result,"success"),$scope.goBack("article.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.isFieldEnabled=function(field){if($scope.restrictEdit)return!1;var article=$scope.model;switch(field){case"UnitPrice":return"Undefined"===article.PriceAdjustmentType;case"PriceAdjustmentType":return"Cost"!==article.Type;case"PriceAdjustmentValue":case"CostPrice":return"Cost"!==article.Type&&"Undefined"!==article.PriceAdjustmentType;case"ShowPriceAdjustmentOnOwnLine":return!["Undefined","FixedAmount"].includes(article.PriceAdjustmentType)}return!0},$scope.isFieldVisible=function(field){var article=$scope.model;switch(field){case"RentalPeriodNumber":case"RentalPeriodUnit":return article.CanBeRentedOut;case"PriceAdjustmentType":return"Cost"!==article.Type;case"PriceAdjustmentValue":case"CostPrice":return"Cost"!==article.Type&&"Undefined"!==article.PriceAdjustmentType;case"MergeInInvoice":case"ShowPriceAdjustmentOnOwnLine":return!["Undefined","Sale","Cost","FixedPrice"].includes(article.Type)}return!0},$scope.calculateSalePrice=function(){var article=$scope.model;switch(article.PriceAdjustmentType){case"Undefined":break;case"FixedAmount":article.UnitPrice=article.PriceAdjustmentValue;break;case"AddedAmount":article.UnitPrice=article.CostPrice+article.PriceAdjustmentValue;break;case"AddedFactor":article.UnitPrice=Math.round(article.CostPrice*(1+article.PriceAdjustmentValue))}},$scope.onChange=function(field){switch(field){case"PriceAdjustmentType":case"PriceAdjustmentValue":case"CostPrice":$scope.calculateSalePrice()}},$scope.onDisabledFromDateCheckboxChange=function(){$scope.model.isDisabled?$scope.model.DisabledFromDate=(new Date).toISOString():$scope.model.DisabledFromDate=null},$scope.formattedPriceAdjustmentValue=function(value){var article=$scope.model;if(!angular.isDefined(value))return"AddedFactor"===article.PriceAdjustmentType?100*article.PriceAdjustmentValue:article.PriceAdjustmentValue;article.PriceAdjustmentValue="AddedFactor"===article.PriceAdjustmentType?value/100:value}}angular.module("Plania").controller("ArticleController",["$scope","Repository","$stateParams","TranslationService","EnumService",controller])}(),function(){function controller($scope,$modalInstance,repository,params){function pollCacheStatistics(forcePolling){"Internal"===params.ProcessingStatus||!0===forcePolling?params.getModel().then(function(){getCacheStatistics(!0)}):getCacheStatistics()}function getCacheStatistics(withPolling){repository.getSingleWithNoParameter(repository.apiData.bimFile.url+params.GuidBimFile+"/CacheStatistics").then(function(result){$scope.bimCache=result,withPolling&&setTimeout(function(){pollCacheStatistics()},5e3)})}$scope.ProcessingStatus=params.ProcessingStatus,$scope.ProcessingError=params.ProcessingError,$scope.RevisionComment=params.RevisionComment,$scope.bimCache={},getCacheStatistics(!0),$scope.resetCache=function(){repository.runAction(repository.apiData.bimFile.url+params.GuidBimFile+"/resetCache").then(function(result){params.resetCacheData(),setTimeout(function(){pollCacheStatistics(!0)},5e3)},function(error){repository.growl(error,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("Canceled")}}angular.module("Plania").controller("BimFileCacheStatusModalController",["$scope","$modalInstance","Repository","params",controller])}(),function(){function controller($scope,$stateParams,repository,translationService,$modal,$rootScope,ngTableParams,$filter,$window,config,listService){function getModel(){return repository.getSingle(repository.apiData.bimFile.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess(),setProperties(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})}function getRevisions(){repository.getSingleWithNoParameter(repository.apiData.bimFile.url+$scope.model.Guid+"/GetRevisions").then(function(result){revisions=result,$scope.revisionsTable.reload()})}$scope.isUpdate="bimFile.edit"===$scope.navigation.current.name,$scope.activateAutocomplete=!1,$scope.model={Guid:$stateParams.guid},$scope.viewMode=!!$scope.isUpdate,$scope.bimCache={},$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.BimFile,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.BimFile,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.BimFile),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.BimFile)};updateAccess();var setProperties=function(){var bimFile=$scope.model;bimFile.Building&&($scope.building=$scope.getEntityCaption(bimFile.Building))};$scope.isUpdate?getModel():$scope.activateAutocomplete=!0,$scope.update=function(destination){var success=function(result){repository.growl(translationService.translate("web-bimFile-update-success","Bim filen har blitt oppdatert"),"success"),$scope.goBack(destination,{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate&&repository.updateSingle(repository.apiData.bimFile.url,$scope.model).then(success).catch(error)},$scope.cancel=function(){$scope.goBack("bimFile.list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-bimFile-message","BIM-filen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-bimFile-button-confirm","Ja, fjern BIM-filen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.bimFile.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-bimFile-success","BIM-filen ble fjernet!"),result,"success"),$scope.goBack("bimFile.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.createNewRevision=function(){$modal.open({templateUrl:"app/bimFile/views/createBimFileModal.html",controller:"CreateBimFileModalController",resolve:{modalParams:function(){return{model:$scope.model}}}}).result.then(function(){$scope.goBack("bimFile.edit",{menuGuid:$scope.navigation.params.menuGuid}),repository.growl(translationService.translate("web-bimFile-createNewRevision-started","Ny revisjon er opprettet, og vil bli tilgjengelig når filen er ferdig prossessert."),"success")})},$scope.$on($scope.events.newSelection,function(){getModel(),updateAccess()});var revisions=[];$scope.revisionColumns=[{Position:1,Title:translationService.translate("web-bimFile-revision-version","Modellserver versjonsnummer"),Property:"version",PropertyType:"number"},{Position:2,Title:translationService.translate("web-bimFile-revision-createdAt","Opplastet"),Property:"createdAt",PropertyType:"date"},{Position:3,Title:translationService.translate("web-bimFile-revision-comment","Revisjonskommentar"),Property:"comment",PropertyType:"string"}],getRevisions();var sortFunction=function(key){return function(a,b){var aVal=a[key],bVal=b[key];return aValbVal?1:0}},getFilteredData=function(filter){var filterText=filter.searchString.toLowerCase(),data=revisions;return data=data.filter(function(product){if(void 0===filterText||null===filterText||""===filterText.trim())return!0;var state=!1;return $scope.revisionColumns.forEach(function(column){(""+product[column.Property]).toLowerCase().includes(filterText)&&(state=!0)}),state})};$scope.getFormattedDate=function(date){return $filter("date")(date,"dd.MM.yyyy, HH:mm:ss")},$scope.getPropertyValue=function(revision,column){var value=revision[column.Property];if(void 0===value||null===value||""===value)return"";if("date"===column.PropertyType)return $filter("date")(value,"dd.MM.yyyy, HH:mm:ss");var result=$filter("limitTo")(value,50);return value.length>50?result+"...":result},$scope.revisionsTable=new ngTableParams({page:1,count:10,sorting:{version:"desc"},filter:{searchString:""}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var data=getFilteredData(params.filter()),sortingKey=Object.keys(params.sorting())[0],direction=params.sorting()[sortingKey];data=data.sort(sortFunction(sortingKey)),"desc"===direction.toLowerCase()&&(data=data.reverse()),$scope.revisionsTable.settings().total=data.length,$scope.revisionsTable.settings().filterDelay=50,data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$defer.resolve(data)}}),$scope.resetCacheData=function(){$scope.model.ProcessingStatus="Internal"},$scope.showBimFileCacheStatusModal=function(){$modal.open({templateUrl:"app/bimFile/views/bimFileCacheStatusModal.html",controller:"BimFileCacheStatusModalController",resolve:{params:function(){return{GuidBimFile:$scope.model.Guid,resetCacheData:$scope.resetCacheData,getModel:getModel,ProcessingStatus:$scope.model.ProcessingStatus,ProcessingError:$scope.model.ProcessingError,RevisionComment:$scope.model.RevisionComment}}}}).result.then(function(){},function(){})},$scope.open2DMappingModal=function(){$modal.open({templateUrl:"app/bimFile/views/bimFileMappingModal.html",controller:"bimFileMappingModalController",size:"lg",resolve:{params:function(){return{GuidBimFile:$scope.model.Guid,getModel:getModel,MappingData:$scope.model.MappingData}}}}).result.then(function(){getModel()},function(){})},$scope.getRevisionOptions=function(revision){var options=[];return options.push({html:' '+translationService.translate("web-bimFile-revision-download","Last ned")+"",click:function($itemScope,$event,modelValue,text,$li){repository.getSingleWithNoParameter(repository.apiData.bimFile.url+$scope.model.Guid+"/GetRevisionDownloadToken/"+revision.id).then(function(token){var dataOwner=repository.commonService.getFilterData().selectedDataOwner.Guid;$window.open(config.baseUrlApi+repository.apiData.bimFile.url+$scope.model.Guid+"/DownloadRevision/"+revision.id+"?dataOwner="+dataOwner+"&token="+token,"_blank")},function(error){repository.showError(error)})}}),options};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.getBuildingXBimFileOptions=function(buildingXBimFile){var options=[],toggleText=buildingXBimFile.ShowAsDefault?translationService.translate("web-bimFile-buildingXBimFile-showAsDefault-false","Ikke vis modell som standard ved åpning"):translationService.translate("web-bimFile-buildingXBimFile-showAsDefault-true","Vis modell som standard ved åpning");return options.push({html:' '+toggleText+"",click:function($itemScope,$event,modelValue,text,$li){repository.patch(repository.apiData.buildingXBimFile.url,buildingXBimFile.Guid,{ShowAsDefault:!buildingXBimFile.ShowAsDefault}).then(function(result){$scope.buildingXBimFileTable.reload()},function(error){repository.showError(error)})}}),options.push(getMenuLink($rootScope.navigation.href("bimFile.viewBim",{guidBuilding:buildingXBimFile.GuidBuilding,guidBimFile:$scope.model.Guid}),translationService.translate("web-bimFile-buildingXBimFile-viewInBimsyncViewer","Gå til bim modell"))),$scope.hasReadAccess("Building")&&options.push(getMenuLink($rootScope.navigation.href("building.edit",{guid:buildingXBimFile.GuidBuilding}),translationService.translate("web-bimFile-buildingXBimFile-viewBuilding","Gå til bygg"))),$scope.hasDeleteAccess("BuildingXBimFile")&&options.push({html:' '+translationService.translate("web-bimFile-buildingXBimFile-delete","Knytt bort fra bygg")+"",click:function($itemScope,$event,modelValue,text,$li){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-buildingXBimFile-message","Knytningen immot bygg vil bli fjernet."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-buildingXBimFile-button-confirm","Ja"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.buildingXBimFile.url,buildingXBimFile.Guid).then(function(){swal.close(),$scope.buildingXBimFileTable.reload()},function(error){repository.showError(error)})})}}),options},$scope.getPropertyValue=function(entity,field){return listService.GetPropertyValue(entity,field)},$scope.buildingXBimFileColumns=[{Position:1,Title:"Bygg",Property:"Building.Id",PropertyType:"string"},{Position:2,Title:"Bygg",Property:"Building.Description",PropertyType:"string"},{Position:3,Title:"Kategori",Property:"Building.BuildingCategory.Description",PropertyType:"string"},{Position:4,Title:"Vis som standard",Property:"ShowAsDefault",PropertyType:"bool"}],$scope.buildingXBimFileTable=new ngTableParams({page:1,count:10,sorting:{"Building.Id":"asc"},filter:{searchString:"",FilterModel:{Condition:"and",Rules:[{Property:"GuidBimFile",Operator:"=",Value:$stateParams.guid}]}}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];$scope.buildingXBimFileColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.buildingXBimFile.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.buildingXBimFileTable.settings().total=result.TotalCount,$scope.buildingXBimFileTable.settings().filterDelay=500,$defer.resolve(result.List)})}}),$scope.addNewBuilding=function(){$modal.open({templateUrl:"app/bimFile/views/createBuildingXBimFileModal.html",controller:"CreateBuildingXBimFileModalController",resolve:{params:function(){return{guidBimFile:$scope.model.Guid,guidBimProject:$scope.model.GuidBimProject}}}}).result.then(function(){$scope.buildingXBimFileTable.reload()},function(){})}}angular.module("Plania").controller("BimFileController",["$scope","$stateParams","Repository","TranslationService","$modal","$rootScope","ngTableParams","$filter","$window","config","ListService",controller])}(),function(){function controller($scope,$modalInstance,params,repository,translationService){var existingColumns=params.existingColumns;$scope.enableConstantValue=params.enableConstantValue,$scope.inputMode="column",$scope.model=params.PropertyData,$scope.constantValue="",$scope.selectedColumns=null,$scope.ok=function(){"column"===$scope.inputMode?$modalInstance.close({type:"column",value:$scope.selectedColumns}):"constant"===$scope.inputMode&&$modalInstance.close({type:"constant",value:$scope.constantValue})};var match=function(textToSearch,searchValue){return!searchValue||!!textToSearch&&textToSearch.toLowerCase().includes(searchValue.toLowerCase())},searchMatch=function(col,searchString){return match(col.Title,searchString)};$scope.columnFilter=function(col){return!!searchMatch(col,$scope.searchString)&&col},$scope.selectColumn=function(column,event){event.stopPropagation(),column.Children.length>0?column.isExpanded=!column.isExpanded:(event.stopPropagation(),$modalInstance.close(column))},$scope.alreadyMapped=function(column){return!!_.contains(existingColumns,column.Title)||!!_.contains(existingColumns,column.Children.Title)},$scope.isColumnSelected=function(column){return _.contains($scope.selectedColumns,column)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("bimFileFieldMappingModalController",["$scope","$modalInstance","params","Repository","TranslationService",controller])}(),function(){function controller($scope,$modal,$modalInstance,repository,translationService,params){function getMapping(){repository.getWithUrlParameter(repository.apiData.bimFile.url+params.GuidBimFile+"/getMapping").then(function(result){$scope.model=result})}$scope.model={},$scope.PropertyData=[],getMapping(),repository.getWithUrlParameter(repository.apiData.bimFile.url+params.GuidBimFile+"/properties").then(function(result){_.forEach(result,function(col){$scope.PropertyData.push(col)})}),$scope.update=function(){var success=function(result){repository.growl(translationService.translate("web-bimFile-mapping-update-success","Mappingen har blitt oppdatert"),"success"),$modalInstance.close()},error=function(e){repository.showError(e)};repository.updateSingle(repository.apiData.bimFile.url+params.GuidBimFile+"/changeMapping",$scope.model).then(success).catch(error)},$scope.clearAttribute=function(field){$scope.model[field]=void 0},$scope.openAttributeSelectModal=function(field){$modal.open({templateUrl:"app/bimFile/views/bimFileFieldMappingModal.html",controller:"bimFileFieldMappingModalController",resolve:{params:function(){return{PropertyData:$scope.PropertyData}}}}).result.then(function(result){$scope.model[field]={Title:result.Title,PropertyName:result.PropertyName}},function(){})},$scope.cancel=function(){$modalInstance.dismiss("Canceled")}}angular.module("Plania").controller("bimFileMappingModalController",["$scope","$modal","$modalInstance","Repository","TranslationService","params",controller])}(),function(){function controller($scope,$modalInstance,repository,modalParams,listService,translationService,ngTableParams){$scope.isUpdate=!!modalParams.model,$scope.bimFile=angular.copy(modalParams.model||{}),$scope.bimFile.RevisionComment="",$scope.step={index:0},$scope.files=[],$scope.removeFile=function(index){$scope.files.splice(index,1)},$scope.onFileSelect=function($files){if($scope.isUpdate&&$files.length&&($scope.files=[]),!$scope.isUpdate&&!$scope.bimFile.Description&&$files&&$files.length&&$files[0].name){var newId=$files[0].name;newId=newId.split(".").slice(0,-1).join(""),$scope.bimFile.Description=newId}$scope.files=$scope.files.concat($files)},$scope.dragOverClass=function($event){var items=$event.dataTransfer.items,hasFile=!1;if(items){for(var i=0;i=file.total?"success":"info")};$scope.isUpdate?repository.updateSingleWithBinary(repository.apiData.bimFile.urlChunk,$scope.bimFile,$scope.files[0]).then(onSuccess,onFail,onUpdate):repository.createSingleWithBinary(repository.apiData.bimFile.urlChunk,$scope.bimFile,$scope.files).then(onSuccess,onFail,onUpdate)},$scope.selectedItems=[],$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.addSelectedItem=function(object){if($scope.isItemSelected(object)){for(var i=0;i<$scope.selectedItems.length;i++)if($scope.selectedItems[i].Guid===object.Guid)return void $scope.selectedItems.splice(i,1)}else $scope.selectedItems.push(object)},$scope.isItemSelected=function(object){return _.find($scope.selectedItems,function(o){return o.Guid===object.Guid})},$scope.buildingColumns=[{Position:1,Title:translationService.translate("web-createBimFileModal-buildingTable-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-createBimFileModal-buildingTable-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-createBimFileModal-buildingTable-buildingCategory","Kategori"),Property:"BuildingCategory.Description",PropertyType:"string"}],$scope.buildingTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){if($scope.bimFile.GuidEstate){var columns=_.map($scope.buildingColumns,"Property"),filter=angular.copy(params.filter());filter.FilterModel={Condition:"and",Rules:[{Property:"IsTemplate",Operator:"=",Value:!1},{Property:"GuidEstate",Operator:"=",Value:$scope.bimFile.GuidEstate}]},repository.GetPaginated(repository.apiData.building.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){$scope.buildingTable.settings().total=result.TotalCount,$scope.buildingTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error,"danger")})}}});var connectToSelectedBuildings=function(){if(!$scope.selectedItems.length)return void $modalInstance.close(savedFiles);var buildingXBimFiles=[];$scope.selectedItems.forEach(function(building){savedFiles.forEach(function(guidBimFile){buildingXBimFiles.push({GuidBuilding:building.Guid,GuidBimFile:guidBimFile})})}),repository.createMultiple(repository.apiData.buildingXBimFile.url,buildingXBimFiles).then(function(){repository.growl(translationService.translate("web-createBimFileModal-connectToSelectedBuildings-success","Bim filer er knyttet til valgte bygg"),"success"),$modalInstance.close(savedFiles)},function(error){repository.showError(error)})};$scope.ok=function(){$scope.isUpdate?$modalInstance.close():$scope.selectedItems.length?connectToSelectedBuildings():$modalInstance.close(savedFiles)},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("CreateBimFileModalController",["$scope","$modalInstance","Repository","modalParams","ListService","TranslationService","ngTableParams",controller])}(),function(){function controller($scope,$modalInstance,repository,params,listService,translationService,ngTableParams){var guidBimFile=params.guidBimFile,guidBimProject=params.guidBimProject;$scope.selectedItems=[],$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.addSelectedItem=function(object){if($scope.isItemSelected(object)){for(var i=0;i<$scope.selectedItems.length;i++)if($scope.selectedItems[i].Guid===object.Guid)return void $scope.selectedItems.splice(i,1)}else $scope.selectedItems.push(object)},$scope.isItemSelected=function(object){return _.find($scope.selectedItems,function(o){return o.Guid===object.Guid})},$scope.buildingColumns=[{Position:1,Title:translationService.translate("web-createBuildingXBimFileModal-buildingTable-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-createBuildingXBimFileModal-buildingTable-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-createBuildingXBimFileModal-buildingTable-buildingCategory","Kategori"),Property:"BuildingCategory.Description",PropertyType:"string"}],$scope.buildingTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{GuidBimFileAlreadyConnected:guidBimFile,FilterModel:{Condition:"and",Rules:[{Property:"IsTemplate",Operator:"=",Value:!1},{Property:"Estate.GuidBimProject",Operator:"=",Value:guidBimProject}]}}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){var columns=_.map($scope.buildingColumns,"Property");repository.GetPaginated(repository.apiData.building.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.buildingTable.settings().total=result.TotalCount,$scope.buildingTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error,"danger")})}}),$scope.connectToSelectedBuildings=function(){var buildingXBimFiles=[];$scope.selectedItems.forEach(function(building){buildingXBimFiles.push({GuidBuilding:building.Guid,GuidBimFile:guidBimFile})}),buildingXBimFiles.length&&repository.createMultiple(repository.apiData.buildingXBimFile.url,buildingXBimFiles).then(function(){repository.growl(translationService.translate("web-createBimFileModal-connectToSelectedBuildings-success","Bim filer er knyttet til valgte bygg"),"success"),$modalInstance.close()},function(error){repository.showError(error)})},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("CreateBuildingXBimFileModalController",["$scope","$modalInstance","Repository","params","ListService","TranslationService","ngTableParams",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,ngTableParams,generalOptionsService,listService,$localStorage){$scope.generalOptions=angular.copy($localStorage.generalOptions),$scope.refreshId=(new Date).toISOString(),$scope.dataOwners=[],$scope.search={};var getGeneralOptions=function(refreshImage){generalOptionsService.getGeneralOptionsAsync(!0).then(function(generalOptions){$scope.generalOptions=angular.copy(generalOptions),refreshImage&&($scope.refreshId=(new Date).toISOString())})};getGeneralOptions(),$scope.onImageFileSelect=function(images,isLogo){function handleFileUpload(file){var reader=new FileReader;reader.onload=function(e){var newFile={ImageSrc:e.target.result.substr(e.target.result.indexOf("base64,")+"base64,".length),Name:file.name};files.push(newFile),onLoadEndHandler()},reader.readAsDataURL(file)}function onLoadEndHandler(image){var url=repository.apiData.generalOptions.url+"backgroundImage";isLogo&&(url=repository.apiData.generalOptions.url+"logoImage"),repository.createMultiple(url,files).then(function(result){var successMessage=isLogo?translationService.translate("web-branding-imageLogo-update-success","Logo har blitt oppdatert"):translationService.translate("web-branding-imageBackground-update-success","Bakgrunnsbilde har blitt oppdatert");repository.growl(successMessage,"success"),getGeneralOptions(!0)},function(error){error&&repository.growl(error,"danger")})}var files=[];images&&0!==images.length&&handleFileUpload(images[0])},$scope.deleteImage=function(isLogo){var url=repository.apiData.generalOptions.url+"backgroundImage/";isLogo&&(url=repository.apiData.generalOptions.url+"logoImage/"),repository.deleteSingle(url,"").then(function(result){var successMessage=isLogo?translationService.translate("web-branding-imageLogo-delete-success","Logo har blitt slettet"):translationService.translate("web-branding-imageBackground-delete-success","Bakgrunnsbilde har blitt nullstilt");repository.growl(successMessage,"success"),getGeneralOptions(!0)},function(error){repository.growl(error)})},$scope.dataOwnerTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"}},{total:0,counts:[10,25,50],filterDelay:50,paginationMaxBlocks:6,getData:function($defer,params){if($scope.hasReadAccess("DataOwner")){var columns=["Id","Description"];repository.GetPaginated(repository.apiData.dataOwner.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.dataOwnerTable.settings().total=result.TotalCount,$scope.dataOwnerTable.settings().filterDelay=500,$scope.dataOwners=result.List,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}});var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.dataOwnerContextMenu=function(dataOwner){var options=[];return options.push(getMenuLink($scope.navigation.href("dataOwner.edit",{guid:dataOwner.Guid}),translationService.translate("web-branding-dataOwnerContextMenu-viewDataOwner","Gå til klient"))),options}}angular.module("Plania").controller("BrandingController",["$scope","Repository","$stateParams","TranslationService","ngTableParams","GeneralOptionsService","ListService","$localStorage",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,ngTableParams,$modal,listService,$localStorage){$scope.isUpdate="budget.edit"===$scope.navigation.current.name,$scope.model={},$scope.modelDto={},$scope.viewMode=!!$scope.isUpdate,$scope.prefix=repository.commonService.prefix.Budget ;var yearRangeStart=$localStorage.generalOptions.YearRangeStart,yearRangeEnd=$localStorage.generalOptions.YearRangeEnd,year=yearRangeStart;for($scope.years=[],$scope.search={};$scope.years.length<=yearRangeEnd-yearRangeStart;)$scope.years.push(year),year++;var updateAccess=function(){if($scope.isUpdate){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Budget,checkOtherDo),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Budget,checkOtherDo)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Budget)},setProperties=function(){$scope.model.Service&&($scope.service=$scope.getEntityCaption($scope.model.Service))},columns=["Service.Id","Service.Description","Account.Id","Account.Description","Accounting0.Id","Accounting0.Description","Accounting1.Id","Accounting1.Description","Accounting2.Id","Accounting2.Description","Accounting3.Id","Accounting3.Description","Accounting4.Id","Accounting4.Description","Department.Id","Department.Description","CostCenter.Id","CostCenter.Description"];$scope.isUpdate?repository.getMainModel(repository.apiData.budget.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.reload=!0,updateAccess(),setProperties(),getCardTables()},function(error){repository.growl(error,"danger"),"Ingen data funnet"===error&&($scope.notFoundError=!0)}):$scope.model.Year=moment().year(),$scope.purchaseOrderItemColumns=[{Position:1,Title:translationService.translate("web-purchaseOrder-Id"),Property:"PurchaseOrder.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-purchaseOrderItem-Id"),Property:"Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-purchaseOrderItem-Description"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-supplier-Description","Leverandør navn"),Property:"Supplier.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-purchaseOrderItem-OrderedQuantity"),Property:"OrderedQuantity",PropertyType:"number"},{Position:6,Title:translationService.translate("web-purchaseOrderItem-UnitPrice"),Property:"UnitPrice",PropertyType:"double"},{Position:7,Title:translationService.translate("web-purchaseOrderItem-OrderedAmount"),Property:"OrderedAmount",PropertyType:"double"},{Position:8,Title:translationService.translate("web-purchaseOrderItem-Status"),Property:"Status",PropertyType:"enum.purchaseorderitemstatus"}],$scope.costColumns=[{Position:1,Title:translationService.translate("web-cost-InvoiceNumber"),Property:"InvoiceNumber",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cost-Description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-account-id"),Property:"Account.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-account-description"),Property:"Account.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-cost-amount"),Property:"Amount",PropertyType:"double"},{Position:6,Title:translationService.translate("web-cost-InvoiceDate"),Property:"InvoiceDate",PropertyType:"date"},{Position:7,Title:translationService.translate("web-supplier-description"),Property:"Supplier.Description",PropertyType:"string"},{Position:8,Title:translationService.translate("web-cost-vouchernumber"),Property:"VoucherNumber",PropertyType:"string"}];var getCardTables=function(){var purchaseOrderItemTableFilter={GuidBudget:$scope.model.Guid};$scope.purchaseOrderItemTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:purchaseOrderItemTableFilter},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];$scope.purchaseOrderItemColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.purchaseOrderItem.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.purchaseOrderItemTable.settings().total=result.TotalCount,$scope.purchaseOrderItemTable.settings().filterDelay=500,$defer.resolve(result.List)})}}),$scope.purchaseOrderItemAllocatedTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{GuidBudget:$scope.model.Guid,PropertyFilter:[{Property:"Status",Operator:">",Value:"0"}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];$scope.purchaseOrderItemColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.purchaseOrderItem.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.purchaseOrderItemAllocatedTable.settings().total=result.TotalCount,$scope.purchaseOrderItemAllocatedTable.settings().filterDelay=500,$defer.resolve(result.List)})}});var costTableFilter={GuidBudget:$scope.model.Guid};$scope.costTable=new ngTableParams({page:1,count:10,sorting:{InvoiceNumber:"asc"},filter:costTableFilter},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];$scope.costColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.cost.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.costTable.settings().total=result.TotalCount,$scope.costTable.settings().filterDelay=500,$defer.resolve(result.List)})}})};$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.$watch("model.SumBudget",function(newValue,oldValue){newValue!==oldValue&&($scope.model.SumNotSpecified=newValue-$scope.model.SumSpecified,$scope.model.SumForDisposal=newValue-$scope.model.SumAllocated-$scope.model.SumCost,$scope.model.SumRestNotSpecified=$scope.model.SumForDisposal-$scope.model.SumRestSpecified,void 0===$scope.isDirtyBudgetSum?$scope.isDirtyBudgetSum=!1:$scope.isDirtyBudgetSum=!0)},!0),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-budget-success","Budsjett har blitt oppdatert."):translationService.translate("create-budget-success","Budsjett har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.budget.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.budget.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-priority-message","Prioritet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-budget-button-confirm","Ja, fjern budsjett"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.budget.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-budget-success","Budsjett ble fjernet!"),result,"success"),$scope.goBack("budget.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.goToPurchaseOrder=function(item){$scope.navigation.go("purchaseOrder.edit",{guid:item.GuidPurchaseOrder})},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"service":filter.FilterModel={Condition:"and",Rules:[{Property:"IsBudgetable",Operator:"=",Value:!0}]}}return filter}}angular.module("Plania").controller("BudgetController",["$scope","Repository","$stateParams","TranslationService","ngTableParams","$modal","ListService","$localStorage",controller])}(),function(){function controller($scope,ngTableParams,repository,translationService,$stateParams,$rootScope,listService){$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.viewMode=!0,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.areaColumns=[{Position:1,Title:translationService.translate("web-area-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-area-description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-area-areaCategory"),Property:"AreaCategory.Description",PropertyType:"string"}]}angular.module("Plania").directive("buildingAreaDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",activateAutocomplete:"=activateAutocomplete"},controller:["$scope","ngTableParams","Repository","TranslationService","$stateParams","$rootScope","ListService",controller],templateUrl:"app/building/views/buildingArea.html"}})}(),function(){function controller($scope,repository,$stateParams,$modal,$state,translationService,$location,listService,$sce){$scope.isUpdate="building.edit"===$scope.navigation.current.name,$scope.activateAutocomplete=!1,$scope.reloadDocumentTable=!1,$scope.reloadDeviations=!1,$scope.reloadOperationalMessages=!1,$scope.barcode={},$scope.model={Guid:$stateParams.guid},$scope.dropdownValues={};var availableHashLocations=["#info","#area","#equipment","#maintenance","#image"],updateLocation=function(){var hash=window.location.hash;hash&&availableHashLocations.includes(hash)?($('#buildingTabs a[data-target="'+hash+'"]').tab("show"),$scope.currentTab=hash.substr(1)):($('#buildingTabs a[data-target="#info"]').tab("show"),$scope.currentTab="info")};$scope.$on("$locationChangeSuccess",function(event,newUrl,oldUrl){updateLocation()}),$scope.setTab=function(tab){$location.hash(tab).replace()},$scope.isUpdate&&$stateParams.tab?($scope.setTab($stateParams.tab),updateLocation()):updateLocation();var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Building,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Building,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Building),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Building)};if(updateAccess(),$scope.isUpdate){var columns=["Estate.Id","Estate.Description","Estate.Guid","BuildingCategory.Description","BuildingCategory.Icon","BuildingCategory.Color","CostCenter.Description","CostCenter.Id","Region.Id","BuildingType.Id","BuildingType.Description","BuildingType.IndexPosition","BuildingType.ExplanatoryText1","BuildingType.ExplanatoryText2","BuildingType.GuidParent","BuildingType.ReferenceType.Id","BuildingType.ReferenceType.Description","BuildingType.ReferenceType.ExplanatoryText","BusinessUnit.Id","BusinessUnit.Description","BusinessUnit.IndexPosition","BusinessUnit.ExplanatoryText1","BusinessUnit.ExplanatoryText2","BusinessUnit.GuidParent","BusinessUnit.ReferenceType.Id","BusinessUnit.ReferenceType.Description","BusinessUnit.ReferenceType.ExplanatoryText","OperationsManager.Guid","OperationsManager.FirstName","OperationsManager.LastName","UserAreaComputedBy.RealName","UserCafComputedBy.RealName","Owner.Id","Owner.Description","ExternalFacilityManager.Id","ExternalFacilityManager.Description","FacilityManager.FirstName","FacilityManager.LastName","ManagerPerson1.FirstName","ManagerPerson1.LastName","ManagerPerson2.FirstName","ManagerPerson2.LastName"];repository.getMainModel(repository.apiData.building.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){if($scope.reload=!0,$scope.model=response.Data,$scope.model.IsTemplate)return void $state.go("buildingTemplate.edit",{guid:$scope.model.Guid,model:$scope.model},{location:"replace"});updateAccess(),$scope.reloadDocumentTable=!0,$scope.reloadDeviations=!0,$scope.reloadOperationalMessages=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})}else{var getCategoryPrefill=function(guid){var guidCategory=guid||$scope.model.GuidBuildingCategory;guidCategory&&repository.getSingle(repository.apiData.buildingCategory.url,guidCategory).then(function(result){$scope.model.DynamicProperty=result.Data.DynamicProperty},function(error){repository.growl(error,"danger")})},webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);if(webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value)switch(prefill.Property){case"Estate":$scope.model.Estate={Guid:prefill.Value.Guid,Caption:prefill.Value.Label},$scope.model.GuidEstate=prefill.Value.Guid;break;case"BuildingCategory":$scope.model.BuildingCategory={Guid:prefill.Value.Guid,Caption:prefill.Value.Label},$scope.model.GuidBuildingCategory=prefill.Value.Guid;break;case"CostCenter":$scope.model.CostCenter={Guid:prefill.Value.Guid,Caption:prefill.Value.Label},$scope.model.GuidCostCenter=prefill.Value.Guid}else $scope.model[prefill.Property]=prefill.Value}),$stateParams.guidEntityToCopy&&repository.getSingle(repository.apiData.building.url,$stateParams.guidEntityToCopy).then(function(result){delete result.Data.Guid,delete result.Data.GuidGisEntity,$scope.model=result.Data,$scope.model.Id+="-N",$scope.reload=!0}),$stateParams.showPersistantData){var persistentData=repository.persistedData.getPersistedData("building.create");persistentData&&($scope.model.Estate={Guid:persistentData.GuidEstate,Caption:persistentData.Estate},$scope.model.GuidEstate=persistentData.GuidEstate)}$stateParams.guidEntityToCopy||getCategoryPrefill(),$scope.model.CountryCode||($scope.model.CountryCode=repository.commonService.getFilterData().selectedDataOwner.CountryCode),$scope.activateAutocomplete=!0}$scope.updateBuilding=function(destination){var success=function(result){repository.growl($scope.isUpdate?"Bygg har blitt oppdatert.":"Bygg har blitt opprettet","success"),repository.commonService.getFilterData().selectedSelection.Guid&&repository.growl("Bygget har blitt lagt til gjeldende utvalg.","success");var buildingGuid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,buildingGuid);var hash=window.location.hash;hash&&(hash=hash.substr(1)),$scope.goBack(destination,{guid:buildingGuid,menuGuid:$scope.navigation.params.menuGuid,tab:hash})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?($scope.barcode.Id&&repository.createSingle(repository.apiData.barcode.url,$scope.barcode).then(function(result){},function(error){repository.growl(error,"danger")}),repository.updateSingle(repository.apiData.building.url,$scope.model).then(success).catch(error)):($scope.model.BuildingXBuildingSelectionsToCreate=[{GuidBuildingSelection:repository.commonService.getFilterData().selectedSelection.Guid}],repository.createSingle(repository.apiData.building.url,$scope.model).then(success,error))},$scope.changeId=function(){$modal.open({templateUrl:"app/common/modal/views/changeIdModal.html",controller:"ChangeIdModalController",size:"md",resolve:{params:function(){return{id:$scope.model.Id}}}}).result.then(function(id){id&&repository.patch(repository.apiData.building.url,$scope.model.Guid,{Id:id}).then(function(result){repository.growl(translationService.translate("web-building-changeId-success","Id ble oppdatert"),"success"),$scope.model.Id=id},function(error){repository.showError(error)})})},$scope.removeBuilding=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-building-message","Bygningen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-building-button-confirm","Ja, fjern bygningen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.building.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-building-success","Bygningen ble fjernet!"),result,"success"),repository.growl("Bygningen har blitt fjernet","success"),$scope.goBack("building.list",{menuGuid:$scope.navigation.params.menuGuid})},function(error){swal({title:"Kunne ikke slette bygget!",text:error.Message+"

    Vil du deaktivere bygget?",type:"error",html:!0,showCancelButton:!0,confirmButtonText:"Deaktiver",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.Id="#"+$scope.model.Id,$scope.model.IsDeactivated=!0,$scope.updateBuilding("building.list"))})})})},$scope.cancel=function(){$scope.goBack("building.list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("BuildingController",["$scope","Repository","$stateParams","$modal","$state","TranslationService","$location","ListService","$sce",controller])}(),function(){function controller($scope,translationService,$rootScope,$timeout){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.hasPageLoaded="equipment"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"equipment"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)});$scope.areaColumns=[{Position:1,Title:translationService.translate("web-area-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-area-description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-area-areaCategory"),Property:"AreaCategory.Description",PropertyType:"string"}]}angular.module("Plania").directive("buildingEquipmentDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",currentTab:"=currentTab"},controller:["$scope","TranslationService","$rootScope","$timeout",controller],templateUrl:"app/building/views/buildingEquipment.html"}})}(),function(){function controller($scope,$timeout,$rootScope){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasEditAccess=$rootScope.hasEditAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.hasPageLoaded="image"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"image"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)})}angular.module("Plania").directive("buildingImageDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",activateAutocomplete:"=activateAutocomplete"},controller:["$scope","$timeout","$rootScope",controller],templateUrl:"app/building/views/buildingImage.html"}})}(),function(){function controller($scope,ngTableParams,repository,translationService,$modal,$rootScope,listService,$timeout,registeredFieldService,$localStorage){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasEditAccess=$rootScope.hasEditAccess,$scope.hasModule=$rootScope.hasModule,$scope.userInfo=$rootScope.userInfo,$scope.customization=$rootScope.customization,$scope.generalOptions=$localStorage.generalOptions,$scope.imageApiUrl=$rootScope.imageApiUrl,$scope.hideId=$localStorage.generalOptions.HideIdOnEstateAndBuildingCreation&&"building.edit"!==$rootScope.navigation.current.name,$scope.isDynamicPropertiesCollapsed=!1,$scope.isDocumentsCollapsed=!0,$scope.viewMode=$scope.isUpdate,$scope.hasPageLoaded="info"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"info"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)});$scope.$watchCollection("model.Images",function(){if($scope.model&&$scope.model.Images&&Array.isArray($scope.model.Images)){var defaultImage=$scope.model.Images.find(function(img){return img.IsDefault});defaultImage?$scope.model.GuidDefaultImage=defaultImage.Guid:delete $scope.model.GuidDefaultImage}}),$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.getPropertyValue=function(building,column){return listService.GetPropertyValue(building,column)},$scope.onEstateSelect=function(estate){if(!estate)return void($scope.model.GuidEstate="");estate.GuidBusinessUnit&&!$scope.model.GuidBusinessUnit&&($scope.model.GuidBusinessUnit=estate.GuidBusinessUnit,$scope.model.BusinessUnit=estate.BusinessUnit),$scope.model.GuidEstate=estate.Guid},$scope.onPostCodeSelect=function(postalInfo){postalInfo?($scope.model.PostalCode=postalInfo.ZipCode,$scope.model.GuidPost=postalInfo.Guid,$scope.model.PostalArea=postalInfo.PostalArea,$scope.model.County=postalInfo.County,$scope.model.Municipality=postalInfo.MunicipalityName,$scope.postalInfo=postalInfo):($scope.model.GuidPost=null,$scope.model.PostalArea="",$scope.model.County="",$scope.model.Municipality="")},$scope.countryCodeChanged=function(){$scope.model.CountryCode&&"Undefined"!==$scope.model.CountryCode&&($scope.model.PostalCode=null,$scope.onPostCodeSelect(null))},$scope.onBuildingCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidBuildingCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidBuildingCategory=category.Guid},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"postal":return-1!==$scope.model.CountryCode&&"Undefined"!==$scope.model.CountryCode&&(filter.FilterModel={Condition:"and",Rules:[{Property:"CountryCode",Operator:"=",Value:$scope.model.CountryCode}]}),filter;case"person":return filter.PropertyFilter=[{Property:"IsOperationsManager",Operator:"=",Value:!0}],filter;case"buildingCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter;case"buildingType":return filter.FilterModel={Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null}]},{Property:"ReferenceType.Context",Operator:"=",Value:1}]},filter;case"businessUnit":return filter.FilterModel={Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null}]},{Property:"ReferenceType.Context",Operator:"=",Value:3}]},filter}},$scope.supplierInfo=new function(){var me=this;this.showSupplierLineOfBusiness=!1,this.columns=[{Position:1,Title:translationService.translate("web-building-buildingXSupplier-supplier-id","Leverandør"),Property:"Supplier.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-building-buildingXSupplier-supplier-supplierLineOfBusiness","Bransje"),Property:"Supplier.SupplierLineOfBusiness.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-building-buildingXSupplier-supplier-address1","Adresse"),Property:"Supplier.Address1",PropertyType:"string"},{Position:5,Title:translationService.translate("web-building-buildingXSupplier-supplier-postalcode","Postnr."),Property:"Supplier.PostalCode",PropertyType:"string"},{Position:6,Title:translationService.translate("web-building-buildingXSupplier-supplier-postalarea","Poststed"),Property:"Supplier.PostalArea",PropertyType:"string"},{Position:7,Title:translationService.translate("web-building-buildingXSupplier-supplier-email","E-post"),Property:"Supplier.Email",PropertyType:"string"}],this.getPropertyValue=function(item,column){return"Supplier.Id"===column.Property?item.Supplier?item.Supplier.Caption:"":listService.GetPropertyValue(item,column)},this.initRegisteredFields=function(){registeredFieldService.getFieldRule(repository.commonService.prefix.Supplier,"GuidSupplierLineOfBusiness").then(function(result){me.showSupplierLineOfBusiness=!(result.Hidden||$scope.userInfo.isExternalUser&&result.ExternallyHidden)})},this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{"Supplier.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidBuilding",Operator:"=",value:$scope.model.Guid}]}},{total:0,counts:[10,20,50],filterDelay:10,paginationMaxBlocks:6,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("Supplier.Description"),columns.push("Supplier.GuidSupplierLineOfBusiness"),me.isLoading=!0,repository.GetPaginated(repository.apiData.buildingSupplier.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.isLoading=!1,me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){me.isLoading=!1,repository.growl(error,"danger")})}}))},this.add=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Velg leverandører",columns:[{Title:translationService.translate("web-supplier-id"),Property:"Id"},{Title:translationService.translate("web-supplier-description"),Property:"Description"}],useObjects:!1,url:repository.apiData.supplier.url,sorting:{Id:"asc"},filter:{},alreadySavedGuids:function(){var selectedGuids=[];return me.table.data.forEach(function(entity){selectedGuids.push(entity.GuidSupplier)}),selectedGuids}()}}}}).result.then(function(selectedEntities){var buildingXSupplier=[];selectedEntities.forEach(function(entity){buildingXSupplier.push({GuidBuilding:$scope.model.Guid,GuidSupplier:entity})}),repository.createMultiple(repository.apiData.buildingSupplier.url,buildingXSupplier).then(function(result){repository.growl("Leverandør(er) har blitt latt til bygg","success"),me.table.reload()})})},this.remove=function(supplier){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-building-supplier-message","Knytning til leverandør vil bli slettet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-building-supplier-button-confirm","Ja, fjern knytning"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.buildingSupplier.url,supplier.Guid).then(function(result){repository.growl(translationService.translate("web-swal-building-supplier-success","Knytning av leverandør ble fjernet!"),"success"),me.table.reload()})})},this.contextMenuOptions=function(item){var options=[];return $scope.hasReadAccess("Supplier")&&options.push(getMenuLink($rootScope.navigation.href("supplier.edit",{guid:item.GuidSupplier}),translationService.translate("web-building-buildingXSupplier-viewSupplier","Gå til leverandør"))),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-building-buildingXSupplier-delete","Slett knytning")+"",click:function($itemScope,$event,modelValue,text,$li){me.remove(item)}}),item.Supplier.Email&&options.push(getMenuLink("mailto:{{supplier.Supplier.Email}}",translationService.translate("web-building-buildingXSupplier-send-mail","Send mail"))),options},this.canCreate=function(){return $scope.hasCreateAccess("BuildingXSupplier")},this.canEdit=function(item){return item&&$scope.hasEditAccess("BuildingXSupplier")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("BuildingXSupplier")},this.initTable(),this.initRegisteredFields()};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.buildingPersonInfo=new function(){var me=this;this.isLoading=!1,this.columns=[{Position:1,Title:translationService.translate("web-building-buildingXPerson-person-firstname","Navn"),Property:"Person.FirstName",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-buildingXPerson-person-telephone","Telefon"),Property:"Person.TelephoneWork",PropertyType:"string",SortingDisabled:!0},{Position:3,Title:translationService.translate("web-building-buildingXPerson-resourcegroup-id","Ressurs"),Property:"Person.ResourceGroup.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidResourceGroup",AutocompleteService:"resourceGroup"},{Position:4,Title:translationService.translate("web-building-buildingXPerson-personrole-id","Rolle"),Property:"PersonRole.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidPersonRole",AutocompleteService:"personRole"},{Position:1,Title:translationService.translate("web-building-buildingXPerson-person-email","E-post"),Property:"Person.Email",PropertyType:"string"}],this.getPropertyValue=function(item,column){if("Person.FirstName"===column.Property)return item.Person?item.Person.Caption:"";if("Person.TelephoneWork"===column.Property){if(!item.Person)return"";var texts=[];return item.Person.TelephoneWork&&texts.push(item.Person.TelephoneWork),item.Person.Cellphone&&texts.push(item.Person.Cellphone),texts.join(" / ")}return listService.GetPropertyValue(item,column)},this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{"Person.FirstName":"asc"},filter:{PropertyFilter:[{Property:"GuidBuilding",Operator:"=",Value:$scope.model.Guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("Person.LastName"),columns.push("Person.Cellphone"),me.isLoading=!0,repository.GetPaginated(repository.apiData.buildingPerson.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.isLoading=!1,me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500, $defer.resolve(result.List)},function(error){me.isLoading=!1,repository.growl(error,"danger")})}}))},this.add=function(){$modal.open({templateUrl:"app/buildingPerson/views/createBuildingPerson.html",controller:"BuildingPersonController",resolve:{params:function(){return{GuidBuilding:$scope.model.Guid,selectedEntityGuids:_.map(me.table.data,function(row){return{GuidPerson:row.GuidPerson,GuidBuilding:row.GuidBuilding,GuidPersonRole:row.GuidPersonRole}}),buildingCaption:$scope.model.Id+" - "+$scope.model.Description,isModal:!0}}}}).result.then(function(selectedPersons){me.table.reload()},function(){})},this.edit=function(item){$modal.open({templateUrl:"app/buildingPerson/views/editBuildingPerson.html",controller:"BuildingPersonController",resolve:{params:function(){return{modalParam:{isUpdate:!0},guid:item.Guid,isModal:!0}}}}).result.then(function(){me.table.reload()},function(){})},this.remove=function(buildingXPerson){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-building-person-message","Dette bygget bli frakoblet personen!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-building-person-button-confirm","Ja, fjern knytning"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.buildingPerson.url,buildingXPerson.Guid).then(function(result){swal("Suksess!",translationService.translate("web-swal-building-person-success","Knytning ble fjernet!"),"success"),me.table.reload()})})},this.contextMenuOptions=function(item){var options=[];return $scope.hasReadAccess("Person")&&options.push(getMenuLink($rootScope.navigation.href("person.edit",{guid:item.GuidPerson}),translationService.translate("web-building-buildingXPerson-viewPerson","Gå til person"))),me.canEdit(item)&&options.push({html:' '+translationService.translate("web-building-buildingXPerson-edit","Rediger")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.buildingPersonInfo.edit(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-building-buildingXPerson-delete","Slett knytning")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.buildingPersonInfo.remove(item)}}),item.Person.Email&&options.push(getMenuLink("mailto:{{person.Person.Email}}",translationService.translate("web-building-buildingXPerson-send-mail","Send mail"))),options},this.canCreate=function(){return $scope.hasCreateAccess("BuildingXPerson")},this.canEdit=function(item){return item&&$scope.hasEditAccess("BuildingXPerson")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("BuildingXPerson")},this.initTable()},$scope.contractInfo=new function(){var me=this;this.isLoading=!1,this.columns=["Id","Description","Customer.Id","Customer.Description","StartDate","EndDate","Status"],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{PropertyFilter:[{Property:"ContractItems.GuidBuilding",Operator:"=",Value:$scope.model.Guid},{Property:"ContractItems.IsCurrentVersion",Operator:"=",Value:"true"}]}},{total:0,counts:[10,20,50],filterDelay:10,paginationMaxBlocks:6,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col)}),this.isLoading=!0,repository.GetPaginated(repository.apiData.contract.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){this.isLoading=!1,me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){this.isLoading=!1,repository.growl(error,"danger")})}}))},this.initTable()},$scope.getBuildingTypeColumns=function(){return[{Title:translationService.translate("web-buildingType-indexPosition","Indeks"),Property:"IndexPosition"},{Title:translationService.translate("web-buildingType-id","Id"),Property:"Id"},{Title:translationService.translate("web-buildingType-description","Beskrivelse"),Property:"Description"}]},$scope.getBusinessUnitColumns=function(){return[{Title:translationService.translate("web-businessUnit-indexPosition","Indeks"),Property:"IndexPosition"},{Title:translationService.translate("web-businessUnit-id","Id"),Property:"Id"},{Title:translationService.translate("web-businessUnit-description","Beskrivelse"),Property:"Description"}]},$scope.openReferenceData=function(type){var guid="",initialModel=null;switch(type){case"BusinessUnit":guid=$scope.model.GuidBusinessUnit,initialModel=$scope.model.BusinessUnit;break;case"BuildingType":guid=$scope.model.GuidBuildingType,initialModel=$scope.model.BuildingType}guid&&$modal.open({templateUrl:"app/referenceData/views/referenceDataInfoModal.html",controller:"ReferenceDataInfoModalController",resolve:{modalParams:function(){return{guid:guid,initialModel:initialModel}}},size:"lg"})},$scope.getPropertyCadastralNumber=function(){if(!($scope.model.PropertyCadastralNumber||$scope.model.PropertyUnitNumber||$scope.model.PropertyLeaseholdNumber||$scope.model.PropertyUnderNumber))return"-";var str=$scope.model.PropertyUnderNumber||"";return str&&(str+="/"),str+=$scope.model.PropertyLeaseholdNumber||"",str&&(str+="/"),str+=$scope.model.PropertyUnitNumber||"",str+="/",str+=$scope.model.PropertyCadastralNumber||"",str.split("/").reverse().join("/")},$scope.showAddressSearchModal=function(){$modal.open({templateUrl:"app/address/views/addressSearchModal.html",controller:"AddressSearchController",resolve:{modalParams:function(){return{}}},size:"lg"}).result.then(function(selectedAddress){$scope.model.PostalCode=selectedAddress.Address.PostalCode,$scope.model.PostalArea=selectedAddress.Address.PostalArea,$scope.model.Address=selectedAddress.Address.StreetAddress,$scope.model.PropertyCadastralNumber=selectedAddress.PropertyCadastralNumber,$scope.model.PropertyUnitNumber=selectedAddress.PropertyUnitNumber,$scope.model.PropertyLeaseholdNumber=selectedAddress.PropertyLeaseholdNumber,$scope.model.PropertyUnderNumber=selectedAddress.PropertyUnderNumber})}}angular.module("Plania").directive("buildingInfoDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate",reloadOperationalMessages:"=reloadOperationalMessages",reloadDocumentTable:"=reloadDocumentTable",activateAutocomplete:"=activateAutocomplete",currentTab:"=currentTab",formReference:"="},controller:["$scope","ngTableParams","Repository","TranslationService","$modal","$rootScope","ListService","$timeout","RegisteredFieldService","$localStorage",controller],templateUrl:"app/building/views/buildingInfo.html"}})}(),function(){function controller($scope,repository,translationService,$rootScope){$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.workOrderColumns=[{Position:1,Title:translationService.translate("web-workorder-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-workorder-description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-workorder-equipment"),Property:"Equipment.Description",PropertyType:"autocomplete",AutocompleteProperty:"GuidBuildingCategory",AutocompleteService:"buildingCategory"},{Position:4,Title:translationService.translate("web-workOrder-resourceGroup"),Property:"ResourceGroup.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidResourceGroup",AutocompleteService:"resourceGroup"},{Position:5,Title:translationService.translate("web-workorder-startdate"),Property:"StartDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-workorder-enddate"),Property:"EndDate",PropertyType:"date"}],$scope.createWorkOrder=function(){repository.persistedData.setPersistedData("workOrder.create",{model:{GuidEstate:$scope.model.GuidEstate,GuidBuilding:$scope.model.GuidBuilding},guidEstate:$scope.model.Estate?$scope.model.Estate.Guid:null,estate:$scope.model.Estate?$scope.model.Estate.Caption:null,guidBuilding:$scope.model.Guid,building:$scope.model.Caption}),$scope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})}}angular.module("Plania").directive("buildingMaintenanceDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate",reloadDeviations:"=reloadDeviations"},controller:["$scope","Repository","TranslationService","$rootScope",controller],templateUrl:"app/building/views/buildingMaintenance.html"}})}(),function(){function controller($scope,$modalInstance,params,repository){$scope.persons=params.selectedPersons,$scope.ok=function(){$modalInstance.close($scope.persons)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("SelectPersonRoleModalContreoller",["$scope","$modalInstance","params","Repository",controller])}(),function(){function controller($scope,$stateParams,repository,$localStorage,ngTableParams,translationService,params,$modalInstance,$filter,$modal){if($scope.activateAutocomplete=!1,params.modalParam&¶ms.modalParam.isUpdate){var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.BuildingXPerson,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.BuildingXPerson,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.BuildingXPerson),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.BuildingXPerson)},columns=["Building.Id","Building.Description","Person.FirstName","Person.LastName","PersonRole.Id"];repository.getSingle(repository.apiData.buildingPerson.url,params.guid,JSON.stringify(columns)).then(function(response){$scope.fieldRules=response.FieldRules,$scope.reload=!0,$scope.model=response.Data,updateAccess(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})}$scope.isAddingBuilding=!!params.GuidPerson,$scope.usePersonRole=$localStorage.generalOptions.UsePersonRole,$scope.isAddingBuilding?$scope.Title=translationService.translate("web-buildingXPerson-addBuilding-title","Legg til bygg"):$scope.Title=translationService.translate("web-buildingXPerson-addPerson-title","Legg til person");var selectedEntities=[];$scope.usePersonRole=$localStorage.generalOptions.UsePersonRole,$scope.isAddingBuilding?$scope.columns=[{Position:1,Title:translationService.translate("web-building-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-Description","Beskrivelse"),Property:"Description",PropertyType:"string"}]:$scope.columns=[{Position:1,Title:translationService.translate("web-person-employeeNr","AnsattNr"),Property:"EmployeeNr",PropertyType:"string"},{Position:1,Title:translationService.translate("web-person-firstname","Fornavn"),Property:"FirstName",PropertyType:"string"},{Position:1,Title:translationService.translate("web-person-lastname","Etternavn"),Property:"LastName",PropertyType:"string"},{Position:1,Title:translationService.translate("web-PersonRole-Id","Rolle"),Property:"PersonRole.Id",PropertyType:"string"}];var selected=[],filter={PropertyFilter:[]};$localStorage.generalOptions.UsePersonRole||(selected=$scope.isAddingBuilding?_.map(params.selectedEntityGuids,function(m){return m.GuidBuilding}):_.map(params.selectedEntityGuids,function(m){return m.GuidPerson})),$scope.isAddingBuilding&&filter.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:!1}),selected.length>0&&filter.PropertyFilter.push({Property:"Guid",Operator:"notin",Value:selected.join(",")}),params.isOperationsManager&&filter.PropertyFilter.push({Property:"IsOperationsManager",Operator:"=",Value:!0}),$scope.entities=new ngTableParams({page:1,count:10,sorting:$scope.isAddingBuilding?{id:"asc"}:{EmployeeNr:"asc"},filter:filter},{total:0,counts:[10,25,50],getData:function($defer,params){var url=$scope.isAddingBuilding?repository.apiData.building.url:repository.apiData.person.url,columns=_.map($scope.columns,"Property");repository.GetPaginated(url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.saveEdit=function(){var success=function(response){repository.growl(translationService.translate("web-buildingXPerson-Edit-Success","ByggXPerson er oppdatert"),"success"),$modalInstance.close("Ok")},error=function(error){repository.growl(error,"danger")};repository.updateSingle(repository.apiData.buildingPerson.url,$scope.model).then(success).catch(error)},$scope.save=function(fromRoleSelection){var models=[],duplicatePersons=[],openSelectRoleModal=!1;fromRoleSelection?selectedEntities.forEach(function(entity){var model=entity;$localStorage.generalOptions.UsePersonRole?_.findWhere(params.selectedEntityGuids,{GuidPerson:model.GuidPerson,GuidBuilding:model.GuidBuilding,GuidPersonRole:model.GuidPersonRole})?(duplicatePersons.push(model),openSelectRoleModal=!0):(params.selectedEntityGuids.push(model),models.push(model)):models.push(model)}):selectedEntities.forEach(function(entity){var model={};$scope.isAddingBuilding?(model.GuidBuilding=entity.guid,model.GuidPerson=params.GuidPerson,model.GuidPersonRole=params.GuidPersonRole):(model.GuidBuilding=params.GuidBuilding,model.GuidPerson=entity.guid,model.GuidPersonRole=entity.data.GuidPersonRole),$localStorage.generalOptions.UsePersonRole?_.findWhere(params.selectedEntityGuids,{GuidPerson:model.GuidPerson,GuidBuilding:model.GuidBuilding,GuidPersonRole:model.GuidPersonRole})?($scope.isAddingBuilding?(model.personRoleCaption=params.personRole,model.personCaption=params.personCaption,model.buildingCaption=entity.data.Id+" "+entity.data.Description):(model.personCaption=entity.data.FirstName+" "+entity.data.LastName,model.personRoleCaption=entity.data.PersonRole.Id,model.buildingCaption=params.buildingCaption),duplicatePersons.push(model),openSelectRoleModal=!0):(params.selectedEntityGuids.push(model),models.push(model)):models.push(model)}),models.length>0&&repository.createMultiple(repository.apiData.buildingPerson.url,models).then(function(result){openSelectRoleModal||($scope.isAddingBuilding?repository.growl("Bygg(ene) har blitt lagt til på personen","success"):repository.growl("Person(er) har blitt lagt til på bygget","success"),$modalInstance.close("Ok"))}).catch(function(error){repository.growl(error,"danger")}),openSelectRoleModal&&(fromRoleSelection&&repository.growl(translationService.translate("web-buildingxperson-role-already-exist error","Rollen eksisterer allerede på person, vennligst velg ny rolle"),"danger"),$modal.open({templateUrl:"app/building/views/selectPersonRoleModal.html",controller:"SelectPersonRoleModalContreoller",resolve:{params:function(){return{selectedPersons:duplicatePersons}}}}).result.then(function(changedEntities){selectedEntities=changedEntities,$scope.save(!0)},function(){selectedEntities=[]}))},$scope.addSelected=function(row){if(_.findWhere(selectedEntities,{guid:row.Guid}))for(var i=0;i",Value:$scope.model.Guid,CollectionOperator:"all"},{Property:"IsTemplate",Operator:"=",Value:!1}]}}}}}}).result.then(function(selectedGuids){var promises=selectedGuids.map(function(guid){return createBuildingXBuildingSelection({GuidBuildingSelection:$stateParams.guid,GuidBuilding:guid})});$q.all(promises).then(function(){repository.growl("Byggningene har blitt lagt til","success"),$scope.buildingXBuildingSelectionTable.reload()}).catch(function(error){$scope.buildingXBuildingSelectionTable.reload()})})},$scope.deleteBuilding=function(building){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-buildingSelection-xEntity-message","Byggning vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-buildingSelection-xEntity-button-confirm","Ja, fjern byggning"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.buildingBuildingSelection.url,building.Guid).then(function(result){swal(translationService.translate("web-swal-buildigSelection-deleteBuilding-success","Byggning ble fjernet!"),result,"success"),$scope.buildingXBuildingSelectionTable.reload()},function(error){repository.growl(error,"danger"),swal("Error!",error,"error")})})}}angular.module("Plania").controller("BuildingSelectionController",["$scope","Repository","$stateParams","TranslationService","ngTableParams","$modal","ListService","$q",controller])}(),function(){function controller($scope,repository,translationService,$rootScope,ngTableParams,$modal,listService){$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasEditAccess=$rootScope.hasEditAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.userInfo=$rootScope.userInfo,$scope.getPropertyValue=function(entity,column){return listService.GetPropertyValue(entity,column)};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.buildingInfo=new function(){var me=this;this.selectedGuids=[],this.columns=[{Position:1,Title:translationService.translate("web-estate-id"),Property:"Estate.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-estate-Description"),Property:"Estate.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-building-Id"),Property:"Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-building-Description"),Property:"Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-building-buildingCategory"),Property:"BuildingCategory.Description",PropertyType:"string"}],this.search={active:!1,focus:!1},this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{PropertyFilter:[{Property:"GuidTemplate",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.building.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List);var guids=result.List.map(function(building){return building.Guid});me.selectedGuids=me.selectedGuids.filter(function(guid){return guids.includes(guid)})},function(error){repository.showError(error)})}}))},this.addBuildings=function(){$scope.userInfo.isSystemAdministrator&&$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:translationService.translate("web-buildingTemplate-addBuilding-title","Legg til Byggning"),columns:[{Title:translationService.translate("web-estate-id"),Property:"Estate.Id"},{Title:translationService.translate("web-estate-Description"),Property:"Estate.Description"},{Title:translationService.translate("web-building-Id"),Property:"Id"},{Title:translationService.translate("web-building-Description"),Property:"Description"},{Title:translationService.translate("web-building-buildingCategory"),Property:"BuildingCategory.Description"},{Title:translationService.translate("web-building-dataOwner"),Property:"DataOwner.Id"}],url:repository.apiData.building.url,sorting:{Id:"asc"},filter:{FilterModel:{Condition:"and",Rules:[{Property:"GuidTemplate",Operator:"=",Value:null},{Property:"IsTemplate",Operator:"=",Value:!1}]}}}}}}).result.then(function(selectedGuids){if(selectedGuids){var changeList=[];selectedGuids.forEach(function(guid){changeList.push({Guid:guid,GuidTemplate:$scope.model.Guid})}),repository.patch(repository.apiData.building.url,null,changeList).then(function(response){_.every(response,function(response){return response.IsSuccess})?repository.growl(translationService.translate("web-buildingTemplate-addBuildings-success","Byggene har blitt lagt til byggmal."),"success"):repository.growl(translationService.translate("web-buildingTemplate-addBuildings-failed","En eller flere bygg ble ikke lagt til byggmal"),"danger"),me.table.reload()},function(error){me.table.reload(),repository.showError(error)})}})},this.selectItem=function(item){me.selectedGuids.includes(item.Guid)?me.selectedGuids=me.selectedGuids.filter(function(guid){return guid!==item.Guid}):me.selectedGuids.push(item.Guid)},this.isItemSelected=function(item){return me.selectedGuids.includes(item.Guid)},this.synchronize=function(guidBuildings){$scope.userInfo.isSystemAdministrator&&$modal.open({templateUrl:"app/buildingTemplate/views/synchronizeBuildingsForTemplateModal.html",controller:"SynchronizeBuildingsForTemplateModalController",size:"lg",resolve:{params:function(){return{guidTemplate:$scope.model.Guid,guidBuildings:guidBuildings,count:guidBuildings?guidBuildings.length:me.table.settings().total}}}}).result.then(function(){me.table.reload()},function(){me.table.reload()})},this.unlink=function(guidBuildings){$scope.userInfo.isSystemAdministrator&&swal({title:translationService.translate("web-buildingTemplate-buildings-unlink-swalTitle","Er du sikker?"),text:translationService.translate("web-buildingTemplate-buildings-unlink-swalMessage","Dette vil koble bort referansen for valgt bygg bort ifra gjeldende mal. Dette vil også frikoble anlegg, dokument og periodiske rutiner fra sine maler."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-buildingTemplate-buildings-unlink-confirm","Ja, koble fra mal"),cancelButtonText:translationService.translate("web-buildingTemplate-buildings-unlink-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.runAction(repository.apiData.building.url+"unlink/",guidBuildings?{GuidBuildings:guidBuildings}:null).then(function(response){swal.close(),me.table.reload()},function(error){repository.showError(error),swal.close(),me.table.reload()})})},this.contextMenuOptions=function(item){var options=[];return options.push(getMenuLink($rootScope.navigation.href("building.edit",{guid:item.Guid}),translationService.translate("web-buildingTemplate-buildings-contextMenu-goToBuilding","Gå til bygg"))),$scope.userInfo.isSystemAdministrator&&(me.selectedGuids.length?options.push({html:' '+translationService.translate("web-buildingTemplate-buildings-contextMenu-synchronizeSelectedBuildings","Synkroniser valgte bygg")+"",click:function(){me.synchronize(me.selectedGuids)}}):options.push({html:' '+translationService.translate("web-buildingTemplate-buildings-contextMenu-synchronizeBuilding","Synkroniser bygg")+"",click:function(){me.synchronize([item.Guid])}}),me.selectedGuids.length?options.push({html:' '+translationService.translate("web-buildingTemplate-buildings-contextMenu-unlinkSelectedBuildings","Koble valgte bygg bort fra mal")+"",click:function(){me.unlink(me.selectedGuids)}}):options.push({html:' '+translationService.translate("web-buildingTemplate-buildings-contextMenu-unlinkBuilding","Koble bygg fra mal")+"",click:function(){me.unlink([item.Guid])}})),options},me.initTable()}}angular.module("Plania").directive("buildingTemplateBuildingDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate"},controller:["$scope","Repository","TranslationService","$rootScope","ngTableParams","$modal","ListService",controller],templateUrl:"app/buildingTemplate/views/buildingTemplateBuilding.html"}})}(),function(){function controller($scope,repository,$stateParams,translationService,ngTableParams,$modal,listService,$state,$location){$scope.isUpdate="buildingTemplate.edit"===$scope.navigation.current.name,$scope.reloadDocumentTable=!1,$scope.model={Guid:$stateParams.guid,IsTemplate:!0};var availableHashLocations=["#info","#periodicTask","#equipment","#building"],updateLocation=function(){var hash=window.location.hash;hash&&availableHashLocations.includes(hash)?($('#buildingTemplateTabs a[data-target="'+hash+'"]').tab("show"),$scope.currentTab=hash.substr(1)):($('#buildingTemplateTabs a[data-target="#info"]').tab("show"),$scope.currentTab="info")};$scope.$on("$locationChangeSuccess",function(event,newUrl,oldUrl){updateLocation()}),$scope.setTab=function(tab){ $location.hash(tab).replace()},$scope.isUpdate&&$stateParams.tab?($scope.setTab($stateParams.tab),updateLocation()):updateLocation();var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Building,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Building,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Building),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Building)};updateAccess(),$scope.isUpdate?repository.getMainModel(repository.apiData.building.url,$stateParams.guid).then(function(response){if($scope.reload=!0,$scope.model=response.Data,!$scope.model.IsTemplate)return void $state.go("building.edit",{guid:$scope.model.Guid,model:$scope.model},{location:"replace"});updateAccess(),$scope.reloadDocumentTable=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}):$scope.activateAutocomplete=!0,$scope.updateBuildingTemplate=function(destination){var success=function(result){repository.growl($scope.isUpdate?"Byggmal har blitt oppdatert.":"Byggmal har blitt opprettet","success");var buildingTemplateGuid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,buildingTemplateGuid);var hash=window.location.hash;hash&&(hash=hash.substr(1)),$scope.goBack(destination,{guid:buildingTemplateGuid,menuGuid:$scope.navigation.params.menuGuid,tab:hash})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.building.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.building.url,$scope.model).then(success,error)},$scope.removeBuildingTemplate=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-buildingTemplate-message","Byggmal vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-buildingTemplate-button-confirm","Ja, fjern byggmal"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.building.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-buildingTemplate-success","Byggmal ble fjernet!"),result,"success"),repository.growl("Byggmal har blitt fjernet","success"),$scope.goBack("buildingTemplate.list",{menuGuid:$scope.navigation.params.menuGuid})},function(error){swal({title:"Kunne ikke slette byggmal!",text:error.Message+"

    Vil du deaktivere byggmal?",type:"error",html:!0,showCancelButton:!0,confirmButtonText:"Deaktiver",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.Id="#"+$scope.model.Id,$scope.model.IsDeactivated=!0,$scope.updateBuildingTemplate("buildingTemplate.list"))})})})},$scope.cancel=function(){$scope.goBack("buildingTemplate.list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("BuildingTemplateController",["$scope","Repository","$stateParams","TranslationService","ngTableParams","$modal","ListService","$state","$location",controller])}(),function(){function controller($scope,repository,translationService,$rootScope){$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.equipmentColumns=[{Position:1,Title:translationService.translate("web-equipment-id"),Property:"Equipment.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-equipment-description"),Property:"Equipment.Description",PropertyType:"string"}],$scope.applyEquipmentFilter=function(filter){return filter.TemplateContext="All",filter},$scope.createEquipment=function(){var persistedData={};persistedData.GuidBuilding=$scope.model.Guid,persistedData.Building=$scope.model,persistedData.IsTemplate=$scope.model.IsTemplate,repository.persistedData.setPersistedData("equipment.create",persistedData),$scope.navigation.go("equipment.create",{showPersistantData:!0},{reload:!0})}}angular.module("Plania").directive("buildingTemplateEquipmentDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate"},controller:["$scope","Repository","TranslationService","$rootScope",controller],templateUrl:"app/buildingTemplate/views/buildingTemplateEquipment.html"}})}(),function(){function controller($scope,ngTableParams,repository,translationService,$modal,$rootScope,listService,$timeout){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.viewMode=$scope.isUpdate,$scope.hasPageLoaded="info"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"info"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)});$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.onBuildingCategorySelect=function(category){if(!category)return void($scope.model.GuidBuildingCategory="");$scope.model.GuidBuildingCategory=category.Guid},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"buildingCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}}}angular.module("Plania").directive("buildingTemplateInfoDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate",reloadDocumentTable:"=reloadDocumentTable",activateAutocomplete:"=activateAutocomplete",currentTab:"=currentTab",formReference:"="},controller:["$scope","ngTableParams","Repository","TranslationService","$modal","$rootScope","ListService","$timeout",controller],templateUrl:"app/buildingTemplate/views/buildingTemplateInfo.html"}})}(),function(){function controller($scope,repository,translationService,$rootScope){$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.periodicTaskColumns=[{Position:1,Title:translationService.translate("web-periodicTask-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-equipment-id"),Property:"Equipment.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidEquipment",AutocompleteService:"equipment"},{Position:3,Title:translationService.translate("web-equipment-description"),Property:"Equipment.Description",PropertyType:"autocomplete",AutocompleteProperty:"GuidEquipment",AutocompleteService:"equipment"},{Position:4,Title:translationService.translate("web-periodicTask-description"),Property:"Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-periodictask-interval"),Property:"Interval",PropertyType:"string"},{Position:6,Title:translationService.translate("web-periodictask-period"),Property:"Period",PropertyType:"enum.timeunit"},{Position:7,Title:translationService.translate("web-periodictask-must-link-instances"),Property:"MustLinkInstances",PropertyType:"bool"},{Position:8,Title:translationService.translate("web-periodictask-is-fire-related"),Property:"IsFireRelated",PropertyType:"bool"},{Position:9,Title:translationService.translate("web-periodictask-is-electro-related"),Property:"IsElectroRelated",PropertyType:"bool"}],$scope.createPeriodicTask=function(){repository.persistedData.setPersistedData("periodicTask.create",{model:{IsTemplate:!0,GuidBuilding:$scope.model.Guid},guidBuilding:$scope.model.Guid,building:$scope.model.Caption}),$scope.navigation.go("periodicTask.create",{showPersistantData:!0},{reload:!0})}}angular.module("Plania").directive("buildingTemplatePeriodicTaskDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate"},controller:["$scope","Repository","TranslationService","$rootScope",controller],templateUrl:"app/buildingTemplate/views/buildingTemplatePeriodicTask.html"}})}(),function(){function controller($scope,params,repository,ngTableParams,$modalInstance,translationService,signalR,$timeout,$rootScope,$window){var guidTemplate=params.guidTemplate,guidBuildings=_.cloneDeep(params.guidBuildings);void 0===params.count?guidBuildings.length:params.count;$scope.currentTab="info",$scope.isRunningAction=!1,$scope.progress={};var startSignalRListener=function(){$scope.progress={};var progressMethodName="synchronizeBuildingsOnTemplateFor_"+guidTemplate;signalR.on(progressMethodName,function(progress){progress.Finished?$timeout(function(){$scope.progress=progress},1e3):$scope.progress=progress}),$scope.$on("$destroy",function(){signalR.off(progressMethodName)})};$scope.responses=[],$scope.resultTable=new ngTableParams({page:1,count:10},{total:$scope.responses.length,counts:[5,10,20],getData:function($defer,params){$scope.resultTable.settings().total=$scope.responses.length;var paginated=$scope.responses.slice((params.page()-1)*params.count(),params.page()*params.count());$defer.resolve(paginated)}}),$scope.startSync=function(){$scope.isRunningAction||($scope.isRunningAction=!0,startSignalRListener(),$scope.currentTab="result",repository.runAction(repository.apiData.building.url+"template/"+guidTemplate+"/synchronize/",guidBuildings?{GuidBuildings:guidBuildings}:null).then(function(response){$scope.responses=response.BuildingResponses,!1===response.IsSuccess&&repository.showError(response.ErrorMessage),$scope.resultTable.reload(),$scope.isRunningAction=!1},function(error){repository.showError(error),$scope.isRunningAction=!1}))},$scope.takeTopN=function(list,amount){return void 0===amount&&(amount=5),list.slice(0,amount)},$scope.contextMenuOptions=function(item){var options=[];return options.push({html:' '+translationService.translate("web-synchronizeBuildingsForTemplateModal-viewBuilding","Åpne bygg i ny tab/fane i nettleseren")+"",click:function(){$window.open($rootScope.navigation.href("building.edit",{guid:item.Guid}),"_blank")}}),options},$scope.cancel=function(){$scope.isRunningAction?swal({title:translationService.translate("web-synchronizeBuildingsForTemplateModal-swal-title","Vil du lukke dette vinduet?"),text:translationService.translate("web-synchronizeBuildingsForTemplateModal-swal-text","Plania vil fortsette å synkronisere bygg, men du vil ikke kunne se potensielle feilmeldinger hvis du lukker dette vinduet."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-button-yes-continue","Ja, fortsett"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$modalInstance.dismiss("canceled")}):$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("SynchronizeBuildingsForTemplateModalController",["$scope","params","Repository","ngTableParams","$modalInstance","TranslationService","SignalR","$timeout","$rootScope","$window",controller])}(),function(){function controller($scope,repository,$interval,translationService){$scope.refreshCache=function(cacheInfo){repository.deleteSingle(repository.apiData.cacheInfo.url,cacheInfo.Type).then(function(result){cacheInfo.LastUpdatedTime=null,cacheInfo.CachedItemsCount=null,repository.growl(translationService.translate("web-cacheInfo-refreshCache-success","Cache invalidert"),"success")},function(error){repository.growl(error,"danger")})};var init=function(){repository.GetPaginated(repository.apiData.cacheInfo.url).then(function(result){$scope.cachedItems=result},function(error){repository.growl(error,"danger")})};init();var reloadDataInterval=$interval(function(){init()},1e4);$scope.$on("$destroy",function(){angular.isDefined(reloadDataInterval)&&$interval.cancel(reloadDataInterval)})}angular.module("Plania").controller("CacheInfoController",["$scope","Repository","$interval","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,ngTableParams,$modal,listService){$scope.isUpdate="cause.edit"===$scope.navigation.current.name,$scope.model={},$scope.resourceColumns=["ResourceGroup.Id","ResourceGroup.Description","ResourceGroup.Guid"];var getCardTables=function(){$scope.resourceTable=new ngTableParams({page:1,count:10,sorting:{"ResourceGroup.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidCause",Operator:"=",value:$scope.model.Guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){$scope.loadingResources=!0,repository.GetPaginated(repository.apiData.resourceGroupCause.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify($scope.resourceColumns)).then(function(result){$scope.loadingResources=!1,$scope.resourceTable.settings().total=result.TotalCount,$scope.resourceTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){$scope.loadingResources=!1,repository.growl(error,"danger")})}})};$scope.addResource=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Velg ressurs",columns:[{Title:translationService.translate("web-cause-resource-id"),Property:"Id"},{Title:translationService.translate("web-cause-resource-description"),Property:"Description"}],useObjects:!1,url:repository.apiData.resourceGroup.url,sorting:{Id:"asc"},filter:{},alreadySavedGuids:function(){var selectedGuids=[];return $scope.resourceTable.data.forEach(function(entity){selectedGuids.push(entity.GuidResourceGroup)}),selectedGuids}()}}}}).result.then(function(selectedEntities){var resourceXCause=[];selectedEntities.forEach(function(entity){resourceXCause.push({GuidCause:$scope.model.Guid,GuidResourceGroup:entity})}),repository.createMultiple(repository.apiData.resourceGroupCause.url,resourceXCause).then(function(result){repository.growl("Ressurs(er) har blitt lagt til","success"),$scope.resourceTable.reload()})})},$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)},$scope.removeResource=function(resourceCause){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cause-resourceGroup-message","Ressurs vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cause-resourceGroup-button-confirm","Ja, fjern ressurs"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.resourceGroupCause.url,resourceCause.Guid).then(function(result){swal(translationService.translate("web-swal-cause-resourcegroup-success","Ressurs ble fjernet!"),result,"success"),$scope.resourceTable.reload()})})};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Cause,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Cause,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Cause),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Cause)};$scope.isUpdate&&repository.getSingle(repository.apiData.cause.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess(),getCardTables(),$scope.reload=!0},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-cause-success","Årsak har blitt oppdatert."):translationService.translate("create-cause-success","Årsak har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.cause.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.cause.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cause-message","Årsak vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cause-button-confirm","Ja, fjern årsak"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.cause.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-cause-success","Årsak ble fjernet!"),result,"success"),$scope.goBack("cause.list",{menuGuid:$scope.navigation.params.menuGuid})},function(error){var swalMessage=error.Message;error.IsDeactivateable&&(swalMessage+="

    Vil du deaktivere årsaken?"),swal({title:"Kunne ikke slette årsaken!",text:swalMessage,type:"error",html:!0,showCancelButton:!0,confirmButtonText:error.IsDeactivateable?"Deaktiver":"Ok",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.IsDeactivated=!0,$scope.model.Id=("#"+$scope.model.Id).substring(0,50),$scope.update("cause.list"))})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("CauseController",["$scope","Repository","$stateParams","TranslationService","ngTableParams","$modal","ListService",controller])}(),function(){function controller($scope,repository,translationService,$modal){function getChangeSets(){var columns=["EntityType","GuidEntity","CreationDate","Status","UserCreatedBy.RealName"],changeSetFilter={FilterModel:{Condition:"and",Rules:[{Property:"EntityType",Operator:"=",Value:$scope.entityType},{Property:"GuidEntity",Operator:"=",Value:$scope.guidEntity}]}};"all"!==$scope.currentSelectedFilterType.value&&changeSetFilter.FilterModel.Rules.push({Property:"Status",Operator:"=",Value:$scope.currentSelectedFilterType.enumValue}),repository.GetPaginated(repository.apiData.changeSet.url,0,1e4,{CreationDate:"desc"},changeSetFilter,null,JSON.stringify(columns)).then(function(result){$scope.totalCount=result.TotalCount,$scope.changeSets=result.List},function(error){repository.growl(error,"danger")})}if($scope.guidEntity&&$scope.entityType){var filterTypes=[{value:"all",name:translationService.translate("web-changeSet-filterType-all","Alle"),longName:translationService.translate("web-changeSet-filterType-showAll","Vis alle")},{value:"Pending",enumValue:0,name:translationService.translate("web-changeSet-filterType-pending","Klare"),longName:translationService.translate("web-changeSet-filterType-showPending","Vis endringer klare til behandling")},{value:"Approved",enumValue:1,name:translationService.translate("web-changeSet-filterType-approved","Godkjente"),longName:translationService.translate("web-changeSet-filterType-showApproved","Vis godkjente endringer")},{value:"Rejected",enumValue:2,name:translationService.translate("web-changeSet-filterType-rejected","Avslåtte"),longName:translationService.translate("web-changeSet-filterType-showRejected","Vis avslåtte endringer")}];$scope.currentSelectedFilterType=filterTypes[1],$scope.changeSets=[],getChangeSets(),$scope.setFilter=function(filterTypeValue){var selectedFilterType=_.find(filterTypes,{value:filterTypeValue});selectedFilterType&&filterTypeValue!==$scope.currentSelectedFilterType.value&&($scope.currentSelectedFilterType=selectedFilterType,getChangeSets())},$scope.getStatusColor=function(status){if("Pending"===status)return"default";switch(status){case"Approved":return"success";case"Rejected":return"danger"}},$scope.getStatusIcon=function(status){if("Pending"===status)return"zmdi-circle-o";switch(status){case"Approved":return"zmdi-check-circle";case"Rejected":return"zmdi-minus-circle"}},$scope.openChangeSet=function(set){$modal.open({templateUrl:"app/changeSet/views/changeSetModal.html",controller:"ChangeSetModalController",resolve:{params:function(){return{guid:set.Guid,entityType:set.EntityType}}}}).result.then(function(){getChangeSets()})}}}angular.module("Plania").directive("changeSet",function(){return{restrict:"E",scope:{reload:"=reload",entityType:"=entityType",guidEntity:"=guidEntity",disableActions:"=disableActions"},controller:["$scope","Repository","TranslationService","$modal",controller],link:function(scope,element,attrs){},templateUrl:"app/changeSet/views/changeSetDirective.html"}})}(),function(){function controller($scope,repository,params,modalInstance,translationService){var guid=params.guid,entityType=params.entityType,columns=["UserCreatedBy.RealName"];repository.getSingle(repository.apiData.changeSet.url,guid,JSON.stringify(columns)).then(function(result){$scope.model=result.Data,entityType=$scope.model.EntityType;var apiDataEntry=entityType.charAt(0).toLowerCase()+entityType.slice(1),guidEntity=$scope.model.GuidEntity;repository.getSingle(repository.apiData[apiDataEntry].url,guidEntity).then(function(result){$scope.planiaEntity=result.Data},function(error){repository.growl(error,"danger")})},function(error){repository.growl(error,"danger")}),$scope.getTranslatedPropertyName=function(planiaPropertyName){if(planiaPropertyName.startsWith("Text")||planiaPropertyName.startsWith("Number")||planiaPropertyName.startsWith("Combo")){return $scope.getTranslatedPropertyNameFromDynamicCategory(planiaPropertyName)}return translationService.translate("web-"+entityType+"-"+planiaPropertyName,planiaPropertyName)},$scope.getTranslatedPropertyNameFromDynamicCategory=function(planiaPropertyName){if($scope.planiaEntity&&$scope.planiaEntity.DynamicProperty){var translatedValue="";return $scope.planiaEntity.DynamicProperty.Groups.forEach(function(group){group.Items.forEach(function(item){if(item.Template)item.Template.Groups.forEach(function(templateGroup){templateGroup.Items.forEach(function(templateItem){if(templateItem.PropertyName===planiaPropertyName)return translatedValue=templateItem.LabelPropertyValue})});else if(item.PropertyName===planiaPropertyName)return translatedValue=item.LabelPropertyValue})}),translatedValue}},$scope.getPlaniaValue=function(planiaProperty){return $scope.planiaEntity[planiaProperty]},$scope.setProcessed=function(){$scope.model.Status="Approved",repository.updateSingleDictionary(repository.apiData.changeSet.url,$scope.model).then(function(result){modalInstance.close()},function(error){repository.growl(error,"danger")})},$scope.ok=function(){modalInstance.close()},$scope.cancel=function(){modalInstance.dismiss("cancel")}}angular.module("Plania").controller("ChangeSetModalController",["$scope","Repository","params","$modalInstance","TranslationService",controller])}(),function(){function controller($scope,repository,$state,$modal,config,translationService,$filter,listService){var user=repository.authService.getUserData();$scope.model.GuidPerson=user.guidPerson,$scope.person=user.realName,$scope.images=[],$scope.isCorrecting=!0,$scope.activateAutocomplete=!1,$scope.doesCleaningTasks=!1,$scope.isRunningAction=!1,$scope.hiddenDailyCleaningTasks=[],repository.getSingle(repository.apiData.person.url,$scope.model.GuidPerson).then(function(result){$scope.doesCleaningTasks=result.Data.DoesCleaningTasks});var getArea=function(guidArea){repository.getSingle(repository.apiData.area.url,guidArea).then(function(area){$scope.area=area.Data,$scope.showGoToDrawingButton=$scope.area.GuidDrawing&&"dwg.view"!==$state.current.name,$scope.area&&$scope.area.MustCorrectDrawing?($scope.model.MustCorrectDrawing=$scope.area.MustCorrectDrawing,$scope.model.MustCorrectDrawingComment=$scope.area.MustCorrectDrawingComment,$scope.isCorrecting=!0===$scope.model.MustCorrectDrawing):$scope.isCorrecting=!1,$scope.reload=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)}),getCleaningTasks(guidArea)};$scope.selectedTasks=[],$scope.selectedInfoTasks=[],$scope.selectedObjectInfoTasks=[],$scope.selectTask=function(task){if(_.contains($scope.selectedTasks,task.Guid))for(var i=0;i<$scope.selectedTasks.length;i++){var p=$scope.selectedTasks[i];if(p===task.Guid)return $scope.selectedTasks.splice(i,1),void $scope.selectedObjectInfoTasks.splice(i,1)}else $scope.selectedTasks.push(task.Guid),$scope.selectedObjectInfoTasks.push(task)},$scope.isSelected=function(guid){return _.contains($scope.selectedTasks,guid)},$scope.selectInfoTask=function(task){if(_.contains($scope.selectedInfoTasks,task.Guid))for(var i=0;i<$scope.selectedInfoTasks.length;i++){var p=$scope.selectedInfoTasks[i];if(p===task.Guid)return void $scope.selectedInfoTasks.splice(i,1)}else $scope.selectedInfoTasks.push(task.Guid)},$scope.isInfoSelected=function(task){return _.contains($scope.selectedInfoTasks,task.Guid)};var getCleaningTasks=function(guidArea){var columns=["EstimatedTime","CleaningTask.Id","CleaningTask.CleaningType","CleaningTask.EstimatedTime","CleaningTask.ExplanatoryText","DelayedDate","ExitCleaningRequestStatus","ExitCleaningConfirmedDate","ExitCleaningDecisionDate","NextCleaningDate"],filter={showTodaysTasks:!0,PropertyFilter:[{Property:"GuidArea",Operator:"=",Value:guidArea}]};repository.GetPaginated(repository.apiData.areaXCleaningTask.url,0,50,{},filter,null,JSON.stringify(columns)).then(function(result){$scope.cleaningTasks=result.List,$scope.exitCleaningTask=_.find($scope.cleaningTasks,function(task){return"ExitCleaning"===task.CleaningTask.CleaningType}),$scope.exitCleaningTask?($scope.cleaningTasks.sort(function(x,y){return"ExitCleaning"===x.CleaningTask.CleaningType?-1:"ExitCleaning"===y.CleaningTask.CleaningType?1:0}),"Confirmed"!==$scope.exitCleaningTask.ExitCleaningRequestStatus&&"Discharged"!==$scope.exitCleaningTask.ExitCleaningRequestStatus||($scope.selectedTasks=[],$scope.selectTask($scope.exitCleaningTask),$scope.hiddenDailyCleaningTasks=$scope.cleaningTasks.filter(function(task){if("StandardCleaning"===task.CleaningTask.CleaningType)return task}),$scope.cleaningTasks=$scope.cleaningTasks.filter(function(task){if("StandardCleaning"!==task.CleaningTask.CleaningType)return task}))):$scope.task&&_.find($scope.cleaningTasks,{Guid:$scope.task.Guid})?$scope.selectTask(_.find($scope.cleaningTasks,{Guid:$scope.task.Guid})):1===$scope.cleaningTasks.length&&$scope.selectTask($scope.cleaningTasks[0])}).catch(function(error){repository.growl(error,"danger")})};$scope.deleteImage=function(image,index){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-image-message","Bildet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-image-button-confirm","Ja, fjern bildet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.image.url,image.Guid).then(function(result){swal(translationService.translate("web-swal-image-success","Bildet ble fjernet!"),result,"success"),$scope.area.Images.splice(index,1)})})},$scope.init=function(guidArea,task){$scope.model={GuidArea:guidArea,GuidPerson:user.guidPerson},$scope.task=task,getArea(guidArea)},$scope.autocompleteFilter=function(filterName){switch(filterName){case"cleaningTask":return{PropertyFilter:[{Property:"IsAdditionalTask",Operator:"=",Value:"1"}]};case"person":return{PropertyFilter:[{Property:"DoesCleaningTasks",Operator:"=",Value:"1"}]}}return null},$scope.onPersonSelect=function(person){if(!person)return void($scope.model.GuidPerson="");$scope.model.GuidPerson=person.Guid},$scope.addNewImage=function(){$modal.open({templateUrl:"app/document/views/createImageModal.html",controller:"CreateDocumentXEntityController",size:"lg",resolve:{params:function(){return{guidArea:$scope.model.GuidArea}}}}).result.then(function(images){images&&images.forEach(function(image){$scope.area.Images.push(image)})},function(msg){})},$scope.delayCleaning=function(){for(var i=0;i<$scope.selectedTasks.length;i++){var selectedTask=_.find($scope.cleaningTasks,{Guid:$scope.selectedTasks[i]});if("StandardCleaning"!==selectedTask.CleaningTask.CleaningType&&"Undefined"!==selectedTask.CleaningTask.CleaningType)return void swal({title:translationService.translate("web-swal-cleaningCompletion-delay-nonStandard-title","Kan ikke utsette engangsoppgaver"),text:translationService.translate("web-swal-cleaningCompletion-delay-nonStandard-message","Fjern kryssene på valgte engangsoppgaver for å utsette daglig renhold"),type:"warning",confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-button-ok","Ok"),closeOnConfirm:!1,showLoaderOnConfirm:!0})}var changeList=[];$scope.selectedTasks.forEach(function(taskGuid){changeList.push({Guid:taskGuid,DelayedDate:(new Date).toISOString()})}),$scope.isRunningAction=!0,repository.patch(repository.apiData.areaXCleaningTask.url,null,changeList).then(function(response){var success=_.every(response,function(response){return response.IsSuccess});$scope.isRunningAction=!1,success?repository.growl(translationService.translate("web-cleaningTask-delayedTask","Rengjøring utsatt"),"success"):repository.growl(translationService.translate("web-cleaningTask-delayedTask-failed","En eller flere renhold ble ikke utsatt"),"danger"),$scope.ok("delayed")},function(error){$scope.isRunningAction=!1,repository.showError(error)})},$scope.save=function(){var completionList=[],completingExitCleaningTask=!1;$scope.selectedTasks.forEach(function(taskGuid){var task=_.find($scope.cleaningTasks,function(o){return o.Guid===taskGuid}),cleaningCompletion={GuidCleaningTask:task.GuidCleaningTask,GuidArea:task.GuidArea,GuidPerson:$scope.model.GuidPerson,ExplanatoryText:task.ExplanatoryText,ExtraTime:task.ExtraTime,MustCorrectDrawing:$scope.model.MustCorrectDrawing,MustCorrectDrawingComment:$scope.model.MustCorrectDrawingComment,EstimatedTime:Math.ceil(60*task.EstimatedTime),CompletionStatus:"Completed"};"ExitCleaning"===task.CleaningTask.CleaningType&&(completingExitCleaningTask=!0, cleaningCompletion.ExitCleaningDecisionDate=task.ExitCleaningDecisionDate,cleaningCompletion.ExitCleaningConfirmedDate=task.ExitCleaningConfirmedDate,cleaningCompletion.ExitCleaningRequestStatus=task.ExitCleaningRequestStatus),completionList.push(cleaningCompletion)}),completingExitCleaningTask&&$scope.hiddenDailyCleaningTasks.forEach(function(task){var cleaningCompletion={GuidCleaningTask:task.GuidCleaningTask,GuidArea:task.GuidArea,GuidPerson:$scope.model.GuidPerson,ExplanatoryText:task.ExplanatoryText,ExtraTime:task.ExtraTime,MustCorrectDrawing:$scope.model.MustCorrectDrawing,MustCorrectDrawingComment:$scope.model.MustCorrectDrawingComment,CompletionStatus:"CompletedByExitCleaning"};completionList.push(cleaningCompletion)}),$scope.isRunningAction=!0,repository.createMultiple(repository.apiData.cleaningCompletion.url,completionList).then(function(result){$scope.isRunningAction=!1,repository.growl("Rengjøringen har blitt lagret","success"),$scope.ok()},function(error){$scope.isRunningAction=!1,repository.growl(error,"danger")})},$scope.disableCompletion=function(){return _.find($scope.selectedTasks,function(guid){var selectedTask=_.find($scope.cleaningTasks,function(task){return guid===task.Guid});return selectedTask&&!selectedTask.Recurrence&&!selectedTask.ExtraTime&&"ExitCleaning"!==selectedTask.CleaningTask.CleaningType})},$scope.disableCleaningCompletionForm=function(form){return $scope.selectedTasks.length<1||(!!$scope.disableCompletion()||(!(!$scope.model.MustCorrectDrawing||!$scope.isCorrecting||$scope.model.MustCorrectDrawingComment)||!(!form||form.$valid)))},$scope.goToDrawing=function(){$scope.doesCleaningTasks?$scope.navigation.go("dwg.view",{guid:$scope.area.GuidDrawing,selectedTheme:"cleaning",guidArea:$scope.model.GuidArea}):$scope.navigation.go("dwg.view",{guid:$scope.area.GuidDrawing,theme:"cleaningMaintenance",guidArea:$scope.model.GuidArea})},$scope.getNextCleaningDateString=function(task){return listService.getNextCleaningDateString(task,!0)},$scope.filterCleaningInfo=function(task){var show=!1;return task.AttributeValues.length>0&&(show=!0),task.ResourceGroup&&(show=!0),task.CleaningTask&&task.CleaningTask.ExplanatoryText&&(show=!0),show},$scope.$watch("parentReload",function(newVal,oldVal){newVal!==oldVal&&$scope.model.GuidArea&&getCleaningTasks($scope.model.GuidArea)})}angular.module("Plania").controller("CleaningCompletionController",["$scope","Repository","$state","$modal","config","TranslationService","$filter","ListService",controller])}(),function(){function controller($scope,repository,translationService,ngTableParams,listService,documentService,$modal){$scope.documents=[],$scope.showCleaningHistory=!1,$scope.init=function(guidArea,task){$scope.guidArea=guidArea,$scope.task=task,getData(guidArea)},repository.getSingle(repository.apiData.person.url,$scope.userInfo.guidPerson).then(function(result){$scope.person=result.Data}),$scope.cleaningCompletionColumns=[{Position:1,Title:translationService.translate("web-cleaningTask-id"),Property:"CleaningTask.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cleaningCompletion-explanatoryText","Kommentar"),Property:"ExplanatoryText",PropertyType:"string"},{Position:3,Title:translationService.translate("web-cleaningCompletion-CompletionDate","Utført dato"),Property:"CompletionDate",PropertyType:"date"}],$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.getTranslatedValueType=function(type){return translationService.translate("web-enum-FieldType-"+type)},$scope.showDocuments=repository.authService.hasReadAccess(repository.commonService.prefix.Document),$scope.showVideos=repository.authService.hasReadAccess(repository.apiData.videoXEntity.prefix);var getData=function(guidArea){var columns=["Area.Guid","CleaningTask.CleaningType","CleaningTask.ExplanatoryText","CleaningTask.Id","Area.CleaningComment","ResourceGroup.Id","NextCleaningDate"];repository.GetPaginated(repository.apiData.areaXCleaningTask.url,0,50,{},{PropertyFilter:[{Property:"GuidArea",Operator:"=",Value:guidArea}]},null,JSON.stringify(columns)).then(function(result){$scope.cleaningTasks=result.List,$scope.cleaningTasks[0]&&$scope.cleaningTasks[0].Area&&($scope.area=$scope.cleaningTasks[0].Area),$scope.task&&($scope.selectedTask=_.find($scope.cleaningTasks,function(o){return o.Guid===$scope.task.Guid})),$scope.showDocuments&&getDocuments(),$scope.showVideos&&getVideos()}).catch(function(error){repository.growl(error,"danger")})},getDocuments=function(){var documentColumns=["Document.Id","Document.Description","Document.FilePath"];$scope.documents=[],$scope.cleaningTasks.forEach(function(cleaningTask){repository.GetPaginated(repository.apiData.documentXEntity.url,0,100,{"Document.Description":"asc"},{GuidCleaningTask:cleaningTask.GuidCleaningTask},null,JSON.stringify(documentColumns)).then(function(result){result.List.forEach(function(document){_.some($scope.documents,{Guid:document.Guid})||$scope.documents.push(document)})},function(error){repository.growl(error,"danger")})})},getVideos=function(){var videoColumns=["Video.Id","Video.Description","Video.GuidVideoBinary","Video.FileName"];$scope.videos=[],$scope.cleaningTasks.forEach(function(cleaningTask){repository.GetPaginated(repository.apiData.videoXEntity.url,0,100,{"Video.Description":"asc"},{PropertyFilter:[{Property:"GuidCleaningTask",Operator:"=",Value:cleaningTask.GuidCleaningTask}]},null,JSON.stringify(videoColumns)).then(function(result){result.List.forEach(function(video){_.some($scope.videos,{Guid:video.Guid})||$scope.videos.push(video)})},function(error){repository.growl(error,"danger")})})};$scope.setShowCleaningHistory=function(show){show&&!$scope.cleaningCompletionTable&&($scope.cleaningCompletionTable=initCleaningCompletionTable($scope.guidArea)),$scope.showCleaningHistory=show};var initCleaningCompletionTable=function(guidArea){return new ngTableParams({page:1,count:10,sorting:{CompletionDate:"desc"},filter:{PropertyFilter:[{Property:"GuidArea",Operator:"=",Value:guidArea}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var completionColumns=[];$scope.cleaningCompletionColumns.forEach(function(column){completionColumns.push(column.Property)}),repository.GetPaginated(repository.apiData.cleaningCompletion.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(completionColumns)).then(function(result){$defer.resolve(result.List)})}})};$scope.openDocument=function(document){documentService.openDocument(document.Document).then(function(result){$scope.isCollapsed=!1})},$scope.playVideo=function(video){$modal.open({size:"lg",controller:"VideoPlayerModalController",templateUrl:"app/video/views/videoPlayerModal.html",resolve:{params:function(){return{video:video.Video,guidVideoBinary:video.Video.GuidVideoBinary}}}})},$scope.undoCleaning=function(task){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cleaning-undo-message","Den registrete renholdsgjennomføringen vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaning-undo-button-confirm","Ja, tilbakestill renholdet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.cleaningCompletion.url,task.Guid).then(function(result){swal(translationService.translate("web-swal-cleaning-undo-success","Renholdet ble tilbakestilt!"),result,"success"),$scope.cleaningCompletionTable.reload(),$scope.toggleParentReload&&$scope.toggleParentReload()})})},$scope.isToday=function(date){var momentDate=moment(date);return moment().startOf("day").isSame(momentDate.startOf("day"))},$scope.selectTask=function(task){$scope.selectedTask=task},$scope.updateAreaCleaningComment=function(){repository.patch(repository.apiData.area.url,$scope.area.Guid,{CleaningComment:$scope.area.CleaningComment}).then(function(result){getData($scope.area.Guid)},function(error){repository.showError(error)})},$scope.getNextCleaningDateString=function(task){return listService.getNextCleaningDateString(task,!0)}}angular.module("Plania").controller("CleaningInfoController",["$scope","Repository","TranslationService","NgTableParams","ListService","DocumentService","$modal",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,translationService,ngTableParams,listService){$scope.model={Guid:$stateParams.guid},$scope.isPaused=function(task){var today=moment().startOf("day");return task.PausedFromDate&&task.PausedToDate&&today.isBetween(task.PausedFromDate,task.PausedToDate,"days","[]")},$scope.getPropertyValue=function(item,column){return item.Prefix===repository.commonService.prefix.AreaXCleaningTask&&"IsPaused"===column.Property?$scope.isPaused(item)?translationService.translate("web-areaxcleaningtask-pausedStatusColumn-paused","Pauset"):translationService.translate("web-areaxcleaningtask-pausedStatusColumn-active","Aktiv"):listService.GetPropertyValue(item,column)};var columns=["ResourceGroup.Id","CleaningQuality.Id","CleaningQuality.Description","Person.FirstName","Person.LastName"];repository.getMainModel(repository.apiData.area.url,$scope.model.Guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data},function(error){repository.showError(error)}),$scope.cleaningTaskInfo=new function(){var me=this;this.isLoading=!1,this.columns=[{Position:2,Title:translationService.translate("web-areaxcleaningtask-cleaningTask-id","Renholdsoppgave"),Property:"CleaningTask.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-areaxcleaningtask-ResourceGroup-id","Renholdsteam"),Property:"ResourceGroup.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-areaxcleaningtask-AverageCleaningPerYear","Minutter neste år"),Property:"AverageCleaningPerYear",PropertyType:"number"},{Position:5,Title:translationService.translate("web-areaxcleaningtask-Recurrence","Gjentakelsesregel"),Property:"Recurrence",PropertyType:"recurrence"},{Position:6,Title:translationService.translate("web-areaxcleaningtask-NextCleaningDate","Utføres"),Property:"NextCleaningDate",PropertyType:"date"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{"CleaningTask.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidArea",Operator:"=",Value:$scope.model.Guid}],CleaningStatus:"Undefined"}},{total:0,counts:[10,20,50],filterDelay:10,paginationMaxBlocks:6,getData:function($defer,params){me.isLoading=!0;var columns=[];me.columns.forEach(function(col){"IsPaused"!==col.Property&&columns.push(col.Property)}),columns.push("PausedFromDate"),columns.push("PausedToDate"),repository.GetPaginated(repository.apiData.areaXCleaningTask.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.isLoading=!1,me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500;var hasPausedTask=!1;result.List.forEach(function(task){$scope.isPaused(task)&&(hasPausedTask=!0)}),hasPausedTask?"IsPaused"!==me.columns[0].Property&&me.columns.unshift({Position:1,SortingDisabled:!0,Title:translationService.translate("web-areaxcleaningtask-pausedStatusColumn","Status"),Property:"IsPaused"}):"IsPaused"===me.columns[0].Property&&me.columns.shift(),$defer.resolve(result.List)},function(error){me.isLoading=!1,repository.showError(error)})}}))},this.add=function(){$modal.open({templateUrl:"app/cleaningTask/views/cleaningTaskWizardModal.html",controller:"CleaningTaskWizardModalController",resolve:{modalParams:function(){return{columns:[{Title:translationService.translate("web-cleaningTask-id"),Property:"Id"},{Title:translationService.translate("web-CleaningTask-estimatedtime"),Property:"EstimatedTime"}],url:repository.apiData.cleaningTask.url,sorting:{Id:"asc"},filter:{},area:$scope.model}}}}).result.then(function(result){var cleaningTask=result.cleaningTask,recurrenceRule=result.recurrenceRule,attributeValues=result.attributeValues,areaXCleaningTasks=[{GuidCleaningTask:cleaningTask.Guid,RecurrenceRule:recurrenceRule,GuidArea:$scope.model.Guid,AttributeValues:attributeValues}];repository.createMultiple(repository.apiData.areaXCleaningTask.url,areaXCleaningTasks).then(function(result){me.table.reload()},function(error){repository.showError(error)})})},this.update=function(item){me.canEdit(item)&&$modal.open({templateUrl:"app/area/views/EditAreaXCleaningTaskModal.html",controller:"AreaXCleaningTaskController",resolve:{modalParams:function(){return{Guid:item.Guid}}}}).result.then(function(result){repository.growl(result,"info"),me.table.reload()})},this.remove=function(item){me.canDelete(item)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-area-cleaningtask-message","Renholdsoppgaven vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-area-cleaningtask-button-confirm","Ja, fjern renholdsoppgaven"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.areaXCleaningTask.url,"","guids="+JSON.stringify([item.Guid])).then(function(result){swal(translationService.translate("web-swal-area-cleaningTask-success","Renholdsoppgaven ble fjernet!"),result,"success"),repository.growl("Renholdsoppgaven har blitt fjernet","success"),me.table.reload()})})},this.pause=function(item){$modal.open({templateUrl:"app/area/views/editAreaXCleaningTaskStartDateModal.html",controller:"AreaXCleaningTaskController",size:"md",resolve:{modalParams:function(){return{Guid:item.Guid,SuggestedPause:{From:new Date,To:(new Date).setDate((new Date).getDate()+1)}}}}}).result.then(function(result){repository.growl(result,"info"),me.table.reload()})},this.contextMenuOptions=function(item){var options=[];if(item.CleaningTask&&"ExitCleaning"!==item.CleaningTask.CleaningType&&"InfectionCleaning"!==item.CleaningTask.CleaningType){var text=$scope.isPaused(item)?translationService.translate("web-areaXCleaningTask-cleaningTaskMenuOptions-setCleaningPauseDate-isPaused","Start renhold"):translationService.translate("web-areaXCleaningTask-cleaningTaskMenuOptions-setCleaningPauseDate-isNotPaused","Sett renhold på pause");options.push({html:' '+text+"",click:function(){me.pause(item)}})}return me.canEdit(item)&&options.push({html:' '+translationService.translate("web-areaXCleaningTask-cleaningTaskMenuOptions-edit","Rediger")+"",click:function(){me.update(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-areaXCleaningTask-cleaningTaskMenuOptions-delete","Slett")+"",click:function(){me.remove(item)}}),options},this.canEdit=function(item){return item&&$scope.hasEditAccess("AreaXCleaningTask")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("AreaXCleaningTask")},me.initTable()}}angular.module("Plania").controller("CleaningMaintenanceController",["$scope","Repository","$stateParams","$modal","TranslationService","NgTableParams","ListService",controller])}(),function(){function controller($scope,repository,params,modalInstance,translationService){$scope.model=params.model,$scope.ok=function(selectedDeviation){modalInstance.close(selectedDeviation)},$scope.cancel=function(){modalInstance.dismiss("cancel")},$scope.select=function(tabName){switch($scope.cleaningInfoIsActive=!1,$scope.cleaningCompletionIsActive=!1,tabName){case"cleaningInfo":$scope.cleaningInfoIsActive=!0;break;case"cleaningCompletion":$scope.cleaningCompletionIsActive=!0}},$scope.select(params.isCompletion?"cleaningCompletion":"cleaningInfo")}angular.module("Plania").controller("CleaningModalController",["$scope","Repository","params","$modalInstance","TranslationService",controller])}(),function(){function controller($scope,repository,translationService,$timeout){$scope.request={},$scope.autoCompleteModel={};var cleaningColumns=["Id","EstimatedTime","EstimatedCost","ExplanatoryText","NumericFieldName","CleaningType","ExitCleaningDecisionDate","ExitCleaningConfirmedDate"],filter={PropertyFilter:[{Property:"IsTemplate",Operator:"=",Value:"1"}]};$scope.extraData&&$scope.extraData.exitGuidAreaXCleaningTask&&filter.PropertyFilter.push({Property:"CleaningType",Operator:"<>",Value:"ExitCleaning"}),repository.GetPaginated(repository.apiData.cleaningTask.url,0,50,{Id:"asc"},filter,null,JSON.stringify(cleaningColumns)).then(function(result){$scope.tasks=result.List,$scope.tasks.forEach(function(task){"ExitCleaning"===task.CleaningType&&(task.ExitCleaningRequestStatus="Possible",task.ExitCleaningDecisionDate?task.ExitCleaningDecisionDate=getCurrentIsoDate(task.ExitCleaningDecisionDate):task.ExitCleaningDecisionDate=getCurrentIsoDate("default"),task.ExitCleaningConfirmedDate?task.ExitCleaningConfirmedDate=getCurrentIsoDate(task.ExitCleaningConfirmedDate):task.ExitCleaningConfirmedDate=getCurrentIsoDate("default")),task.AttributeValues.forEach(function(attribute){attribute.TextValue=attribute.NamedSelectionDefaultOption})})}),$scope.selectTask=function(task){$scope.selectedTask=task},$scope.isTimeInPast=function(fieldName){if(!$scope.selectedTask)return!1;var time=$scope.selectedTask[fieldName];return!!time&&(new Date).getTime()>new Date(time).getTime()};var getCurrentIsoDate=function(input){if(!input)return null;var date=new Date,selectedDate=new Date(input);return"default"===input?date.setHours(12,0,0):date.setHours(selectedDate.getHours(),selectedDate.getMinutes()),date.toISOString()};$scope.send=function(){$scope.areaCleaningTask={GuidArea:$scope.model.Guid,GuidCleaningTask:$scope.selectedTask.Guid,AttributeValues:$scope.selectedTask.AttributeValues},"ExitCleaning"===$scope.selectedTask.CleaningType&&("Possible"===$scope.selectedTask.ExitCleaningRequestStatus?($scope.areaCleaningTask.ExitCleaningConfirmedDate=null,$scope.areaCleaningTask.ExitCleaningDecisionDate=getCurrentIsoDate($scope.selectedTask.ExitCleaningDecisionDate)):"Discharged"===$scope.selectedTask.ExitCleaningRequestStatus?($scope.areaCleaningTask.ExitCleaningDecisionDate=null,$scope.areaCleaningTask.ExitCleaningConfirmedDate=(new Date).toISOString()):($scope.areaCleaningTask.ExitCleaningDecisionDate=null,$scope.areaCleaningTask.ExitCleaningConfirmedDate=getCurrentIsoDate($scope.selectedTask.ExitCleaningConfirmedDate)),$scope.areaCleaningTask.ExitCleaningRequestStatus=$scope.selectedTask.ExitCleaningRequestStatus),$scope.areaCleaningTask.AttributeValues.forEach(function(attribute){"Date"===attribute.ValueType&&attribute.DateValue&&(attribute.DateValue=attribute.DateValue.toISOString())}),repository.createSingle(repository.apiData.areaXCleaningTask.url,$scope.areaCleaningTask).then(function(result){repository.growl("Innmeldingen ble registrert","success"),$scope.selectedTask={},$scope.areaCleaningTask={},$scope.ok(result)},function(error){repository.growl(error,"danger")})}}angular.module("Plania").controller("CleaningRequestController",["$scope","Repository","TranslationService","$timeout",controller])}(),function(){function controller($scope,repository,params,modalInstance,translationService,listService,$q){function validateSelectedTasks(){if(!$scope.selectedTasks||0===$scope.selectedTasks.length)return!1;var firstCleaningTaskGuid=_.head($scope.selectedTasks),firstCleaningTask=_.find($scope.cleaningTasks,function(task){return task.Guid===firstCleaningTaskGuid});return!!_.every($scope.selectedTasks,function(guid){return _.find($scope.cleaningTasks,function(t){return t.Guid===guid}).GuidCleaningTask===firstCleaningTask.GuidCleaningTask})||($scope.errorMessage=translationService.translate("web-cleaningTask-multiEdit-errorMessage","Kan ikke endre ulike oppgaver"),!1)}function getAreaXCleaningTasks(){var deferred=$q.defer();return repository.GetPaginated(repository.apiData.areaXCleaningTask.url,0,-1,{},filter,null,JSON.stringify(columns)).then(function(result){$scope.cleaningTasks=result.List,$scope.cleaningTasksGrouped=[],$scope.cleaningTasks.forEach(function(task){var cleaningTaskGroup=_.find($scope.cleaningTasksGrouped,function(grouped){return grouped.header===task.CleaningTask.Id});cleaningTaskGroup?cleaningTaskGroup.items.push(task):$scope.cleaningTasksGrouped.push({header:task.CleaningTask.Id,items:[task]})}),$scope.cleaningTasksGrouped.sort(function(a,b){return(""+a.header).localeCompare(b.header)}),checkSelectedTasks(),setTimeout(function(){$scope.activateAutocomplete=!0},250),deferred.resolve()}).catch(function(error){repository.growl(error,"danger"),deferred.reject(error)}),deferred.promise}function checkSelectedTasks(skipGroup){$scope.selectedTasks.length===$scope.cleaningTasks?$scope.isAllTasksSelected=!0:$scope.isAllTasksSelected=!1,skipGroup||$scope.cleaningTasksGrouped.forEach(function(task){var guids=task.items.map(function(item){return item.Guid}),selected=$scope.selectedTasks.filter(function(guidTask){return guids.indexOf(guidTask)>=0});task.allTasksSelected=selected.length===guids.length})}function handleEditTaskTabChanged(){if($scope.changeModel={},$scope.tasksToChange=[],$scope.selectedTasks&&0!==$scope.selectedTasks.length){var selectedTaskGuid=$scope.selectedTasks[0],cleaningTask=_.find($scope.cleaningTasks,function(task){return task.Guid===selectedTaskGuid});$scope.changeModel=angular.copy(cleaningTask),"ExitCleaning"===$scope.changeModel.CleaningType&&($scope.changeModel.ExitCleaningDecisionDate?$scope.changeModel.ExitCleaningDecisionDate=getCurrentIsoDate(task.ExitCleaningDecisionDate):$scope.changeModel.ExitCleaningDecisionDate=getCurrentIsoDate("default"),$scope.changeModel.ExitCleaningConfirmedDate?$scope.changeModel.ExitCleaningConfirmedDate=getCurrentIsoDate(task.ExitCleaningConfirmedDate):$scope.changeModel.ExitCleaningConfirmedDate=getCurrentIsoDate("default")),$scope.exitCleaningRequestStatuses=["1","2"],_.forEach($scope.selectedTasks,function(guid){var task=_.find($scope.cleaningTasks,function(t){return t.Guid===guid});$scope.tasksToChange.push(task)})}}var user=repository.authService.getUserData();$scope.person={Caption:user.realName,Guid:user.guidPerson},$scope.activateAutocomplete=!1,$scope.cleaningTasks=[],$scope.cleaningTasksGrouped=[],$scope.cleaningTaskGroupBy="cleaningType",$scope.isAllTasksSelected=!1,$scope.selectedTasks=[],$scope.showMultiSelectView=!1,$scope.multiSelectedAreaXCleaningTasks=[],$scope.templateCleaningTask={},$scope.cancelExitCleaning=!1;var wasUpdated=!1,columns=["AverageCleaningPerYear","CleaningTask.Id","CleaningTask.CleaningType","CleaningTask.AverageCleaningPerYear","CleaningTask.ExplanatoryText","Area.Id","Area.Description","DelayedDate","ExitCleaningRequestStatus","ExitCleaningConfirmedDate","ExitCleaningDecisionDate","NextCleaningDate"],filter={showTodaysTasks:!0,PropertyFilter:[{Property:"GuidArea",Operator:"in",Value:params.guids.join(",")}]};$scope.tabs=[{heading:translationService.translate("web-dwg-editMultipleRequests-chooseCleaningTask","Velg renhold"),step:0},{heading:translationService.translate("web-dwg-editMultipleRequests-confirmRooms","Rediger valgte renhold"),step:1}],$scope.step=0,$scope.isCurrentStep=function(step){return $scope.step===step},$scope.setCurrentStep=function(step){0===$scope.step&&0===$scope.selectedTasks.length||($(".tab-content").css("overflow","hidden"),setTimeout(function(){$(".tab-content").css("overflow","visible")},500),$scope.step=step)},$scope.isLastStep=function(){return $scope.step===$scope.tabs.length-1},$scope.getNextLabel=function(){return $scope.isLastStep()?translationService.translate("web-button-confirm","Bekreft"):translationService.translate("web-button-next","Neste")},$scope.handlePrevious=function(){$scope.setCurrentStep($scope.step-(0===$scope.step?0:1))},$scope.handleNext=function(closeOnSave){if($scope.isLastStep())return void($scope.cancelExitCleaning?$scope.saveCancelledExitCleanings(closeOnSave):$scope.save(closeOnSave));0===$scope.step&&0===$scope.selectedTasks.length||($scope.setCurrentStep($scope.step+=1),1===$scope.step&&handleEditTaskTabChanged())},$scope.isCurrentStepValid=function(){return $scope.errorMessage=null,0===$scope.step?validateSelectedTasks():($scope.step,!0)},getAreaXCleaningTasks(),$scope.selectTask=function(task){if(_.contains($scope.selectedTasks,task.Guid))for(var i=0;i<$scope.selectedTasks.length;i++){var p=$scope.selectedTasks[i];if(p===task.Guid)return $scope.selectedTasks.splice(i,1),void checkSelectedTasks()}else $scope.selectedTasks.push(task.Guid),checkSelectedTasks()},$scope.isSelected=function(guid){return _.contains($scope.selectedTasks,guid)},$scope.selectMultipleTasks=function(){$scope.selectedTasks=[],$scope.isAllTasksSelected||$scope.cleaningTasks.forEach(function(task){$scope.selectedTasks.push(task.Guid)}),$scope.isAllTasksSelected=!$scope.isAllTasksSelected,$scope.cleaningTasksGrouped.forEach(function(group){group.allTasksSelected=$scope.isAllTasksSelected})},$scope.selectMultipleGroupedTasks=function(group){if(group&&"none"!==$scope.cleaningTaskGroupBy){var list=$scope.cleaningTasksGrouped,guids=_.find(list,function(l){return l.header===group.header}).items.map(function(item){return item.Guid});group.allTasksSelected?$scope.selectedTasks=$scope.selectedTasks.filter(function(guidTask){return guids.indexOf(guidTask)<0}):guids.forEach(function(guid){$scope.selectedTasks.indexOf(guid)<0&&$scope.selectedTasks.push(guid)}),group.allTasksSelected=!group.allTasksSelected,checkSelectedTasks(!0)}},$scope.getNextCleaningDateString=function(task){return listService.getNextCleaningDateString(task,!0)},$scope.changeModel={},$scope.getCurrentIsoDate=function(input){if(!input)return null;var date=new Date,selectedDate=new Date(input);return"default"===input?date.setHours(12,0,0):date.setHours(selectedDate.getHours(),selectedDate.getMinutes()),date.toISOString()},$scope.hasWarnings=function(areaXCleaningTask){return"Possible"===areaXCleaningTask.ExitCleaningRequestStatus?$scope.isTimeInPast(areaXCleaningTask.ExitCleaningDecisionDate):"Confirmed"===areaXCleaningTask.ExitCleaningRequestStatus&&$scope.isTimeInPast(areaXCleaningTask.ExitCleaningConfirmedDate)},$scope.isTimeInPast=function(dateProperty){if(!dateProperty)return!1;var time=dateProperty;return(new Date).getTime()>new Date(time).getTime()},$scope.toggleCancelExitCleaning=function(){$scope.cancelExitCleaning=!$scope.cancelExitCleaning},$scope.saveCancelledExitCleanings=function(closeOnSave){var changeList=[];_.forEach($scope.tasksToChange,function(task){var cleaningCompletion={GuidCleaningTask:task.GuidCleaningTask,GuidArea:task.GuidArea,GuidPerson:user.guidPerson,GuidResourceGroup:user.guidPersonResourceGroup,ExitCleaningDecisionDate:task.ExitCleaningDecisionDate,ExitCleaningConfirmedDate:task.ExitCleaningConfirmedDate,ExitCleaningRequestStatus:task.ExitCleaningRequestStatus,ExitCleaningCompletionStatus:"Cancelled"};changeList.push(cleaningCompletion)}),repository.createMultiple(repository.apiData.cleaningCompletion.url,changeList).then(function(result){wasUpdated=!0,repository.growl(translationService.translate("web-cleaningTask-editMultipleRequests-success","Renholdsoppgaver er oppdatert"),"success"),closeOnSave&&modalInstance.close(),getAreaXCleaningTasks().then(function(){$scope.selectedTasks=[],$scope.setCurrentStep(0)})},function(error){repository.growl(error,"danger")})},$scope.save=function(closeOnSave){var changeList=[];_.forEach($scope.tasksToChange,function(task){"ExitCleaning"===$scope.changeModel.CleaningTask.CleaningType&&(task.ExitCleaningRequestStatus=$scope.changeModel.ExitCleaningRequestStatus,"Possible"===task.ExitCleaningRequestStatus?(task.ExitCleaningConfirmedDate=null,task.ExitCleaningDecisionDate=$scope.getCurrentIsoDate($scope.changeModel.ExitCleaningDecisionDate)):"Discharged"===task.ExitCleaningRequestStatus?(task.ExitCleaningDecisionDate=null,task.ExitCleaningConfirmedDate=(new Date).toISOString()):(task.ExitCleaningDecisionDate=null,task.ExitCleaningConfirmedDate=$scope.getCurrentIsoDate($scope.changeModel.ExitCleaningConfirmedDate))),$scope.changeModel.AttributeValues&&$scope.changeModel.AttributeValues.length>0&&$scope.changeModel.AttributeValues.forEach(function(attribute){"Date"===attribute.ValueType&&attribute.DateValue&&(attribute.DateValue=attribute.DateValue.toISOString());var attributeToCopyTo=_.find(task.AttributeValues,function(av){return av.GuidEntityXAttribute===attribute.GuidEntityXAttribute});attributeToCopyTo&&(attributeToCopyTo.TextValue=attribute.TextValue,attributeToCopyTo.BitValue=attribute.BitValue,attributeToCopyTo.NumericValue=attribute.NumericValue,attributeToCopyTo.DateValue=attribute.DateValue)}),changeList.push(task)}),repository.updateMultiple(repository.apiData.areaXCleaningTask.url,changeList).then(function(result){if(wasUpdated=!0,repository.growl(translationService.translate("web-cleaningTask-editMultipleRequests-success","Renholdsoppgaver er oppdatert"),"success"),closeOnSave)return void modalInstance.close();getAreaXCleaningTasks().then(function(){$scope.setCurrentStep(0)})},function(error){repository.growl(error,"error")})},$scope.ok=function(result){modalInstance.close(result)},$scope.close=function(){wasUpdated?modalInstance.close():modalInstance.dismiss("cancel")}}angular.module("Plania").controller("EditMultipleDwgRequestController",["$scope","Repository","params","$modalInstance","TranslationService","ListService","$q",controller])}(),function(){function controller($scope,repository,translationService,params,modalInstance){var user=repository.authService.getUserData(),getCurrentIsoDate=function(input){if(!input)return null;var date=new Date,selectedDate=new Date(input);return"default"===input?date.setHours(12,0,0):date.setHours(selectedDate.getHours(),selectedDate.getMinutes()),date.toISOString()};repository.getSingle(repository.apiData.areaXCleaningTask.url,params.guidAreaXCleaningTask).then(function(response){$scope.model=response.Data,$scope.model.ExitCleaningDecisionDate||"Possible"!==$scope.model.ExitCleaningRequestStatus||($scope.model.ExitCleaningDecisionDate=getCurrentIsoDate("default")),$scope.model.ExitCleaningConfirmedDate||"Possible"===$scope.model.ExitCleaningRequestStatus||($scope.model.ExitCleaningConfirmedDate=getCurrentIsoDate("default"))}),$scope.save=function(close){repository.updateSingle(repository.apiData.areaXCleaningTask.url,$scope.model).then(function(result){repository.growl(translationService.translate("web-areaXCleaningTask-exitCleaning-saved","Utreisevasket har blitt oppdatert"),"success"),close&&$scope.ok(result)},function(error){repository.growl(error,"danger")})},$scope.cancelExitCleaning=function(){var cleaningCompletion={GuidCleaningTask:$scope.model.GuidCleaningTask,GuidArea:$scope.model.GuidArea,GuidPerson:user.guidPerson,GuidResourceGroup:user.guidPersonResourceGroup,ExitCleaningDecisionDate:getCurrentIsoDate($scope.model.ExitCleaningDecisionDate),ExitCleaningConfirmedDate:getCurrentIsoDate($scope.model.ExitCleaningConfirmedDate),ExitCleaningRequestStatus:$scope.model.ExitCleaningRequestStatus,ExitCleaningCompletionStatus:"Cancelled",MustCorrectDrawing:$scope.model.MustCorrectDrawing,MustCorrectDrawingComment:$scope.model.MustCorrectDrawingComment};repository.createMultiple(repository.apiData.cleaningCompletion.url,[cleaningCompletion]).then(function(result){repository.growl(translationService.translate("web-areaXCleaningTask-exitCleaning-cancelled","Utreisevasket har blitt kansellert"),"success"),$scope.ok()},function(error){repository.growl(error,"danger")})}, $scope.setExitCleaningStatus=function(status){status&&$scope.model.ExitCleaningRequestStatus!==status&&($scope.model.ExitCleaningRequestStatus=status,"Possible"===status||$scope.model.ExitCleaningConfirmedDate||($scope.model.ExitCleaningConfirmedDate=getCurrentIsoDate("default")),"Discharged"===status&&($scope.model.ExitCleaningConfirmedDate=(new Date).toISOString()),$scope.save(!0))},$scope.cancel=function(reason){reason?modalInstance.dismiss(reason):modalInstance.dismiss("cancel")},$scope.ok=function(result){modalInstance.close(result)},$scope.isTimeInPast=function(fieldName){if(!$scope.model)return!1;var time=$scope.model[fieldName];return!!time&&(new Date).getTime()>new Date(time).getTime()}}angular.module("Plania").controller("ExitCleaningController",["$scope","Repository","TranslationService","params","$modalInstance",controller])}(),function(){function controller($scope,repository,params,modalInstance,config,translationService,$filter,listService){var user=repository.authService.getUserData();$scope.person={Caption:user.realName,Guid:user.guidPerson},$scope.activateAutocomplete=!1,$scope.cleaningTasks=[],$scope.cleaningTasksAreaGrouped=[],$scope.cleaningTasksCleaningTypeGrouped=[],$scope.cleaningTaskGroupBy="none",$scope.isAllTasksSelected=!1,$scope.isRunningAction=!1;var columns=["AverageCleaningPerYear","CleaningTask.Id","CleaningTask.CleaningType","CleaningTask.AverageCleaningPerYear","CleaningTask.ExplanatoryText","Area.Id","Area.Description","DelayedDate","ExitCleaningRequestStatus","ExitCleaningConfirmedDate","ExitCleaningDecisionDate","NextCleaningDate"],filter={showTodaysTasks:!0,PropertyFilter:[{Property:"GuidArea",Operator:"in",Value:params.guids.join(",")}]};repository.GetPaginated(repository.apiData.areaXCleaningTask.url,0,-1,{},filter,null,JSON.stringify(columns)).then(function(result){$scope.cleaningTasks=result.List,$scope.cleaningTasks.sort(sortByCleaningType),$scope.cleaningTasks.forEach(function(task){var areaGroup=_.find($scope.cleaningTasksAreaGrouped,function(grouped){return grouped.header===task.Area.Caption}),cleaningTypeGroup=_.find($scope.cleaningTasksCleaningTypeGrouped,function(grouped){return grouped.header===task.CleaningTask.CleaningType});areaGroup?areaGroup.items.push(task):$scope.cleaningTasksAreaGrouped.push({header:task.Area.Caption,items:[task]}),cleaningTypeGroup?cleaningTypeGroup.items.push(task):$scope.cleaningTasksCleaningTypeGrouped.push({header:task.CleaningTask.CleaningType,items:[task]}),"StandardCleaning"===task.CleaningTask.CleaningType&&$scope.selectedTasks.push(task.Guid)}),$scope.cleaningTasksAreaGrouped.sort(function(a,b){return(""+a.header).localeCompare(b.header)}),checkSelectedTasks(),setTimeout(function(){$scope.activateAutocomplete=!0},250)}).catch(function(error){repository.growl(error,"danger")}),$scope.selectedTasks=[];var checkSelectedTasks=function(skipGroup){$scope.selectedTasks.length===$scope.cleaningTasks?$scope.isAllTasksSelected=!0:$scope.isAllTasksSelected=!1,skipGroup||($scope.cleaningTasksAreaGrouped.forEach(function(task){var guids=task.items.map(function(item){return item.Guid}),selected=$scope.selectedTasks.filter(function(guidTask){return guids.indexOf(guidTask)>=0});task.allTasksSelected=selected.length===guids.length}),$scope.cleaningTasksCleaningTypeGrouped.forEach(function(task){var guids=task.items.map(function(item){return item.Guid}),selected=$scope.selectedTasks.filter(function(guidTask){return guids.indexOf(guidTask)>=0});task.allTasksSelected=selected.length===guids.length}))};$scope.selectTask=function(task){if(_.contains($scope.selectedTasks,task.Guid))for(var i=0;i<$scope.selectedTasks.length;i++){var p=$scope.selectedTasks[i];if(p===task.Guid)return $scope.selectedTasks.splice(i,1),void checkSelectedTasks()}else $scope.selectedTasks.push(task.Guid),checkSelectedTasks()},$scope.isSelected=function(guid){return _.contains($scope.selectedTasks,guid)},$scope.selectMultipleTasks=function(){$scope.selectedTasks=[],$scope.isAllTasksSelected||$scope.cleaningTasks.forEach(function(task){$scope.selectedTasks.push(task.Guid)}),$scope.isAllTasksSelected=!$scope.isAllTasksSelected,$scope.cleaningTasksAreaGrouped.forEach(function(group){group.allTasksSelected=$scope.isAllTasksSelected}),$scope.cleaningTasksCleaningTypeGrouped.forEach(function(group){group.allTasksSelected=$scope.isAllTasksSelected})},$scope.selectMultipleGroupedTasks=function(group){if(group&&"none"!==$scope.cleaningTaskGroupBy){var list="area"===$scope.cleaningTaskGroupBy?$scope.cleaningTasksAreaGrouped:$scope.cleaningTasksCleaningTypeGrouped,guids=_.find(list,function(l){return l.header===group.header}).items.map(function(item){return item.Guid});group.allTasksSelected?$scope.selectedTasks=$scope.selectedTasks.filter(function(guidTask){return guids.indexOf(guidTask)<0}):guids.forEach(function(guid){$scope.selectedTasks.indexOf(guid)<0&&$scope.selectedTasks.push(guid)}),group.allTasksSelected=!group.allTasksSelected,checkSelectedTasks(!0)}},$scope.getNextCleaningDateString=function(task){return listService.getNextCleaningDateString(task,!0)};var sortByCleaningType=function(left,right){return"StandardCleaning"===left.CleaningTask.CleaningType?-1:"StandardCleaning"===right.CleaningTask.CleaningType?1:"InfectionCleaning"===left.CleaningTask.CleaningType?-1:"InfectionCleaning"===right.CleaningTask.CleaningType?1:"ExitCleaning"===left.CleaningTask.CleaningType?-1:"ExitCleaning"===right.CleaningTask.CleaningType?1:"AdditionalCleaning"===left.CleaningTask.CleaningType?-1:"AdditionalCleaning"===right.CleaningTask.CleaningType?1:"PeriodicCleaning"===left.CleaningTask.CleaningType?-1:"PeriodicCleaning"===right.CleaningTask.CleaningType?1:"Undefined"===left.CleaningTask.CleaningType?-1:"Undefined"===right.CleaningTask.CleaningType?1:left.CleaningTask.CleaningType===right.CleaningTask.CleaningType?0:void 0};$scope.autocompleteFilter=function(filterName){switch(filterName){case"person":return{PropertyFilter:[{Property:"DoesCleaningTasks",Operator:"=",Value:"1"}]}}return null},$scope.save=function(){var completionList=[];$scope.selectedTasks.forEach(function(taskGuid){var task=_.find($scope.cleaningTasks,function(o){return o.Guid===taskGuid}),cleaningCompletion={GuidCleaningTask:task.GuidCleaningTask,GuidArea:task.GuidArea,GuidPerson:$scope.person.Guid,ExplanatoryText:task.ExplanatoryText,ExtraTime:task.ExtraTime,EstimatedTime:Math.ceil(60*task.EstimatedTime),CompletionStatus:"Completed"};"ExitCleaning"===task.CleaningTask.CleaningType&&(cleaningCompletion.ExitCleaningDecisionDate=task.ExitCleaningDecisionDate,cleaningCompletion.ExitCleaningConfirmedDate=task.ExitCleaningConfirmedDate,cleaningCompletion.ExitCleaningRequestStatus=task.ExitCleaningRequestStatus),completionList.push(cleaningCompletion)}),$scope.isRunningAction=!0,repository.createMultiple(repository.apiData.cleaningCompletion.url,completionList).then(function(result){$scope.isRunningAction=!1,repository.growl("Rengjøringen har blitt lagret","success"),$scope.ok()},function(error){$scope.isRunningAction=!1,repository.growl(error,"danger")})},$scope.delayCleaning=function(){for(var i=0;i<$scope.selectedTasks.length;i++){var selectedTask=_.find($scope.cleaningTasks,{Guid:$scope.selectedTasks[i]});if("StandardCleaning"!==selectedTask.CleaningTask.CleaningType&&"Undefined"!==selectedTask.CleaningTask.CleaningType)return void swal({title:translationService.translate("web-swal-cleaningCompletion-delay-nonStandard-title","Kan ikke utsette engangsoppgaver"),text:translationService.translate("web-swal-cleaningCompletion-delay-nonStandard-message","Fjern kryssene på valgte engangsoppgaver for å utsette daglig renhold"),type:"warning",confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-button-ok","Ok"),closeOnConfirm:!1})}var changeList=[];$scope.selectedTasks.forEach(function(taskGuid){changeList.push({Guid:taskGuid,DelayedDate:(new Date).toISOString()})}),$scope.isRunningAction=!0,repository.patch(repository.apiData.areaXCleaningTask.url,null,changeList).then(function(response){var success=_.every(response,function(response){return response.IsSuccess});$scope.isRunningAction=!1,success?repository.growl(translationService.translate("web-cleaningTask-delayedTask","Rengjøring utsatt"),"success"):repository.growl(translationService.translate("web-cleaningTask-delayedTask-failed","En eller flere renhold ble ikke utsatt"),"danger"),$scope.ok("delayed")},function(error){$scope.isRunningAction=!1,repository.showError(error)})},$scope.disableCompletion=function(){return _.find($scope.selectedTasks,function(guid){var selectedTask=_.find($scope.cleaningTasks,function(task){return guid===task.Guid});return selectedTask&&!selectedTask.Recurrence&&!selectedTask.ExtraTime&&"ExitCleaning"!==selectedTask.CleaningTask.CleaningType})},$scope.disableCleaningCompletionForm=function(form){return $scope.selectedTasks.length<1||(!!$scope.disableCompletion()||!(!form||form.$valid))},$scope.ok=function(result){modalInstance.close(result)},$scope.cancel=function(){modalInstance.dismiss("cancel")}}angular.module("Plania").controller("MultipleCleaningCompletionsController",["$scope","Repository","params","$modalInstance","config","TranslationService","$filter","ListService",controller])}(),function(){function controller($scope,repository,params,modalInstance,config,translationService,$filter,listService){function getAreaXCleaningTasks(){repository.GetPaginated(repository.apiData.areaXCleaningTask.url,0,-1,{},filter,null,JSON.stringify(columns)).then(function(result){$scope.cleaningTasksAreaGrouped=[],$scope.cleaningTasksCleaningTypeGrouped=[],$scope.cleaningTasks=result.List,$scope.cleaningTasks.sort(sortByCleaningType),$scope.cleaningTasks.forEach(function(task){var areaGroup=_.find($scope.cleaningTasksAreaGrouped,function(grouped){return grouped.header===task.Area.Caption}),cleaningTypeGroup=_.find($scope.cleaningTasksCleaningTypeGrouped,function(grouped){return grouped.header===task.CleaningTask.CleaningType});areaGroup?areaGroup.items.push(task):$scope.cleaningTasksAreaGrouped.push({header:task.Area.Caption,items:[task]}),cleaningTypeGroup?cleaningTypeGroup.items.push(task):$scope.cleaningTasksCleaningTypeGrouped.push({header:task.CleaningTask.CleaningType,items:[task]}),"StandardCleaning"===task.CleaningTask.CleaningType&&$scope.selectedTasks.push(task.Guid)}),$scope.cleaningTasksAreaGrouped.sort(function(a,b){return(""+a.header).localeCompare(b.header)}),checkSelectedTasks(),setTimeout(function(){$scope.activateAutocomplete=!0},250)}).catch(function(error){repository.growl(error,"danger")})}$scope.cleaningTasks=[],$scope.selectedTasks=[],$scope.cleaningTasksAreaGrouped=[],$scope.cleaningTasksCleaningTypeGrouped=[],$scope.cleaningTaskGroupBy="none",$scope.isAllTasksSelected=!1;var wasUpdated=!1,filter={PropertyFilter:[{Property:"GuidArea",Operator:"in",Value:params.guids.join(",")},{Property:"CleaningTask.CleaningType",Operator:"<>",Value:"1"},{Property:"CleaningTask.CleaningType",Operator:"<>",Value:"3"}]},columns=["CleaningTask.Id","CleaningTask.CleaningType","CleaningTask.ExplanatoryText","Area.Id","Area.Description","PausedFromDate","PausedToDate","PausedReason"],sortByCleaningType=function(left,right){return"StandardCleaning"===left.CleaningTask.CleaningType?-1:"StandardCleaning"===right.CleaningTask.CleaningType?1:"InfectionCleaning"===left.CleaningTask.CleaningType?-1:"InfectionCleaning"===right.CleaningTask.CleaningType?1:"ExitCleaning"===left.CleaningTask.CleaningType?-1:"ExitCleaning"===right.CleaningTask.CleaningType?1:"AdditionalCleaning"===left.CleaningTask.CleaningType?-1:"AdditionalCleaning"===right.CleaningTask.CleaningType?1:"PeriodicCleaning"===left.CleaningTask.CleaningType?-1:"PeriodicCleaning"===right.CleaningTask.CleaningType?1:"Undefined"===left.CleaningTask.CleaningType?-1:"Undefined"===right.CleaningTask.CleaningType?1:left.CleaningTask.CleaningType===right.CleaningTask.CleaningType?0:void 0},checkSelectedTasks=function(skipGroup){$scope.selectedTasks.length===$scope.cleaningTasks?$scope.isAllTasksSelected=!0:$scope.isAllTasksSelected=!1,skipGroup||($scope.cleaningTasksAreaGrouped.forEach(function(task){var guids=task.items.map(function(item){return item.Guid}),selected=$scope.selectedTasks.filter(function(guidTask){return guids.indexOf(guidTask)>=0});task.allTasksSelected=selected.length===guids.length}),$scope.cleaningTasksCleaningTypeGrouped.forEach(function(task){var guids=task.items.map(function(item){return item.Guid}),selected=$scope.selectedTasks.filter(function(guidTask){return guids.indexOf(guidTask)>=0});task.allTasksSelected=selected.length===guids.length}))};getAreaXCleaningTasks(),$scope.selectTask=function(task){if(_.contains($scope.selectedTasks,task.Guid))for(var i=0;i<$scope.selectedTasks.length;i++){var p=$scope.selectedTasks[i];if(p===task.Guid)return $scope.selectedTasks.splice(i,1),void checkSelectedTasks()}else $scope.selectedTasks.push(task.Guid),checkSelectedTasks()},$scope.selectMultipleTasks=function(){$scope.selectedTasks=[],$scope.isAllTasksSelected||$scope.cleaningTasks.forEach(function(task){$scope.selectedTasks.push(task.Guid)}),$scope.isAllTasksSelected=!$scope.isAllTasksSelected,$scope.cleaningTasksAreaGrouped.forEach(function(group){group.allTasksSelected=$scope.isAllTasksSelected}),$scope.cleaningTasksCleaningTypeGrouped.forEach(function(group){group.allTasksSelected=$scope.isAllTasksSelected})},$scope.selectMultipleGroupedTasks=function(group){if(group&&"none"!==$scope.cleaningTaskGroupBy){var list="area"===$scope.cleaningTaskGroupBy?$scope.cleaningTasksAreaGrouped:$scope.cleaningTasksCleaningTypeGrouped,guids=_.find(list,function(l){return l.header===group.header}).items.map(function(item){return item.Guid});group.allTasksSelected?$scope.selectedTasks=$scope.selectedTasks.filter(function(guidTask){return guids.indexOf(guidTask)<0}):guids.forEach(function(guid){$scope.selectedTasks.indexOf(guid)<0&&$scope.selectedTasks.push(guid)}),group.allTasksSelected=!group.allTasksSelected,checkSelectedTasks(!0)}},$scope.isSelected=function(guid){return _.contains($scope.selectedTasks,guid)},$scope.canSave=function(){return $scope.selectedTasks.length>0&&$scope.pausedFromDate&&$scope.pausedToDate},$scope.canRemovePause=function(){var anyPaused=_.some($scope.selectedTasks,function(guid){var task=_.find($scope.cleaningTasks,function(ct){return ct.Guid===guid});return task.PausedFromDate||task.PausedToDate});return $scope.selectedTasks.length>0&&anyPaused},$scope.removePausedDates=function(){var changeList=[];_.forEach($scope.selectedTasks,function(guid){var change={Guid:guid,PausedFromDate:null,PausedToDate:null,PausedReason:null};changeList.push(change)}),repository.patch(repository.apiData.areaXCleaningTask.url,null,changeList).then(function(response){_.every(response,function(response){return response.IsSuccess})?repository.growl(translationService.translate("web-cleaningTask-multipleOnHold-updateSuccess","Oppgaver oppdatert"),"success"):repository.growl(translationService.translate("web-cleaningTask-multipleOnHold-updateFailed","En eller flere oppgaver ble ikke oppdatert"),"danger"),getAreaXCleaningTasks(),wasUpdated=!0},function(error){repository.growl(error,"danger")})},$scope.save=function(){var changeList=[],pausedFromDate=new Date($scope.pausedFromDate.setHours(0,0,0,0)),pausedToDate=new Date($scope.pausedToDate.setHours(0,0,0,0));_.forEach($scope.selectedTasks,function(guid){var change={Guid:guid,PausedFromDate:pausedFromDate,PausedToDate:pausedToDate,PausedReason:$scope.pausedReason};changeList.push(change)}),repository.patch(repository.apiData.areaXCleaningTask.url,null,changeList).then(function(response){_.every(response,function(response){return response.IsSuccess})?repository.growl(translationService.translate("web-cleaningTask-multipleOnHold-updateSuccess","Oppgaver oppdatert"),"success"):repository.growl(translationService.translate("web-cleaningTask-multipleOnHold-updateFailed","En eller flere oppgaver ble ikke oppdatert"),"danger"),getAreaXCleaningTasks(),wasUpdated=!0},function(error){repository.growl(error,"danger")})},$scope.close=function(){wasUpdated?modalInstance.close():modalInstance.dismiss("cancel")}}angular.module("Plania").controller("MultipleCleaningOnHoldController",["$scope","Repository","params","$modalInstance","config","TranslationService","$filter","ListService",controller])}(),function(){function controller($scope,$modalInstance,params,repository,translationService,listService,ngTableParams){$scope.selectedCleaningTask=null,$scope.selectedAreaXCleaningTask={},$scope.areaXCleaningTasks=[],$scope.areas=[],$scope.errorDuplicateExitCleaningOnRoom=!1,$scope.errorNoAreaXCleaningTasks=!1,$scope.showMultiSelectView=!1,$scope.multiSelectedAreaXCleaningTasks=[],$scope.templateCleaningTask={},$scope.tabs=[{heading:translationService.translate("web-dwg-multipleRequest-chooseCleaningTask","Velg renhold"),step:0},{heading:translationService.translate("web-dwg-multipleRequest-confirmRooms","Fyll ut og bekreft valgte rom"),step:1}],$scope.step=0,$scope.isCurrentStep=function(step){return $scope.step===step},$scope.setCurrentStep=function(step){0===$scope.step&&0===$scope.areaXCleaningTasks.length||($(".tab-content").css("overflow","hidden"),setTimeout(function(){$(".tab-content").css("overflow","visible")},500),$scope.step=step)},$scope.isLastStep=function(){return $scope.step===$scope.tabs.length-1},$scope.getNextLabel=function(){return $scope.isLastStep()?translationService.translate("web-button-confirm","Bekreft"):translationService.translate("web-button-next","Neste")},$scope.handlePrevious=function(){$scope.setCurrentStep($scope.step-(0===$scope.step?0:1))},$scope.handleNext=function(){if($scope.isLastStep())$scope.create();else{if(0===$scope.step&&0===$scope.areaXCleaningTasks.length)return;$scope.setCurrentStep($scope.step+=1)}};var areaColumns=["Id","Description","HasExitCleaning"],areaFilter={PropertyFilter:[{Property:"Guid",Operator:"in",Value:params.guids.join(",")}]};repository.GetPaginated(repository.apiData.area.url,0,-1,{},areaFilter,null,JSON.stringify(areaColumns)).then(function(result){$scope.areas=result.List,$scope.cleaningTaskInfo.initTable()},function(error){repository.growl(error,"danger")}),$scope.cleaningTaskInfo=new function(){var me=this;this.apiData=repository.apiData.cleaningTask,this.filter={PropertyFilter:[{Property:"IsTemplate",Operator:"=",Value:"1"}]},this.columns=[{Position:1,Title:translationService.translate("web-cleaningTask-Id","Renhold"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cleaningTask-CleaningType","Renholdstype"),Property:"CleaningType",PropertyType:"enum.cleaningType"}],this.dataColumns=["Id","EstimatedTime","EstimatedCost","ExplanatoryText","NumericFieldName","CleaningType","ExitCleaningDecisionDate","ExitCleaningConfirmedDate"],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:me.filter},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),me.dataColumns.forEach(function(col){columns.includes(col)||columns.push(col)}),repository.GetPaginated(me.apiData.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){result.List.forEach(function(task){"ExitCleaning"===task.CleaningType&&(task.ExitCleaningRequestStatus="Possible",task.ExitCleaningDecisionDate=getCurrentIsoTime(task.ExitCleaningDecisionDate),task.ExitCleaningConfirmedDate=getCurrentIsoTime(task.ExitCleaningConfirmedDate))}),me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))},this.selectCleaningTask=function(cleaningTask){if($scope.selectedCleaningTask){if($scope.selectedCleaningTask.Guid===cleaningTask.Guid)return void $scope.handleNext();$scope.areaXCleaningTasks=[]}$scope.selectedCleaningTask=cleaningTask,$scope.errorDuplicateExitCleaningOnRoom=!1,$scope.errorNoAreaXCleaningTasks=!1,$scope.areas.forEach(function(area){if("ExitCleaning"===$scope.selectedCleaningTask.CleaningType&&area.HasExitCleaning)$scope.errorDuplicateExitCleaningOnRoom=!0;else{var cleaningTaskCopy=angular.copy($scope.selectedCleaningTask),areaXCleaningTask={GuidArea:area.Guid,GuidCleaningTask:cleaningTaskCopy.Guid,AttributeValues:cleaningTaskCopy.AttributeValues,Area:area,CleaningTask:cleaningTaskCopy};"ExitCleaning"===cleaningTaskCopy.CleaningType&&(areaXCleaningTask.ExitCleaningConfirmedDate=cleaningTaskCopy.ExitCleaningConfirmedDate,areaXCleaningTask.ExitCleaningDecisionDate=cleaningTaskCopy.ExitCleaningDecisionDate,areaXCleaningTask.ExitCleaningRequestStatus=cleaningTaskCopy.ExitCleaningRequestStatus),areaXCleaningTask.AttributeValues.forEach(function(attribute){"Date"===attribute.ValueType&&attribute.DateValue&&(attribute.DateValue=attribute.DateValue.toISOString())}),$scope.areaXCleaningTasks.push(areaXCleaningTask)}}),$scope.areaXCleaningTasks.length>0?($scope.areaXCleaningTasks[0].hasBeenViewed=!0,$scope.selectedAreaXCleaningTask=$scope.areaXCleaningTasks[0],$scope.handleNext()):$scope.errorNoAreaXCleaningTasks=!0}},$scope.create=function(){var copyAreaXCleaningTasks=angular.copy($scope.areaXCleaningTasks),postAreaXCleaningTask=[];copyAreaXCleaningTasks.forEach(function(task){"ExitCleaning"===task.CleaningTask.CleaningType&&("Possible"===task.ExitCleaningRequestStatus?(task.ExitCleaningConfirmedDate=null,task.ExitCleaningDecisionDate=getCurrentIsoTime(task.ExitCleaningDecisionDate)):"Discharged"===task.ExitCleaningRequestStatus?(task.ExitCleaningDecisionDate=null,task.ExitCleaningConfirmedDate=(new Date).toISOString()):(task.ExitCleaningDecisionDate=null,task.ExitCleaningConfirmedDate=getCurrentIsoTime(task.ExitCleaningConfirmedDate))),task.AttributeValues.forEach(function(attribute){"Date"===attribute.ValueType&&attribute.DateValue&&(attribute.DateValue=attribute.DateValue.toISOString())}),delete task.Area,delete task.CleaningTask,postAreaXCleaningTask.push(task)}),repository.createMultiple(repository.apiData.areaXCleaningTask.url,postAreaXCleaningTask).then(function(result){repository.growl(translationService.translate("web-dwg-multipleRequest-create-success","Renholdsoppgavene har blitt registrert til rommet")),$scope.close()},function(error){repository.growl(error,"danger")})},$scope.selectAreaXCleaningTask=function(task){$scope.multiSelectView=!1,task.hasBeenViewed=!0,$scope.selectedAreaXCleaningTask=task};var attributeHasValue=function(attribute){switch(attribute.ValueType){case"Combo":case"Text":return attribute.TextValue;case"Numeric":return attribute.NumericValue;case"Date":return attribute.DateValue;case"CheckBox":return attribute.BitValue}};$scope.$watch("multiSelectView",function(newValue,oldValue){oldValue!==newValue&&(!0===newValue?$scope.templateCleaningTask=angular.copy($scope.selectedAreaXCleaningTask):$scope.multiSelectedAreaXCleaningTasks=[])}),$scope.multiSelectTask=function(areaXCleaningTask){_.some($scope.multiSelectedAreaXCleaningTasks,{$$hashKey:areaXCleaningTask.$$hashKey})?_.remove($scope.multiSelectedAreaXCleaningTasks,{$$hashKey:areaXCleaningTask.$$hashKey}):$scope.multiSelectedAreaXCleaningTasks.push(areaXCleaningTask)},$scope.copyPropertiesFromTemplateToTasks=function(){_.forEach($scope.multiSelectedAreaXCleaningTasks,function(templateAreaXCleaningTask){var originalTask=_.find($scope.areaXCleaningTasks,{$$hashKey:templateAreaXCleaningTask.$$hashKey});originalTask.ExitCleaningConfirmedDate=$scope.templateCleaningTask.ExitCleaningConfirmedDate,originalTask.ExitCleaningDecisionDate=$scope.templateCleaningTask.ExitCleaningDecisionDate,originalTask.ExitCleaningRequestStatus=$scope.templateCleaningTask.ExitCleaningRequestStatus,originalTask.AttributeValues=angular.copy($scope.templateCleaningTask.AttributeValues)}),$scope.multiSelectView=!1},$scope.isTaskMultiSelected=function(areaXCleaningTask){return _.some($scope.multiSelectedAreaXCleaningTasks,{$$hashKey:areaXCleaningTask.$$hashKey})},$scope.getStatusIcon=function(areaXCleaningTask){return $scope.hasMissingProperties(areaXCleaningTask)?"fa-circle-exclamation c-red":$scope.hasWarnings(areaXCleaningTask)?"fa-triangle-exclamation c-orange":"fa-check-circle c-green"},$scope.hasMissingProperties=function(task){var mandatoryFields=task.AttributeValues.filter(function(attr){return"Mandatory"===attr.ValidityRules});if(!mandatoryFields)return!1;for(var i=0;inew Date(time).getTime()};var getCurrentIsoTime=function(input){var date=new Date;if(input){var selectedDate=new Date(input);date.setHours(selectedDate.getHours(),selectedDate.getMinutes(),0,0)}else date.setHours(12,0,0,0);return date.toISOString()};$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.close=function(){$modalInstance.close()}}angular.module("Plania").controller("MultipleDwgRequestController",["$scope","$modalInstance","params","Repository","TranslationService","ListService","ngTableParams",controller])}(),function(){function controller($scope,repository,enumService,registeredFieldService,constants,$modal,translationService){$scope.request={},$scope.autoCompleteModel={},$scope.selectedRequest={},$scope.mandatoryFieldRules=[];var registeredFieldsPromise=registeredFieldService.getRegisteredField(repository.commonService.prefix.Request);registeredFieldsPromise.then(function(result){$scope.mandatoryFieldRules=_.filter(result,{Mandatory:!0})}),$scope.isMandatoryOrPrefill=function(domainFieldName){return!!domainFieldName&&(!!$scope.request[domainFieldName]||_.some($scope.mandatoryFieldRules,function(rule){return rule.DomainFieldName===domainFieldName}))};var setUserDataOnRequest=function(request){registeredFieldsPromise.then(function(){var userData=repository.authService.getUserData();request.EmailAddress=userData.email,request.Telephone=userData.phone,request.ContactPerson=userData.guidPerson?userData.personFirstName+" "+userData.personLastName:userData.realName,userData.guidDepartment&&(request.GuidDepartment=userData.guidDepartment,request.Department={Guid:userData.guidDepartment,Name:userData.userDepartment,Caption:userData.userDepartment},$scope.department=request.Department.Caption)})};setUserDataOnRequest($scope.request);var requestColumns=["Description","ExplanatoryText","DueDate","Priority.Id","Priority.Description","ActivityCategory.Id","ActivityCategory.Description","ResourceGroup.Id","ResourceGroup.Description","ResponsiblePerson.FirstName","ResponsiblePerson.LastName"];repository.GetPaginated(repository.apiData.request.url,0,50,{Description:"asc"},{PropertyFilter:[{Property:"IsTemplate",Operator:"=",Value:"true"}]},null,JSON.stringify(requestColumns)).then(function(result){$scope.requests=result.List}),$scope.activateAutocomplete=!0,$scope.autoCompleteFilter=function(filterName){switch(filterName){case"equipment":return{GuidBuilding:$scope.request.GuidBuilding,IsApparatus:!1,PropertyFilter:[{Property:"IsTemplate",Operator:"=",Value:!1}]};case"area":return{GuidBuilding:$scope.request.GuidBuilding,GuidDrawing:$scope.request.GuidDrawing};case"drawing":return{GuidBuilding:$scope.request.GuidBuilding};case"person":return{};case"responsiblePerson":return{GuidBuildingResponsible:$scope.request.GuidBuilding};case"department":return{};case"priority":return $scope.request.IsBBYLimited?{PropertyFilter:[{Property:"Description",Operator:"contains",Value:"VH"},{Property:"EntityType",Operator:"=",Value:6}]}:{PropertyFilter:[{Property:"EntityType",Operator:"=",Value:6}]};case"cause":return $scope.request.IsBBYLimited?{PropertyFilter:[{Property:"Id",Operator:"StartsWith",Value:"VH"}]}:{};case"resourceGroup":return{PropertyFilter:[{Property:"DoesMaintenanceTasks",Operator:"=",Value:"true"}]};case"activityCategory":return{PropertyFilter:[{Property:"UseInRequest",Operator:"=",Value:"true"},{Property:"IsAbstract",Operator:"=",Value:"0"}]}}},$scope.onPrioritySelect=function(priority){priority&&($scope.request.GuidPriority=priority.Guid,priority.HasDeadline?($scope.request.DueDate=enumService.getTimeUnitDate(new Date,priority.DeadlinePeriodUnit,priority.DeadlinePeriodNumber),$scope.restrictDueDate=!0):$scope.restrictDueDate=!1)},$scope.calendars={dueDate:!1},$scope.open=function($event,calendar){$scope.calendars[calendar]=!$scope.calendars[calendar],$event.preventDefault(),$event.stopPropagation()},$scope.selectRequest=function(request){$scope.request=angular.copy(request),$scope.restrictDueDate=!1,$scope.autoCompleteModel.responsible=request.ResponsiblePerson?request.ResponsiblePerson.Caption:null,$scope.autoCompleteModel.activityCategory=request.ActivityCategory?request.ActivityCategory.Caption:null,$scope.autoCompleteModel.priority=request.Priority?request.Priority.Caption:null,$scope.autoCompleteModel.resourceGroup=request.ResourceGroup?request.ResourceGroup.Caption:null,$scope.selectedRequest=request,setUserDataOnRequest($scope.request)},$scope.sendRequest=function(){var addImages=$scope.request.AddImages;$scope.request.RegisteredDate=new Date,$scope.request.Status=constants.requestStatus.new,$scope.request.GuidBuilding=$scope.model.GuidBuilding,$scope.request.GuidArea=$scope.model.Guid,delete $scope.request.Guid,delete $scope.request.GuidDataOwner,delete $scope.request.GuidUserCreatedBy,delete $scope.request.GuidUserUpdatedBy,$scope.request.RegisteredDate=new Date($scope.request.RegisteredDate).toISOString(),$scope.request.StartDate&&($scope.request.StartDate=new Date($scope.request.StartDate).toISOString()),$scope.request.DueDate&&($scope.request.DueDate=new Date($scope.request.DueDate).toISOString()),repository.createSingle(repository.apiData.request.url,$scope.request).then(function(result){$scope.request={},$scope.selectedRequest={},$scope.autoCompleteModel.responsible="",$scope.autoCompleteModel.activityCategory="",$scope.autoCompleteModel.priority="",addImages?$modal.open({templateUrl:"app/document/views/createImageModal.html",controller:"CreateDocumentXEntityController",size:"lg",resolve:{params:function(){return{guidRequest:result.Guid}}}}).result.then(function(){repository.growl(translationService.translate("web-technicalRequest-sendRequest-success","Meldingen ble sendt"),"success"),$scope.ok(result)},function(){repository.growl(translationService.translate("web-technicalRequest-sendRequest-success","Meldingen ble sendt"),"success"),$scope.ok(result)}):(repository.growl(translationService.translate("web-technicalRequest-sendRequest-success","Meldingen ble sendt"),"success"),$scope.ok(result))},function(error){repository.growl(error,"danger")})}}angular.module("Plania").controller("TechnicalRequestController",["$scope","Repository","EnumService","RegisteredFieldService","Constants","$modal","TranslationService",controller])}(),function(){function controller($scope,repository,params,$modalInstance){$scope.model={Guid:params.guid} ;var columns=["Area.Id","Area.Description","Area.GuidBuilding","Area.GuidCleaningTeam","Area.Building.Id","Area.Building.Description","Area.ResourceGroup.Id","Area.ResourceGroup.Description","CleaningTask.Id","CleaningTask.Description","CleaningTask.CleaningType","CleaningTask.RecurrenceRule","CleaningTask.Recurrence","Person.FirstName","Person.LastName","UserCreatedBy.RealName","UserUpdatedBy.RealName"];repository.getSingle(repository.apiData.cleaningCompletion.url,$scope.model.Guid,JSON.stringify(columns)).then(function(result){result.Data&&($scope.model=result.Data)},function(error){repository.growl(error,"danger")}),$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CleaningCompletionModalController",["$scope","Repository","params","$modalInstance",controller])}(),function(){function controller($scope,repository,translationService,listCompressionService,$state,ngTableParams,listService,$sessionStorage){function getSummaryData(){var filter={PropertyFilter:[]};$scope.selectedTreeViewItem&&filter.PropertyFilter.push({Property:"Building"===$scope.selectedTreeViewItem.Prefix?"Area.GuidBuilding":"GuidArea",Value:$scope.selectedTreeViewItem.Guid,Operator:"="}),repository.GetPaginated(repository.apiData.cleaningCompletion.url+"getSummary/",0,-1,null,filter,null).then(function(result){$scope.cleaningCompletionSummary=result},function(error){repository.growl(error,"danger")})}function saveHistoryTableSetup(){$sessionStorage.storedCleaningHistoryTable||($sessionStorage.storedCleaningHistoryTable={}),$sessionStorage.storedCleaningHistoryTable[$state.current.name]||($sessionStorage.storedCleaningHistoryTable[$state.current.name]={}),$sessionStorage.storedCleaningHistoryTable[$state.current.name].columnSetup=$scope.completionHistoryColumns}function isTreeViewStored(){return $sessionStorage.storedCleaningHistoryTable&&$sessionStorage.storedCleaningHistoryTable[$state.current.name]}function loadHistoryTableSetup(){return!!isTreeViewStored()&&($scope.completionHistoryColumns=$sessionStorage.storedCleaningHistoryTable[$state.current.name].columnSetup,!0)}$scope.selectedTreeViewItem=null,$scope.cleaningCompletionHistoryList=[],$scope.cleaningCompletionSummary={},$scope.search={history:!1},getSummaryData(),$scope.getHref=function(status){var propertyFilter=[];switch(status){case"expired":propertyFilter.push({Property:"CompletionStatus",Value:0,Operator:"="});break;case"completed":propertyFilter.push({Property:"CompletionStatus",Value:1,Operator:"=",Operand:"OR"}),propertyFilter.push({Property:"CompletionStatus",Value:-1,Operator:"=",Operand:"OR"});break;case"delayed":propertyFilter.push({Property:"CompletionStatus",Value:2,Operator:"="});break;case"cancelled":propertyFilter.push({Property:"CompletionStatus",Value:3,Operator:"="});break;case"completedByExitCleaning":propertyFilter.push({Property:"CompletionStatus",Value:4,Operator:"="});break;case"paused":propertyFilter.push({Property:"CompletionStatus",Value:5,Operator:"="})}$scope.selectedTreeViewItem&&("Building"===$scope.selectedTreeViewItem.Prefix?propertyFilter.push({Property:"Area.GuidBuilding",Value:$scope.selectedTreeViewItem.Guid,Operator:"="}):"Area"===$scope.selectedTreeViewItem.Prefix&&propertyFilter.push({Property:"GuidArea",Value:$scope.selectedTreeViewItem.Guid,Operator:"="}));var filters=listCompressionService.encodeListUri({filter:{PropertyFilter:propertyFilter}});return $state.href("cleaningCompletion.list",{filter:filters})},loadHistoryTableSetup()||($scope.completionHistoryColumns=[{Position:1,Title:translationService.translate("web-cleaningCompletionHistory-year","År"),Property:"Year",PropertyType:"number",groupable:!0,isGrouping:!0,isVisible:!1,sortDir:"desc"},{Position:2,Title:translationService.translate("web-cleaningCompletionHistory-month","Måned"),Property:"Month",PropertyType:"enum.month",groupable:!0,isGrouping:!1,isVisible:!0},{Position:3,Title:translationService.translate("web-cleaningCompletionHistory-estate","Eiendom"),Property:"Estate",PropertyType:"string",groupable:!0,isGrouping:!1,isVisible:!1},{Position:4,Title:translationService.translate("web-cleaningCompletionHistory-building","Bygg"),Property:"Building",PropertyType:"string",groupable:!0,isGrouping:!1,isVisible:!1},{Position:5,Title:translationService.translate("web-cleaningCompletionHistory-cleaningTask","Oppgave"),Property:"CleaningTask",PropertyType:"string",groupable:!0,isGrouping:!1,isVisible:!0},{Position:6,Title:translationService.translate("web-cleaningCompletionHistory-cleaningType","Type"),Property:"CleaningType",PropertyType:"enum.cleaningType",groupable:!0,isGrouping:!1,isVisible:!0},{Position:7,Title:translationService.translate("web-cleaningCompletionHistory-dataOwner","Klient"),Property:"DataOwner",PropertyType:"string",groupable:!0,isGrouping:!1,isVisible:!1},{Position:8,Title:translationService.translate("web-cleaningCompletionHistory-areaClassification","Spesifikasjon"),Property:"AreaClassification",PropertyType:"string",groupable:!0,isGrouping:!1,isVisible:!1},{Position:9,Title:translationService.translate("web-cleaningCompletionHistory-areaCleaningQuality","Kvalitet"),Property:"AreaCleaningQuality",PropertyType:"string",groupable:!0,isGrouping:!1,isVisible:!1},{Position:10,Title:translationService.translate("web-cleaningCompletionHistory-sumCancelled","Kansellert"),Property:"SumCancelled",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!1},{Position:11,Title:translationService.translate("web-cleaningCompletionHistory-sumCompleted","Fullført"),Property:"SumCompleted",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!0},{Position:12,Title:translationService.translate("web-cleaningCompletionHistory-sumCompletedByExitCleaning","Fullført via utreisevask"),Property:"SumCompletedByExitCleaning",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!1},{Position:13,Title:translationService.translate("web-cleaningCompletionHistory-sumDelayed","Utsatt"),Property:"SumDelayed",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!1},{Position:14,Title:translationService.translate("web-cleaningCompletionHistory-sumEstimatedTime","Estimert tid"),Property:"SumEstimatedTime",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!1},{Position:15,Title:translationService.translate("web-cleaningCompletionHistory-sumExitCleaningRequestStatusConfirmed","Bekreftet utreise"),Property:"SumExitCleaningRequestStatusConfirmed",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!1},{Position:16,Title:translationService.translate("web-cleaningCompletionHistory-sumExitCleaningRequestStatusDischarged","Utreist"),Property:"SumExitCleaningRequestStatusDischarged",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!1},{Position:17,Title:translationService.translate("web-cleaningCompletionHistory-sumExitCleaningRequestStatusPossible","Mulig utreise"),Property:"SumExitCleaningRequestStatusPossible",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!1},{Position:18,Title:translationService.translate("web-cleaningCompletionHistory-sumExpired","Utgått"),Property:"SumExpired",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!0},{Position:19,Title:translationService.translate("web-cleaningCompletionHistory-sumExtraTime","Ekstra tid"),Property:"SumExtraTime",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!1},{Position:19,Title:translationService.translate("web-cleaningCompletionHistory-sumPaused","Pauset"),Property:"SumPaused",PropertyType:"number",groupable:!1,isGrouping:!1,isVisible:!1}]),$scope.visibleColumns=$scope.completionHistoryColumns.filter(function(col){return col.isVisible&&!col.isGrouping}),$scope.currentGroupColumn=$scope.completionHistoryColumns.find(function(col){return col.isGrouping}),$scope.historyTable=new ngTableParams({page:1,count:20,sorting:{Month:"desc"},filter:{}},{total:0,counts:[10,20,50],filterDelay:10,groupBy:$scope.currentGroupColumn.Property,getData:function($defer,params){var sorting={},filter=angular.copy(params.filter());filter.PropertyFilter||(filter.PropertyFilter=[]);var secondarySortKey=Object.keys(params.sorting())[0],secondarySortDir=params.sorting()[secondarySortKey];if($scope.currentGroupColumn.sortDir||($scope.currentGroupColumn.sortDir="asc"),$scope.currentGroupColumn.Property===secondarySortKey){var firstVisibleColumn=$scope.visibleColumns[0];sorting[$scope.currentGroupColumn.Property]=$scope.currentGroupColumn.sortDir,sorting[firstVisibleColumn.Property]="asc",params.sorting(firstVisibleColumn.Property,"asc")}else sorting[$scope.currentGroupColumn.Property]=$scope.currentGroupColumn.sortDir,sorting[secondarySortKey]=secondarySortDir;$scope.selectedTreeViewItem&&filter.PropertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:"Building"===$scope.selectedTreeViewItem.Prefix?$scope.selectedTreeViewItem.Guid:$scope.selectedTreeViewItem.GuidBuilding});var columns=$scope.completionHistoryColumns.filter(function(col){if(col.isVisible)return col}).map(function(col){return col.Property});repository.GetPaginated(repository.apiData.cleaningCompletionHistory.url,params.page()-1,params.count(),sorting,filter,"",JSON.stringify(columns)).then(function(result){result&&(saveHistoryTableSetup(),$scope.historyTable.settings().total=result.TotalCount,$scope.historyTable.settings().filterDelay=500,$defer.resolve(result.List))},function(error){repository.growl(error,"danger")})}}),$scope.updateGroupedColumns=function(column){$scope.completionHistoryColumns.forEach(function(col){col.Property===column.Property?($scope.currentGroupColumn=col,col.isGrouping=!0):col.isGrouping=!1}),$scope.visibleColumns=$scope.completionHistoryColumns.filter(function(col){return col.isVisible&&!col.isGrouping}),$scope.historyTable.settings().groupBy=$scope.currentGroupColumn.Property,$scope.historyTable.reload()},$scope.getGroupHeaderValue=function(group,currentGroupColumn){return group.data.length>0&&group.data[0][currentGroupColumn.Property]?listService.GetPropertyValue(group.data[0],currentGroupColumn):header.value},$scope.sortGroupColumn=function(){$scope.currentGroupColumn.sortDir="asc"===$scope.currentGroupColumn.sortDir?"desc":"asc",$scope.historyTable.reload()},$scope.groupSorter=function(groups){if(groups){var asc="asc"===$scope.currentGroupColumn.sortDir;return groups.sort(function(a,b){return asc?a.value-b.value:b.value-a.value}),groups}},$scope.getPropertyValue=function(entity,field){return listService.GetPropertyValue(entity,field)},$scope.$watch("selectedTreeViewItem",function(newVal,oldVal){if(newVal!==oldVal&&(getSummaryData(),$scope.historyTable))if(newVal&&oldVal){var newGuidBuilding=newVal.GuidBuilding?newVal.GuidBuilding:newVal.Guid,oldGuidBuilding=oldVal.GuidBuilding?oldVal.GuidBuilding:oldVal.Guid;newGuidBuilding!==oldGuidBuilding&&$scope.historyTable.reload()}else $scope.historyTable.reload()}),$scope.$watch("currentGroupColumn",function(newVal,oldVal){newVal!==oldVal&&$scope.updateGroupedColumns(newVal)}),$scope.$watch("visibleColumns",function(newVal,oldVal){newVal!==oldVal&&newVal&&($scope.completionHistoryColumns.forEach(function(col){col.isGrouping||(newVal.includes(col)?col.isVisible=!0:col.isVisible=!1)}),$scope.historyTable.reload())}),$scope.$on("$stateChangeSuccess",function(event,toState,toParams,fromState,fromParams){$scope.fromState=fromState.name})}angular.module("Plania").controller("CleaningCompletionOverviewController",["$scope","Repository","TranslationService","ListCompressionService","$state","NgTableParams","ListService","$sessionStorage",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,ngTableParams,$modal,listService,$localStorage){$scope.isUpdate="cleaningQuality.edit"===$scope.navigation.current.name,$scope.model={},$scope.viewMode=!!$scope.isUpdate,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.areaColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Building.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-description"),Property:"Building.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-area-id"),Property:"Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-area-description"),Property:"Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-areaCategory-Description"),Property:"AreaCategory.Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-area-ComputedGrossArea"),Property:"ComputedGrossArea",PropertyType:"string"},{Position:7,Title:translationService.translate("web-area-ComputedNetArea"),Property:"ComputedNetArea",PropertyType:"string"}],$localStorage.generalOptions&&$localStorage.generalOptions.UseAreaClassification&&($scope.areaColumns.push({Position:8,Title:translationService.translate("web-Area-MainFunction"),Property:"MainFunction",PropertyType:"string"}),$scope.areaColumns.push({Position:9,Title:translationService.translate("web-Area-PartFunction"),Property:"PartFunction",PropertyType:"string"}),$scope.areaColumns.push({Position:10,Title:translationService.translate("web-Area-RoomName"),Property:"RoomName",PropertyType:"string"}),$scope.areaColumns.push({Position:11,Title:translationService.translate("web-Area-RoomSpecification"),Property:"RoomSpecification",PropertyType:"string"}));var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.CleaningQuality,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.CleaningQuality,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.CleaningQuality),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.CleaningQuality)};updateAccess(),$scope.isUpdate&&(repository.getSingle(repository.apiData.cleaningQuality.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess(),$scope.reload=!0},function(error){repository.growl(error,"danger")}),$scope.areaTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{PropertyFilter:[{Property:"GuidCleaningQuality",Operator:"=",Value:$stateParams.guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){$scope.loadingAreas=!0;var columns=_.map($scope.areaColumns,"Property");repository.GetPaginated(repository.apiData.area.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.loadingAreas=!1,$scope.areaTable.settings().total=result.TotalCount,$scope.areaTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){$scope.loadingAreas=!1,repository.growl(error,"danger")})}})),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-cleaningQuality-success","Renholdskvaliteten har blitt oppdatert."):translationService.translate("create-cleaningQuality-success","Renholdskvaliteten har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.cleaningQuality.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.cleaningQuality.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cleaningQuality-message","Renholdskvaliteten vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaningQuality-button-confirm","Ja, fjern Renholdskvaliteten"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.cleaningQuality.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-cleaningQuality-success","Renholdskvaliteten ble fjernet!"),result,"success"),$scope.goBack("cleaningQuality.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.addArea=function(){var columns=[{Title:translationService.translate("web-building-id"),Property:"Building.Id"},{Title:translationService.translate("web-building-description"),Property:"Building.Description"},{Title:translationService.translate("web-area-id"),Property:"Id"},{Title:translationService.translate("web-area-description"),Property:"Description"},{Title:translationService.translate("web-areacategory-Description"),Property:"AreaCategory.Description"}];$localStorage.generalOptions&&$localStorage.generalOptions.UseAreaClassification&&(columns.push({Title:translationService.translate("web-Area-MainFunction"),Property:"MainFunction"}),columns.push({Title:translationService.translate("web-Area-PartFunction"),Property:"PartFunction"}),columns.push({Title:translationService.translate("web-Area-RoomName"),Property:"RoomName"}),columns.push({Title:translationService.translate("web-Area-RoomSpecification"),Property:"RoomSpecification"}));var filter={};$scope.hasEditAccess("Area",null,!0)||(filter.PropertyFilter=[{Property:"GuidDataOwner",Operator:"=",Value:repository.commonService.getFilterData().selectedDataOwner.Guid}]),$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:"Legg til Rom",columns:columns,url:repository.apiData.area.url,sorting:{Id:"asc"},filter:filter}}}}).result.then(function(selectedGuids){var areas=[];selectedGuids.forEach(function(guid){areas.push({Guid:guid,GuidCleaningQuality:$scope.model.Guid})}),repository.patch(repository.apiData.area.url,null,areas).then(function(response){_.every(response,function(response){return response.IsSuccess})?repository.growl("Rommene har blitt lagt til","success"):repository.growl("En eller flere rom ble ikke lagt til","danger"),$scope.areaTable.reload()},function(error){repository.showError(error)})},function(error){})},$scope.removeArea=function(area){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cleaningquality-area-message","Rommet vil ikke lenger være knyttet til renholdskvaliteten!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaningquality-area-button-confirm","Ja, fjern rommet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.patch(repository.apiData.area.url,area.Guid,{GuidCleaningQuality:null}).then(function(response){swal(translationService.translate("web-swal-cleaningquality-area-success","Rommet ble fjernet!"),"","success"),$scope.areaTable.reload()},function(error){swal("Error!",error,"error")})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("CleaningQualityController",["$scope","Repository","$stateParams","TranslationService","ngTableParams","$modal","ListService","$localStorage",controller])}(),function(){function controller($scope,repository,params,translationService,$modalInstance){$scope.model=params.cleaningQualityControlArea,$scope.dataLoaded=!1,repository.getSingle(repository.apiData.cleaningQualityControlArea.url,params.cleaningQualityControlArea.Guid).then(function(result){$scope.dataLoaded=!0,$scope.model=result.Data,$scope.IsNew="New"===$scope.model.Status}),$scope.setNotAvailableArea=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cleaningQualityControlArea-setNotAvailableArea-message","Rommet vil bli fjernet fra kontrollen og et nytt rom vil bli valgt ut tilfeldig!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaningQualityControlArea-setNotAvailableArea-button-confirm","Ja, fjern rommet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.runAction(repository.apiData.cleaningQualityControlArea.url+"/setNotAvailable/"+$scope.model.Guid).then(function(result){repository.growl(result,"success"),$modalInstance.close("ok")},function(error){repository.showError(error)})})},$scope.save=function(){swal({title:translationService.translate("web-swal-cleaningQualityControl-complete-title","Er du sikker på at vil du fullføre kontrollen?"),text:translationService.translate("web-swal-cleaningQualityControl-complete-message","Det vil ikke være mulig å gjøre endringer etter den er blitt fullført!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#2196f3",confirmButtonText:translationService.translate("web-swal-cleaningQualityControl-button-complete","Fullfør kontrollen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.model.Status=0,$scope.ok()})},$scope.ok=function(){repository.updateSingle(repository.apiData.cleaningQualityControlArea.url,$scope.model).then(function(result){repository.growl(result,"success"),$modalInstance.close("ok")},function(error){repository.growl(error,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.getInventoryWasteLtValue=function(){var model=$scope.model;return model.InventoryWasteLt+model.InventoryDustLt+model.InventoryStainLt},$scope.getInventoryWasteVtValue=function(){var model=$scope.model;return model.InventoryWasteVt+model.InventoryDustVt+model.InventoryStainVt},$scope.getWallsWasteLtValue=function(){var model=$scope.model;return model.WallsWasteLt+model.WallsDustLt+model.WallsStainLt},$scope.getWallsWasteVtValue=function(){var model=$scope.model;return model.WallsWasteVt+model.WallsDustVt+model.WallsStainVt},$scope.getFloorWasteLtValue=function(){var model=$scope.model;return model.FloorWasteLt+model.FloorDustLt+model.FloorStainLt},$scope.getFloorWasteVtValue=function(){var model=$scope.model;return model.FloorWasteVt+model.FloorDustVt+model.FloorStainVt},$scope.getCeilingWasteLtValue=function(){var model=$scope.model;return model.CeilingWasteLt+model.CeilingDustLt+model.CeilingStainLt},$scope.getCeilingWasteVtValue=function(){var model=$scope.model;return model.CeilingWasteVt+model.CeilingDustVt+model.CeilingStainVt}}angular.module("Plania").controller("CleaningQualityControlAreaModalController",["$scope","Repository","params","TranslationService","$modalInstance",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,ngTableParams,$modal,listService){$scope.isUpdate="cleaningQualityControl.edit"===$scope.navigation.current.name,$scope.model={},$scope.activateAutocomplete=!1,$scope.viewMode=!!$scope.isUpdate,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.CleaningQualityControl,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.CleaningQualityControl,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.CleaningQualityControl),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.CleaningQualityControl)};if($scope.isUpdate){var columns=["Drawing.Id","Drawing.Description","ResourceGroup.Id","ResourceGroup.Description"];repository.getSingle(repository.apiData.cleaningQualityControl.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.reload=!0,updateAccess(),$scope.model.Drawing&&($scope.drawing=$scope.model.Drawing.Id+" - "+$scope.model.Drawing.Description),$scope.model.ResourceGroup&&($scope.resourceGroup=$scope.model.ResourceGroup.Id,$scope.model.ResourceGroup.Description&&($scope.resourceGroup=$scope.resourceGroup+" - "+$scope.model.ResourceGroup.Description)),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}),$scope.areaColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Area.Building.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-description"),Property:"Area.Building.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-area-id"),Property:"Area.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-area-description"),Property:"Area.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-areaCategory-Description"),Property:"Area.AreaCategory.Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-area-ComputedGrossArea"),Property:"Area.ComputedGrossArea",PropertyType:"string"},{Position:7,Title:translationService.translate("web-area-ComputedNetArea"),Property:"Area.ComputedNetArea",PropertyType:"string"},{Position:8,Title:translationService.translate("web-cleaningqualitycontrolxarea-status","Status"),Property:"Status",PropertyType:"string"}],$scope.areaTable=new ngTableParams({page:1,count:10,sorting:{"Area.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidCleaningQualityControl",Operator:"=",Value:$stateParams.guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){$scope.loadingAreas=!0;var columns=_.map($scope.areaColumns,"Property");repository.GetPaginated(repository.apiData.cleaningQualityControlArea.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.loadingAreas=!1,$scope.areaTable.settings().total=result.TotalCount,$scope.areaTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){$scope.loadingAreas=!1,repository.growl(error,"danger")})}})}else{$scope.activateAutocomplete=!0,$scope.model.QualityLevel=6.5;var webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value)switch(prefill.Property){case"Drawing":$scope.drawing=prefill.Value.Label,$scope.model.GuidDrawing=prefill.Value.Guid;break;case"ResourceGroup":$scope.resourceGroup=prefill.Value.Label,$scope.model.GuidResourceGroup=prefill.Value.Guid}else $scope.model[prefill.Property]=prefill.Value})}$scope.goToDrawing=function(){$scope.navigation.go("dwg.view",{guid:$scope.model.GuidDrawing,theme:"cleaningQualityControl",guidQualityControl:$scope.model.Guid})},$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.autocompleteFilter=function(filterName){switch(filterName){case"resourceGroup":return{PropertyFilter:[{Property:"DoesCleaningTasks",operator:"=",Value:"1"}]}}},$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-cleaningQualityControl-success","Kontrollen har blitt oppdatert."):translationService.translate("create-cleaningQualityControl-success","Kontrollen har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};delete $scope.model.Drawing,$scope.isUpdate?(delete $scope.model.NumberOfAreasToCheck,delete $scope.model.ResourceGroup,repository.updateSingle(repository.apiData.cleaningQualityControl.url,$scope.model).then(success,error)):repository.createSingle(repository.apiData.cleaningQualityControl.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cleaningQualityControl-delete-message","Kontrollen og Historikk på tilhørende rom vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaningQualityControl-delete-button-confirm","Ja, fjern kontrollen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.cleaningQualityControl.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-cleaningQualityControl-success","Kontrollen ble fjernet!"),result,"success"),$scope.goBack("cleaningQualityControl.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.OpenArea=function(cleaningQualityControlArea){$modal.open({templateUrl:"app/cleaningQualityControl/views/cleaningQualityControlAreaModal.html",controller:"CleaningQualityControlAreaModalController",size:"lg",resolve:{params:function(){return{cleaningQualityControlArea:cleaningQualityControlArea}}}}).result.then(function(){$scope.areaTable.reload()},function(){$scope.areaTable.reload()})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("CleaningQualityControlController",["$scope","Repository","$stateParams","TranslationService","ngTableParams","$modal","ListService",controller])}(),function(){function controller($scope,$localStorage,translationService,ngTableParams,$stateParams,repository,listService,$modal,$rootScope){$scope.selectedAreas=[],$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.areaColumns=["Area.Building.Id","Area.Building.Description","Area.Building.Guid","Area.Id","Area.Description","Area.Guid","ResourceGroup.Id","ResourceGroup.Guid","AverageCleaningPerYear","Recurrence","Area.RoomName","Area.RoomSpecification","Area.MainFunction","Area.PartFunction","Area.GuidDrawing"],$scope.editedAreaColumns=[{Title:translationService.translate("web-building"),Property:"Area.Building.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidBuilding",AutocompleteService:"building"},{Title:translationService.translate("web-area"),Property:"Area.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidArea",AutocompleteService:"area"},{Title:translationService.translate("web-resourcegroup-id"),Property:"ResourceGroup.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidCleaningTeam",AutocompleteService:"resourceGroup"},{Title:translationService.translate("web-areaxcleaningtask-AverageCleaningPerYear","Tid neste 12 mnd"),Property:"AverageCleaningPerYear",PropertyType:"number"},{Title:translationService.translate("web-areaxcleaningtask-Recurrence","Gjentakelse"),Property:"Recurrence",PropertyType:"recurrence"}], $scope.useAreaClassification=$localStorage.generalOptions&&$localStorage.generalOptions.UseAreaClassification,$scope.useAreaClassification&&($scope.editedAreaColumns.push({Title:translationService.translate("web-Area-MainFunction"),Property:"Area.MainFunction",PropertyType:"string"}),$scope.editedAreaColumns.push({Title:translationService.translate("web-Area-PartFunction"),Property:"Area.PartFunction",PropertyType:"string"}),$scope.editedAreaColumns.push({Title:translationService.translate("web-Area-RoomName"),Property:"Area.RoomName",PropertyType:"string"}),$scope.editedAreaColumns.push({Title:translationService.translate("web-Area-RoomSpecification"),Property:"Area.RoomSpecification",PropertyType:"string"}));var filterTypes=[{value:"Active",name:translationService.translate("web-cleaningTask-areaXCleaningTask-filterType-active","Aktive")},{value:"Expired",name:translationService.translate("web-cleaningTask-areaXCleaningTask-filterType-expired","Utgått")},{value:"Undefined",name:translationService.translate("web-cleaningTask-areaXCleaningTask-filterType-all","Alle")}];$scope.currentSelectedFilterType=filterTypes[0],$scope.setFilter=function(filterTypeValue){var selectedFilterType=_.find(filterTypes,{value:filterTypeValue});selectedFilterType&&filterTypeValue!==$scope.currentSelectedFilterType.value&&($scope.currentSelectedFilterType=selectedFilterType,$scope.areaTable.reload())};var applyFilter=function(filter){var typeValue=$scope.currentSelectedFilterType.value;filter.CleaningStatus=typeValue};$scope.areaTable=new ngTableParams({page:1,count:10,sorting:{"Area.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidCleaningTask",Operator:"=",Value:$stateParams.guid}]}},{total:0,counts:[10,20,50,100,200],filterDelay:10,getData:function($defer,params){var filter=angular.copy(params.filter());void 0!==filter.mainFunction&&""!==filter.mainFunction&&filter.PropertyFilter.push({Property:"Area.MainFunction",Operator:"contains",Value:filter.mainFunction}),void 0!==filter.partFunction&&""!==filter.partFunction&&filter.PropertyFilter.push({Property:"Area.PartFunction",Operator:"contains",Value:filter.partFunction}),void 0!==filter.roomName&&""!==filter.roomName&&filter.PropertyFilter.push({Property:"Area.RoomName",Operator:"contains",Value:filter.roomName}),void 0!==filter.roomSpecification&&""!==filter.roomSpecification&&filter.PropertyFilter.push({Property:"Area.RoomSpecification",Operator:"contains",Value:filter.roomSpecification}),applyFilter(filter),$scope.loadingAreas=!0,repository.GetPaginated(repository.apiData.areaXCleaningTask.url,params.page()-1,params.count(),params.sorting(),filter,"",JSON.stringify($scope.areaColumns)).then(function(result){$scope.loadingAreas=!1,$scope.areaTable.settings().total=result.TotalCount,$scope.areaTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){$scope.loadingAreas=!1,repository.growl(error,"danger")})}}),$scope.addSelected=function(key,guid){if(_.contains($scope.selectedAreas,guid))for(var i=0;i<$scope.selectedAreas.length;i++){var p=$scope.selectedAreas[i];if(p===guid)return void $scope.selectedAreas.splice(i,1)}else $scope.selectedAreas.push(guid)},$scope.isSelected=function(key,guid){return _.contains($scope.selectedAreas,guid)},$scope.addArea=function(){var columns=[{Title:translationService.translate("web-building-caption","Bygg"),Property:"Building.Id"},{Title:translationService.translate("web-area-caption","Areal"),Property:"Id"}];$localStorage.generalOptions&&$localStorage.generalOptions.UseAreaClassification?(columns.push({Title:translationService.translate("web-Area-MainFunction"),Property:"MainFunction"}),columns.push({Title:translationService.translate("web-Area-PartFunction"),Property:"PartFunction"}),columns.push({Title:translationService.translate("web-Area-RoomName"),Property:"RoomName"}),columns.push({Title:translationService.translate("web-Area-RoomSpecification"),Property:"RoomSpecification"})):columns.push({Title:translationService.translate("web-areacategory-Description"),Property:"AreaCategory.Description"}),$modal.open({templateUrl:"app/cleaningTask/views/cleaningTaskWizardModal.html",controller:"CleaningTaskWizardModalController",size:"lg",resolve:{modalParams:function(){return{columns:columns,url:repository.apiData.area.url,sorting:{Id:"asc"},filter:{GuidCleaningTask:$scope.model.Guid},cleaningTask:$scope.model,useCaption:!0}}}}).result.then(function(result){var selectedGuids=result.selectedGuids,recurrenceRule=result.recurrenceRule,attributeValues=result.attributeValues,model=result.model,areaxCleaningTasks=[];selectedGuids.forEach(function(guid){areaxCleaningTasks.push({GuidCleaningTask:$scope.model.Guid,RecurrenceRule:recurrenceRule,GuidArea:guid,AttributeValues:attributeValues,StartDate:model.StartDate?new Date(model.StartDate).toISOString():model.StartDate,UntilDate:model.UntilDate?new Date(model.UntilDate).toISOString():model.UntilDate})}),repository.createMultiple(repository.apiData.areaXCleaningTask.url,areaxCleaningTasks).then(function(result){$scope.areaTable.reload()},function(error){repository.growl(error,"danger")})},function(error){})},$scope.editArea=function(task){$modal.open({templateUrl:"app/area/views/EditAreaXCleaningTaskModal.html",controller:"AreaXCleaningTaskController",resolve:{modalParams:function(){return{Guid:task.Guid}}}}).result.then(function(result){repository.growl(result,"success"),$scope.areaTable.reload()})},$scope.massEdit=function(){if(0===$scope.selectedAreas.length)return void swal({title:translationService.translate("web-swal-error-missingSelect-title","Ingen valg"),text:translationService.translate("list-mass-edit-missingSelect","Ingen valg. Velg en eller flere rader fra listen for å masseredigere"),type:"error"});var showRecurrence="AdditionalCleaning"!==$scope.model.CleaningType&&"InfectionCleaning"!==$scope.model.CleaningType&&"ExitCleaning"!==$scope.model.CleaningType,columns=[];$scope.editedAreaColumns.forEach(function(col){if("Recurrence"!==col.Property||showRecurrence){var column=angular.copy(col);"Recurrence"===col.Property&&(column.CleaningType=$scope.model.CleaningType),columns.push(column)}else;}),$modal.open({templateUrl:"app/common/views/massEditModal.html",controller:"MassEditModalController",size:"lg",resolve:{params:function(){return{columns:columns,selectedRows:$scope.selectedAreas,selectedRowsObjects:_.filter($scope.areaTable.data,function(o){return _.contains($scope.selectedAreas,o.Guid)}),prefix:"AreaXCleaningTask",showPeriodicCleaningRecurrence:"PeriodicCleaning"===$scope.model.CleaningType}}}}).result.then(function(editedRows){$scope.areaTable.reload()},function(){})},$scope.removeArea=function(area){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cleaningquality-area-message","Rommet vil ikke lenger være knyttet til renholdskvaliteten!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaningquality-area-button-confirm","Ja, fjern rommet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.areaXCleaningTask.url,"","guids="+JSON.stringify([area.Guid])).then(function(result){swal(translationService.translate("web-swal-area-cleaningTask-success","Rommet ble fjernet!"),result,"success"),repository.growl("Rommet har blitt fjernet","success"),$scope.selectedAreas=[],$scope.areaTable.reload()})})},$scope.massDeleteArea=function(){if(0===$scope.selectedAreas.length)return void swal({title:translationService.translate("web-swal-error-missingSelect-title","Ingen valg"),text:translationService.translate("list-mass-delete-missingSelect","Ingen valg. Velg en eller flere rader fra listen for å slette flere rom"),type:"error"});swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cleaningtask-areas-message","Rommene vil ikke lenger være knyttet til renholdsoppgaven!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaningquality-areas-button-confirm","Ja, fjern rommene"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.areaXCleaningTask.url,"","guids="+JSON.stringify($scope.selectedAreas)).then(function(result){swal({title:translationService.translate("web-swal-area-cleaningTasks-success","Rommene ble fjernet!"),text:result,type:"success"}),$scope.selectedAreas=[],$scope.areaTable.reload()})})},$scope.$watch("reloadTables",function(newValue,oldValue){newValue!==oldValue&&$scope.areaTable.reload()},!0),$scope.menuOptions=function(area){var options=[];return options.push({html:' '+translationService.translate("web-cleaningTask-areaTable-edit","Rediger rom")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.editArea(area)}}),options.push({html:' '+translationService.translate("web-cleaningTask-areaTable-delete","Slett rom")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.removeArea(area)}}),area.Area.GuidDrawing&&$rootScope.userInfo.enableWebNavigation&&options.push({html:' '+translationService.translate("web-open-drawing","Gå til tegning")+"",click:function($itemScope,$event,modelValue,text,$li){$rootScope.navigation.go("dwg.view",{guid:area.Area.GuidDrawing,theme:"cleaningMaintenance",guidArea:area.GuidArea})}}),options}}angular.module("Plania").directive("cleaningTaskArea",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reloadTables:"=reloadTables"},controller:["$scope","$localStorage","TranslationService","ngTableParams","$stateParams","Repository","ListService","$modal","$rootScope",controller],templateUrl:"app/cleaningTask/views/cleaningTaskArea.html"}})}(),function(){function controller($scope,repository,$stateParams,translationService,enumService,persistentDataService,$rootScope,$location){function handleUndefinedCleaningTask(){$scope.user.guidPerson&&repository.getSingle(repository.apiData.person.url,$scope.user.guidPerson).then(function(result){!result.Data.DoesCleaningTasks&&$rootScope.hasEditAccess(repository.apiData.cleaningTask.prefix)&&swal({title:translationService.translate("web-swal-cleaningTask-undefinedTaskTitle","Renholdstype er ikke definert"),text:translationService.translate("web-swal-cleaningTask-undefinedTaskMessage","Ønsker du å opprette renholdstype for oppgaven?"),type:"info",showCancelButton:!0,confirmButtonColor:"#2196f3",confirmButtonText:translationService.translate("web-swal-cleaningTask-undefinedTask-confirm","Ja, ta meg til oppsett"),cancelButtonText:translationService.translate("web-swal-cleaningTask-undefinedTask-askMeLater","Minn meg på det neste gang"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,persistentDataService.setPersistedData("cleaningTask.create",$scope.model),$scope.navigation.go("cleaningTask.create",{showPersistantData:!0})})})}$scope.model={Guid:$stateParams.guid},$scope.user=repository.authService.getUserData(),$scope.reloadTables=!1,$scope.isUpdate="cleaningTask.edit"===$scope.navigation.current.name;var availableHashLocations=["#info","#area"],updateLocation=function(){var hash=window.location.hash;hash&&availableHashLocations.includes(hash)?$('#cleaningTaskTabs a[data-target="'+hash+'"]').tab("show"):$('#cleaningTaskTabs a[data-target="#info"]').tab("show")};updateLocation(),$scope.$on("$locationChangeSuccess",function(event,newUrl,oldUrl){updateLocation()}),$scope.setTab=function(tab){$location.hash(tab).replace()};var updateAccess=function(){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.CleaningTask,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.CleaningTask,checkOtherDO)};updateAccess(),repository.getSingle(repository.apiData.cleaningTask.url,$stateParams.guid).then(function(response){$scope.reload=!0,$scope.model=response.Data,updateAccess(),"Undefined"===$scope.model.CleaningType&&handleUndefinedCleaningTask()},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var toSave=angular.copy($scope.model);toSave.RecurrenceRule&&toSave.RecurrenceRule.StartDate&&(toSave.RecurrenceRule.StartDate=new Date(toSave.RecurrenceRule.StartDate).toISOString()),toSave.RecurrenceRule&&toSave.RecurrenceRule.Unit&&enumService.setTimeUnitOnRecurrence(toSave.RecurrenceRule);var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-cleaningTask-success","Renholdsoppgaven har blitt oppdatert."):translationService.translate("create-cleaningTask-success","Renholdsoppgaven har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.cleaningTask.url,toSave).then(success,error):repository.createSingle(repository.apiData.cleaningTask.url,toSave).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cleaningTask-message","Renholdsoppgaven vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaningTask-button-confirm","Ja, fjern Renholdsoppgaven"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.cleaningTask.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-cleaningTask-success","Renholdsoppgaven ble fjernet!"),result,"success"),$scope.goBack("cleaningTask.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.$on($scope.events.newSelection,function(){updateAccess(),$scope.reloadTables=!$scope.reloadTables})}angular.module("Plania").controller("CleaningTaskController",["$scope","Repository","$stateParams","TranslationService","EnumService","PersistentDataService","$rootScope","$location",controller])}(),function(){function controller($scope,ngTableParams,repository,translationService,$stateParams,autoCompleteService,listService,$rootScope){function deleteCompletions(guidList){guidList&&0!==guidList.length?swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cleaningtask-completion-message","Fullført renhold vil ikke lenger være tilgjengelig!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaningquality-completion-button-confirm","Ja, fjern fullført renhold"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.cleaningCompletion.url,"","guids="+JSON.stringify(guidList)).then(function(result){swal(translationService.translate("web-swal-completion-cleaningTasks-success","Fullført renhold ble fjernet!"),"","success"),repository.growl("Fullført renhold har blitt fjernet","success"),$scope.selectedCleaningCompletions=[],$scope.cleaningCompletionTable.reload()})}):swal("Ingen valg",translationService.translate("list-mass-edit-missingSelect-completion","Ingen valg. Velg en eller flere rader fra listen for å slette flere fullførte renhold"),"error")}$scope.viewMode=!0,$scope.isDocumentsCollapsed=!1,$scope.isVideosCollapsed=!1,$scope.selectedCleaningCompletions=[],$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasRecurrenceChanged=!1,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.cleaningCompletionColumns=[{Position:1,Title:translationService.translate("web-cleaningCompletion-building","Bygg"),Property:"Area.Building.Caption",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cleaningCompletion-area"),Property:"Area.Caption",PropertyType:"string"},{Position:3,Title:translationService.translate("web-cleaningCompletion-explanatoryText","Kommentar"),Property:"ExplanatoryText",PropertyType:"string"},{Position:3,Title:translationService.translate("web-cleaningCompletion-CompletionStatus","Status"),Property:"CompletionStatus",PropertyType:"enum"},{Position:4,Title:translationService.translate("web-cleaningCompletion-CompletionDate","Utført dato"),Property:"CompletionDate",PropertyType:"date"}];var cleaningCompletionPropertyColumns=["Area.Building.Id","Area.Building.Description","Area.Id","Area.Description","ExplanatoryText","CompletionDate","Area.Guid","Area.Building.Guid","CompletionStatus"];$scope.cleaningCompletionTable=new ngTableParams({page:1,count:10,sorting:{CompletionDate:"desc"},filter:{PropertyFilter:[{Property:"GuidCleaningTask",Operator:"=",Value:$stateParams.guid}]}},{total:0,counts:[10,20,50,200],filterDelay:10,getData:function($defer,params){$scope.loadingCleaningCompletions=!0;var sorting=params.sorting();if(-1!==Object.keys(sorting)[0].indexOf(".Caption")){var key=Object.keys(sorting)[0],order=sorting[key];(key.includes("Area")||key.includes("Area.Building"))&&(key=key.replace(".Caption",".Id")),sorting={},sorting[key]=order}repository.GetPaginated(repository.apiData.cleaningCompletion.url,params.page()-1,params.count(),sorting,params.filter(),"",JSON.stringify(cleaningCompletionPropertyColumns)).then(function(result){$scope.loadingCleaningCompletions=!1,$scope.cleaningCompletionTable.settings().total=result.TotalCount,$scope.cleaningCompletionTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){$scope.loadingCleaningCompletions=!1,repository.growl(error,"danger")})}}),$scope.addSelected=function(key,guid){if(_.contains($scope.selectedCleaningCompletions,guid))for(var i=0;i<$scope.selectedCleaningCompletions.length;i++){var p=$scope.selectedCleaningCompletions[i];if(p===guid)return void $scope.selectedCleaningCompletions.splice(i,1)}else $scope.selectedCleaningCompletions.push(guid)},$scope.isSelected=function(key,guid){return _.contains($scope.selectedCleaningCompletions,guid)},$scope.massDeleteCompletion=function(){deleteCompletions($scope.selectedCleaningCompletions)},$scope.removeCompletion=function(completion){deleteCompletions([completion.Guid])};var recurrenceWatcher=$scope.$watch("model.RecurrenceRule",function(newVal,oldVal){newVal!==oldVal&&void 0!==oldVal&&($scope.hasRecurrenceChanged=!0,recurrenceWatcher())},!0);$scope.onAttributesChanged=function(){repository.getSingle(repository.apiData.cleaningTask.url,$stateParams.guid).then(function(response){$scope.model&&response.Data&&($scope.model.AttributeValues=response.Data.AttributeValues)})}}angular.module("Plania").directive("cleaningTaskInfo",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload"},controller:["$scope","ngTableParams","Repository","TranslationService","$stateParams","AutoCompleteService","ListService","$rootScope",controller],templateUrl:"app/cleaningTask/views/cleaningTaskInfo.html"}})}(),function(){function controller($scope,repository,registeredFieldService,translationService,enumService,$filter,constants,$timeout,persistentDataService,$stateParams,$q){function isFieldSet(field){return void 0!==field&&(null!==field&&""!==field)}function isCleaningTypeWithoutRecurrenceRule(cleaningType){return"AdditionalCleaning"===cleaningType||"InfectionCleaning"===cleaningType||"ExitCleaning"===cleaningType}function confirmRecurrenceRuleDeletion(){var deferred=$q.defer();return swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cleaningTask-wizard-recurrenceRemove","Det eksisterer en gjentakelseregel på oppgaven som ikke er gyldig for valgt renholdstype. Gjentakelseregel vil bli slettet fra oppgaven og tilhørende rom."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaningTask-wizard-recurrenceRemove-confirm","Ja, fjern gjentakelseregel"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,deferred.resolve(isConfirm)}),deferred.promise}if($scope.model={},registeredFieldService.getRegisteredField(repository.commonService.prefix.CleaningTask).then(function(result){$scope.fieldRules=result}),$stateParams.showPersistantData){var persistentData=persistentDataService.getPersistedData("cleaningTask.create");persistentData&&($scope.model=persistentData)}$scope.steps=[{stepNumber:0,name:"chooseType",hidden:!0},{stepNumber:1,name:"basicInfo",title:"Basisinformasjon",hidden:!1}],$scope.currentStep=$scope.steps[0].name,$scope.getCurrentStepNumber=function(){return _.find($scope.steps,{name:$scope.currentStep}).stepNumber},$scope.setCurrentStep=function(step){$scope.currentStep=step},$scope.isStepDisabled=function(step){return _.find($scope.steps,{name:$scope.currentStep}).stepNumber<=step.stepNumber},$scope.isLastStep=function(){return $scope.currentStep===$scope.steps[$scope.steps.length-1].name},$scope.missingMandatoryProperties=[],$scope.hasError=function(field){return!(!$scope.missingMandatoryProperties.includes(field)||isFieldSet($scope.model[field]))||!(!$scope.missingMandatoryProperties.includes(field)||!isFieldSet($scope.model[field]))&&(_.remove($scope.missingMandatoryProperties,function(property){return property===field}),!1)};var basicInformationFields=["Id","EstimatedTime","EstimatedCost","CleaningType","ExplanatoryText","ExitCleaningDecisionDate"],sectionIsValid=function(fields){return $scope.missingMandatoryProperties=[],fields.forEach(function(field){_.find($scope.fieldRules,{DomainFieldName:field,Mandatory:!0})&&!isFieldSet($scope.model[field])&&$scope.missingMandatoryProperties.push(field)}),!($scope.missingMandatoryProperties.length>0)};$scope.handleNextStep=function(){switch($scope.currentStep){case"chooseType":handleCleaningType(),$scope.currentStep="basicInfo";break;case"basicInfo":sectionIsValid(basicInformationFields)&&($scope.isLastStep()?$scope.create():$scope.currentStep="recurrenceRule");break;case"recurrenceRule":$scope.isLastStep()&&$scope.create()}},$scope.handlePreviousStep=function(){$scope.missingMandatoryProperties=[];for(var i=1;i<$scope.steps.length;i++){if($scope.steps[i].name===$scope.currentStep)return void($scope.currentStep=$scope.steps[i-1].name)}},$scope.setCleaningType=function(cleaningType){$scope.model.CleaningType=cleaningType,$scope.model.RecurrenceRule&&isCleaningTypeWithoutRecurrenceRule(cleaningType)?confirmRecurrenceRuleDeletion().then(function(isConfirmed){isConfirmed&&($scope.model.RecurrenceRule=null,$scope.model.Recurrence=null,$scope.handleNextStep())}):$scope.handleNextStep()},$scope.canSetTemplate=function(){return"AdditionalCleaning"===$scope.model.CleaningType||"InfectionCleaning"===$scope.model.CleaningType||"ExitCleaning"===$scope.model.CleaningType};var handleCleaningType=function(){switch($scope.model.CleaningType){case"StandardCleaning":$scope.model.StartDate||($scope.model.StartDate=new Date),$scope.model.RecurrenceRule||($scope.model.RecurrenceRule={StartDate:new Date,Unit:"Day"}),$scope.steps.push({stepNumber:2,name:"recurrenceRule",title:"Gjentakelsesregel",hidden:!1});break;case"ExitCleaning":var date=new Date;date.setHours(12,0,0),$scope.model.ExitCleaningDecisionDate=date;break;case"PeriodicCleaning":$scope.model.StartDate||($scope.model.StartDate=new Date),$scope.model.RecurrenceRule||($scope.model.RecurrenceRule={StartDate:new Date,Unit:"Once",PeriodNumber:1,PeriodUnit:"Day"}),$scope.steps.push({stepNumber:2,name:"recurrenceRule",title:"Gjentakelsesregel",hidden:!1});break;case"InfectionCleaning":case"AdditionalCleaning":$scope.model.RecurrenceRule=null}};$scope.create=function(){if(!$scope.isSaving){$scope.isSaving=!0,$scope.canSetTemplate()||($scope.model.IsTemplate=!1);var toSave=angular.copy($scope.model);toSave.RecurrenceRule&&toSave.RecurrenceRule.StartDate&&(toSave.RecurrenceRule.StartDate=new Date(toSave.RecurrenceRule.StartDate).toISOString()),toSave.RecurrenceRule&&toSave.RecurrenceRule.Until&&(toSave.RecurrenceRule.Until=new Date(toSave.RecurrenceRule.Until).toISOString()),toSave.RecurrenceRule&&toSave.RecurrenceRule.Unit&&enumService.setTimeUnitOnRecurrence(toSave.RecurrenceRule),toSave.ExitCleaningDecisionDate&&(toSave.ExitCleaningDecisionDate=new Date(toSave.ExitCleaningDecisionDate).toISOString()),toSave.NumericFieldName="COMPUTED_NET_AREA";var success=function(result){repository.growl(translationService.translate("create-cleaningTask-success","Renholdsoppgaven har blitt opprettet."),"success");var guid=result.Guid;repository.commonService.setLastRegisterGuid("cleaningTask.edit",guid),$stateParams.showPersistantData&&persistentDataService.clearPersistedData("cleaningTask.create"),$scope.goBack("cleaningTask.edit",{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger"),$scope.isSaving=!1};toSave.Guid?repository.updateSingle(repository.apiData.cleaningTask.url,toSave).then(success,error):repository.createSingle(repository.apiData.cleaningTask.url,toSave).then(success,error)}}}angular.module("Plania").controller("CleaningTaskWizardController",["$scope","Repository","RegisteredFieldService","TranslationService","EnumService","$filter","Constants","$timeout","PersistentDataService","$stateParams","$q",controller])}(),function(){function controller($scope,$modalInstance,modalParams,repository,ngTableParams,translationService,listService,$localStorage,enumService){$scope.modalParams=modalParams,$scope.model={},$scope.showRecurrenceRule=!0,$scope.useAreaClassification=!1;var getUntilDate=function(recurrenceRule,startDate){var untilDate=null;if(recurrenceRule&&recurrenceRule.Until){var objUntilDate=new Date(recurrenceRule.Until);objUntilDate.setHours(0,0,0,0),objUntilDate>startDate&&(untilDate=objUntilDate)}return untilDate},getStartDate=function(recurrenceRule){var startDate=new Date;if(startDate.setHours(0,0,0,0),recurrenceRule&&recurrenceRule.StartDate){var objStartDate=new Date(recurrenceRule.StartDate);objStartDate.setHours(0,0,0,0),objStartDate>startDate&&(startDate=objStartDate)}return startDate};modalParams.cleaningTask&&($scope.isSelectable=!0,$scope.useAreaClassification=$localStorage.generalOptions&&$localStorage.generalOptions.UseAreaClassification,$scope.model.CleaningType=modalParams.cleaningTask.CleaningType,$scope.model.RecurrenceRule=angular.copy(modalParams.cleaningTask.RecurrenceRule),$scope.model.AttributeValues=angular.copy(modalParams.cleaningTask.AttributeValues),$scope.model.StartDate=getStartDate($scope.model.RecurrenceRule),$scope.model.UntilDate=getUntilDate($scope.model.RecurrenceRule,$scope.model.StartDate),$scope.model.AttributeValues.forEach(function(attribute){attribute.TextValue=attribute.NamedSelectionDefaultOption}));var updateTabs=function(){$scope.showRecurrenceRule="PeriodicCleaning"===$scope.model.CleaningType||"StandardCleaning"===$scope.model.CleaningType||"Undefined"===$scope.model.CleaningType&&$scope.model.RecurrenceRule&&$scope.model.RecurrenceRule.ByDay,$scope.showRecurrenceRule?($scope.tabs=[{heading:modalParams.cleaningTask?translationService.translate("web-cleaningtaskwizard-selectarea","Velg Rom"):translationService.translate("web-cleaningtaskwizard-selectCleaningTask","Velg Renholdsoppgave"),step:0},{heading:translationService.translate("web-cleaningtaskwizard-recurrencerule","Gjentakelsesregel"),step:1},{heading:translationService.translate("web-cleaningtaskwizard-extra","Ekstrafelter"),step:2}],$scope.steps=["one","two","three"]):($scope.tabs=[{heading:modalParams.cleaningTask?translationService.translate("web-cleaningtaskwizard-selectarea","Velg Rom"):translationService.translate("web-cleaningtaskwizard-selectCleaningTask","Velg Renholdsoppgave"),step:0},{heading:translationService.translate("web-cleaningtaskwizard-extra","Ekstrafelter"),step:1}],$scope.steps=["one","two"])};updateTabs(),$scope.step=0,$scope.isCurrentStep=function(step){return $scope.step===step},$scope.setCurrentStep=function(step){$(".tab-content").css("overflow","hidden"),setTimeout(function(){$(".tab-content").css("overflow","visible")},500),$scope.step=step},$scope.getCurrentStep=function(){return $scope.steps[$scope.step]},$scope.isLastStep=function(){return $scope.step===$scope.steps.length-1},$scope.getNextLabel=function(){return $scope.isLastStep()?translationService.translate("web-button-save","Lagre"):translationService.translate("web-button-next","Neste")},$scope.handlePrevious=function(){$scope.setCurrentStep($scope.step-(0===$scope.step?0:1))},$scope.handleNext=function(){$scope.isLastStep()?$scope.save():$scope.setCurrentStep($scope.step+=1)},$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.itemTable=new ngTableParams({page:1,count:10,sorting:modalParams.sorting,filter:modalParams.filter},{total:0,counts:[10,50,100],paginationMaxBlocks:8,getData:function($defer,params){var filter=angular.copy(params.filter()),columns=null;modalParams.columns&&(columns=_.map(modalParams.columns,"Property")),columns.push("CleaningType"),modalParams.area&&columns.push("Recurrence"),modalParams.cleaningTask&&(filter.PropertyFilter||(filter.PropertyFilter=[]),void 0!==filter.mainFunction&&""!==filter.mainFunction&&filter.PropertyFilter.push({Property:"MainFunction",Operator:"contains",Value:filter.mainFunction}),void 0!==filter.partFunction&&""!==filter.partFunction&&filter.PropertyFilter.push({Property:"PartFunction",Operator:"contains",Value:filter.partFunction}),void 0!==filter.roomName&&""!==filter.roomName&&filter.PropertyFilter.push({Property:"RoomName",Operator:"contains",Value:filter.roomName}),void 0!==filter.roomSpecification&&""!==filter.roomSpecification&&filter.PropertyFilter.push({Property:"RoomSpecification",Operator:"contains",Value:filter.roomSpecification}),filter.GuidCleaningTask=modalParams.cleaningTask.Guid,modalParams.useCaption&&(columns.push("Building.Description"),columns.push("Description"))),repository.GetPaginated(modalParams.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.selectedItems=[],$scope.save=function(){if(modalParams.useObjects)$modalInstance.close($scope.selectedItems);else{ $scope.model.RecurrenceRule&&$scope.model.RecurrenceRule.Unit&&enumService.setTimeUnitOnRecurrence($scope.model.RecurrenceRule),$scope.model.AttributeValues&&$scope.model.AttributeValues.forEach(function(attribute){"Date"===attribute.ValueType&&attribute.DateValue&&(attribute.DateValue=attribute.DateValue.toISOString())});var resultObject;resultObject=modalParams.area?{cleaningTask:$scope.model.cleaningTask,recurrenceRule:$scope.model.RecurrenceRule,attributeValues:$scope.model.AttributeValues,model:$scope.model}:{selectedGuids:$scope.selectedItems,recurrenceRule:$scope.model.RecurrenceRule,attributeValues:$scope.model.AttributeValues,model:$scope.model},$modalInstance.close(resultObject)}},$scope.addSelectedItem=function(object){if(modalParams.area)$scope.model.cleaningTask=object,$scope.model.CleaningType=object.CleaningType,$scope.model.RecurrenceRule=object.RecurrenceRule,$scope.model.AttributeValues=object.AttributeValues,$scope.model.StartDate=getStartDate(object.RecurrenceRule),$scope.model.UntilDate=getUntilDate(object.RecurrenceRule,$scope.model.StartDate),$scope.model.AttributeValues.forEach(function(attribute){attribute.TextValue=attribute.NamedSelectionDefaultOption}),updateTabs(),$scope.handleNext();else if(_.contains($scope.selectedItems,object.Guid)){for(var i=0;i<$scope.selectedItems.length;i++)if($scope.selectedItems[i]===object.Guid)return void $scope.selectedItems.splice(i,1)}else $scope.selectedItems.push(object.Guid)},$scope.$watch("model.StartDate",function(newVal,oldVal){$scope.model.RecurrenceRule&&($scope.model.RecurrenceRule.StartDate=newVal)}),$scope.$watch("model.UntilDate",function(newVal,oldVal){$scope.model.RecurrenceRule&&($scope.model.RecurrenceRule.Until=newVal)}),$scope.isItemSelected=function(object){return _.contains($scope.selectedItems,object.Guid)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CleaningTaskWizardModalController",["$scope","$modalInstance","modalParams","Repository","ngTableParams","TranslationService","ListService","$localStorage","EnumService",controller])}(),function(){function openModalController($scope,$modal,$window,$localStorage,authService){var vm=this;vm.AllowApiConnections=$localStorage.generalOptions.AllowApiConnections,vm.openModal=function(){$modal.open({controller:"DesktopModalController",templateUrl:"app/common/views/DesktopModal.html"}).result.then(function(result){$window.open("plania://url-"+window.location.origin+"|"+$localStorage.planiaToken.refresh,"_self"),authService.forceRefreshAuthentication()})}}function desktopModalController($scope,$modalInstance,$http,config,$localStorage){$scope.collapseDesktop=$localStorage.CollapseDesktopInstallationGuide,$http({method:"GET",url:encodeURI(config.baseUrl+"Clients/Version.txt")}).then(function(result){$scope.version=result.data,$scope.version.PlaniaLauncherDownloadURL="/"+result.data.PlaniaLauncherDownloadURL}),$scope.openDesktop=function(){$localStorage.CollapseDesktopInstallationGuide=!0,$modalInstance.close("open")},$scope.cancel=function(){$modalInstance.dismiss("cancel")}}angular.module("Plania").controller("DesktopModalOpenController",["$scope","$modal","$window","$localStorage","authService",openModalController]),angular.module("Plania").controller("DesktopModalController",["$scope","$modalInstance","$http","config","$localStorage",desktopModalController])}(),function(){function controller($scope,$modalInstance,params,repository,translationService){var locale=translationService.getLocale(),prefix=params.prefix;prefix===repository.apiData.userGroup.prefix&&(prefix=repository.apiData.user.prefix),$scope.showAdvancedMode=params.showAdvancedMode,prefix&&repository.getWithUrlParameter(repository.apiData.webColumns.url,"domainModel="+prefix+"&locale="+locale).then(function(result){var resultCopy=angular.copy(result),guidProperties=angular.copy(_.filter(resultCopy,function(col){return col.GuidProperty}));guidProperties.forEach(function(col){col.IsExpandable=!1,col.Title=col.GuidProperty,col.isAdvanced=!0,col.Property=col.GuidProperty,col.PropertyType="string"}),$scope.model=resultCopy.concat(guidProperties)}),$scope.getNextLevel=function(column){repository.getWithUrlParameter(repository.apiData.webColumns.url,"domainModel="+column.PropertyType+"&locale="+locale).then(function(result){var resultCopy=angular.copy(result),guidProperties=angular.copy(_.filter(resultCopy,function(col){return col.GuidProperty}));column.Properties=[],result.forEach(function(childColumn){childColumn.Property=column.Property+"."+childColumn.Property,column.Properties.push(childColumn)}),guidProperties.forEach(function(childColumn){childColumn.Property=column.Property+"."+childColumn.GuidProperty,childColumn.IsExpandable=!1,childColumn.Title=childColumn.GuidProperty,childColumn.PropertyType="string",childColumn.isAdvanced=!0,column.Properties.push(childColumn)})})},$scope.selectedColumns=[],$scope.ok=function(){$modalInstance.close($scope.selectedColumns)};var match=function(textToSearch,searchValue){return!searchValue||!!textToSearch&&textToSearch.toLowerCase().includes(searchValue.toLowerCase())},searchMatch=function(col,searchString){return $scope.showPropertyNames?match(col.Title,searchString)||match(col.Property,searchString):match(col.Title,searchString)},hideExpandableColumns=params.hideExpandableColumns,alreadyExist=function(column){return!(!hideExpandableColumns||!column.IsExpandable)||_.filter(params.existingColumns,{Property:column.Property}).length>0};$scope.columnFilter=function(col){return!alreadyExist(col)&&(!!searchMatch(col,$scope.searchString)&&$scope.identityColumnsFilter(col))},$scope.identityColumnsFilter=function(col){return!!$scope.showIdentityColumns||!col.isAdvanced},$scope.selectColumn=function(column,event){if(event.stopPropagation(),column.IsExpandable)column.isExpanded=!column.isExpanded,column.isExpanded&&column.Properties&&0===column.Properties.length&&$scope.getNextLevel(column);else if(_.contains($scope.selectedColumns,column))for(var i=0;i<$scope.selectedColumns.length;i++){var p=$scope.selectedColumns[i];if(p===column)return void $scope.selectedColumns.splice(i,1)}else $scope.selectedColumns.push(column)},$scope.isColumnSelected=function(column){return _.contains($scope.selectedColumns,column)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("AddNewListColumnController",["$scope","$modalInstance","params","Repository","TranslationService",controller])}(),function(){function controller(scope,repository,params,modalInstance,modal,translationService){scope.isUpdate=params.isUpdate,scope.model={},scope.model[params.guidColumn]=params.guid,scope.model.EntityAttribute={},scope.model.IndexPosition=params.indexPosition,scope.valueTypes=[{value:"Text",label:translationService.translate("web-enum-FieldType-Text","Tekst")},{value:"Numeric",label:translationService.translate("web-enum-FieldType-Numeric","Tall")},{value:"Date",label:translationService.translate("web-enum-FieldType-Date","Dato")},{value:"Combo",label:translationService.translate("web-enum-FieldType-Combo","Nedtrekksliste")},{value:"CheckBox",label:translationService.translate("web-enum-FieldType-CheckBox","Sjekkboks")}],scope.model.EntityAttribute.ValueType=scope.valueTypes[0].value;var saveEntityXAttribute=function(){delete scope.model.EntityAttribute,repository.createSingle(repository.apiData.entityXAttribute.url,scope.model).then(function(result){modalInstance.close()})};scope.selectExistingEntityAttribute=function(){modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"md",resolve:{modalParams:function(){return{title:translationService.translate("web-addExistingEntityAttribute","Legg til eksisterende attributt"),url:repository.apiData.entityAttribute.url,sorting:{},filter:{},columns:[{title:"Id",property:"Id"},{title:"Felttype",property:"ValueType",PropertyType:"enum.FieldType"}]}}}}).result.then(function(item){scope.model.EntityAttribute.Id=item.Id,scope.model.GuidEntityAttribute=item.Guid;var newValueType=_.find(scope.valueTypes,function(type){return type.value===item.ValueTypeName});scope.model.EntityAttribute.ValueType=newValueType.value},function(msg){})},scope.selectNamedSelection=function(){modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"md",resolve:{modalParams:function(){return{url:repository.apiData.namedSelection.url,sorting:{},title:"Nedtrekksfelt",filter:{FilterModel:{Condition:"and",Rules:[{Property:"EntityType",Operator:"=",Value:"CleaningTask"}]}},columns:[{title:"Nedtrekksfelt",property:"Value"}]}}}}).result.then(function(item){scope.model.EntityAttribute.GuidNamedSelection=item.Guid,scope.model.EntityAttribute.NamedSelection=item},function(msg){})},scope.save=function(){scope.model.ValidityRules=scope.model.IsMandatory?1:0,"Combo"!==scope.model.EntityAttribute.ValueType&&delete scope.model.EntityAttribute.GuidNamedSelection,scope.model.GuidEntityAttribute?saveEntityXAttribute():(delete scope.model.EntityAttribute.NamedSelection,repository.createSingle(repository.apiData.entityAttribute.url,scope.model.EntityAttribute).then(function(result){scope.model.GuidEntityAttribute=result.Guid,saveEntityXAttribute()}))},scope.cancel=function(){modalInstance.dismiss("canceled")}}angular.module("Plania").controller("AttributeModalController",["$scope","Repository","params","$modalInstance","$modal","TranslationService",controller])}(),function(){function controller($scope,$modalInstance,confirmation){$scope.header=confirmation.header,$scope.message=confirmation.message,$scope.ok=function(){$modalInstance.close()},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("ConfirmationBoxController",["$scope","$modalInstance","confirmation",controller])}(),function(){angular.module("Plania").constant("Constants",{inspectedEntityLocation:{anywhere:0,estate:1,building:2},requestStatus:{new:"New"},priorityLevel:{Low:"Low",Normal:"Normal",High:"High",Critical:"Critical"},elhubStatus:{undefined:"Undefined",noExport:"NoExport",startedInPlania:"StartedInPlania",syncPendingStartConfirmation:"SyncPendingStartConfirmation",syncApproved:"SyncApproved",syncDenied:"SyncDenied",stoppedInPlania:"StoppedInPlania",syncPendingStopConfirmation:"SyncPendingStopConfirmation",syncStopped:"SyncStopped",failed:"Failed"},dateOptions:{"starting-day":1},availableMaps:[{title:"OpenStreetMap",mapData:{TileLayer:"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",TileLayerOptions:JSON.stringify({maxZoom:"19",attribution:"© OpenStreetMap"}),CrsCode:"",Proj4Def:"",Options:{Origin:JSON.stringify(""),Resolution:JSON.stringify("")}}},{title:"NVDB",mapData:{TileLayer:"http://m{s}.nvdbcache.geodataonline.no/arcgis/rest/services/Trafikkportalen/GeocacheTrafikkJPG/MapServer/tile/{z}/{y}/{x}",TileLayerOptions:JSON.stringify({maxZoom:"16",minZoom:"3",subdomains:"123456789",continuousWorld:"true",attribution:"NVDB"}),CrsCode:"EPSG:25833",Proj4Def:"+proj=utm +zone=33 +ellps=GRS80 +units=m +no_defs ",Options:{Origin:JSON.stringify([-25e5,9045984]),Resolution:JSON.stringify([21674.7100160867,10837.35500804335,5418.677504021675,2709.3387520108377,1354.6693760054188,677.3346880027094,338.6673440013547,169.33367200067735,84.66683600033868,42.33341800016934,21.16670900008467,10.583354500042335,5.291677250021167,2.6458386250105836,1.3229193125052918,.6614596562526459,.33072982812632296])}}}],dynamicProperties:{projectCategory:{text:40,date:30,numeric:40,combo:30,max:20}},weekdaysToNumber:{Monday:0,Tuesday:1,Wednesday:2,Thursday:3,Friday:4,Saturday:5,Sunday:6},numberToWeekdays:{0:"Monday",1:"Tuesday",2:"Wednesday",3:"Thursday",4:"Friday",5:"Saturday",6:"Sunday"},months:[{name:"Januar",id:1},{name:"Februar",id:2},{name:"Mars",id:3},{name:"April",id:4},{name:"Mai",id:5},{name:"Juni",id:6},{name:"Juli",id:7},{name:"August",id:8},{name:"September",id:9},{name:"Oktober",id:10},{name:"November",id:11},{name:"Desember",id:12}],defaultSmsConfiguration:{ServicePlanId:"",AccessToken:"",Url:"https://eu.sms.api.sinch.com/xms/v1",SenderId:"Plania",TemplateText:"Din kode for innlogging i Plania er: "},defaultAnonymizationConfiguration:{AnonymizationIntervalInMonths:3,DeletionIntervalInMonths:3,FieldRules:[{FieldName:"[CUSTOMER.DESCRIPTION]",Action:"Remove"},{FieldName:"[CUSTOMER.POSTAL_ADDRESS]",Action:"Remove"}]},defaultAnonymizationConfigurationIntervals:[{label:"1 måned",months:1},{label:"3 måneder",months:3},{label:"6 måneder",months:6},{label:"1 år",months:12},{label:"3 år",months:36},{label:"5 år",months:60},{label:"10 år",months:120}],defaultLikertScaleColors:{0:"#9E9E9E",1:"#2E7D32",2:"#4caf50",3:"#C8E6C9",4:"#FF8F00",5:"#FFC400",6:"#FFECB3",7:"#D84315",8:"#FF3D00",9:"#FFCCBC"},ka:{guidLocalAdminUserGroup:"03f60c1f-99cc-439b-83b1-c6e8739a81a8",guidFdvUserGroup:"03f2fbb7-ed49-4489-9f71-cecbc5807e22",guidInventoryUserGroup:"03ff9d83-9508-42d4-a988-1bb16e2dc843",guidStandardEntityPermissionProfile:"040fdf48-9f74-5d4c-4911-ee998965e191",guidExternalOperatorEntityPermissionProfile:"0408553a-b38f-65e2-dbf5-7ef48a4abe89"}})}(),function(){function controller(scope,repository,modal,translationService){scope.datePickers={},scope.dateOptions={"starting-day":1},scope.open=function($event,calendar){scope.datePickers[calendar]=!scope.datePickers[calendar],$event.preventDefault(),$event.stopPropagation()},scope.model={};var columns=["EntityAttribute.Id","EntityAttribute.ValueType","IndexPosition","ValidityRules"],getAttributes=function(){if(scope.guid){var filter={PropertyFilter:[{Property:scope.guidColumn,Operator:"=",Value:scope.guid}]};repository.GetPaginated(repository.apiData.entityXAttribute.url,0,500,{IndexPosition:"asc"},filter,"",JSON.stringify(columns)).then(function(result){scope.model=result.List,scope.onAttributesChanged&&scope.onAttributesChanged()}).catch(function(error){repository.showError(error)})}};getAttributes(),scope.removeAttribute=function(item){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-entityXAttribute-message","Attributtet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-entityXAttribute-button-confirm","Ja, fjern attributtet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.entityXAttribute.url,item.Guid).then(function(result){getAttributes(),swal(translationService.translate("web-swal-entityXAttribute-success","Attributtet ble fjernet!"),result,"success"),repository.growl("Attributtet har blitt fjernet","success")})})};var getNewIndexPosition=function(){return scope.model&&scope.model.length?_.max(scope.model,function(item){return item.IndexPosition}).IndexPosition+1:0};scope.addAttribute=function(){scope.isCollapsed=!1,modal.open({templateUrl:"app/common/views/attributeModal.html",controller:"AttributeModalController",size:"md",resolve:{params:function(){return{isUpdate:!1,guid:scope.guid,guidColumn:scope.guidColumn,indexPosition:getNewIndexPosition()}}}}).result.then(function(){getAttributes(),scope.isCollapsed=!1},function(msg){scope.isCollapsed=!1})},scope.isMandatory=function(item){return"Mandatory"===item.ValidityRules},scope.treeOptions={dropped:function(event){for(var draggedDown=event.source.index>event.dest.index,startIndex=draggedDown?event.dest.index:event.source.index,endIndex=draggedDown?event.source.index:event.dest.index,i=startIndex;i<=endIndex;i++){var item=scope.model[i];item.IndexPosition=i,repository.updateSingle(repository.apiData.entityXAttribute.url,item)}}},scope.extra={},scope.save=function(destination){"function"==typeof scope.saveFunction&&scope.saveFunction(scope.destinationObject+"."+destination)},scope.reload=!0}angular.module("Plania").directive("entityAttribute",function(){return{restrict:"E",scope:{guid:"=guid",guidColumn:"=guidColumn",isCollapsed:"=isCollapsed",onAttributesChanged:"&onAttributesChanged"},controller:["$scope","Repository","$modal","TranslationService",controller],templateUrl:"app/common/directives/views/entityAttribute.html"}})}(),function(){angular.module("Plania").directive("plTranslate",["TranslationService","$animate","$modal",function(translationService,$animate,$modal){return{restrict:"A",scope:{model:"=plTranslateModel",disableTranslation:"=disableTranslation"},link:function(scope,element,attrs){function getTextContent(input){return input.replace(new RegExp(/%[a-zA-Z0-9\.]*%/g),"")}function appendHelpTextIcon(){$(element).append(function(){return $('').click(showHelpText).css("cursor","help").css("margin-left","5px")})}var systemName=attrs.plTranslate,defaultValue=attrs.plDefaultTranslation?attrs.plDefaultTranslation:element[0].textContent.trim(),value=translationService.translate(systemName,defaultValue,scope.model),hasHelpText=translationService.hasHelpText(systemName),matches=value.match(/%[a-zA-Z0-9\.]*%/g),showHelpText=function(event){event.stopPropagation(),event.preventDefault(),$modal.open({templateUrl:"app/translation/views/helpTextModal.html",controller:"HelpTextModalController",size:"m",resolve:{params:function(){return{systemName:systemName,translatedLabel:value}}}})};matches&&matches.forEach(function(match){var property=match.replace(new RegExp("%","g"),""),properties=property.split("."),tmpModel=scope.model?scope.model[property]:null;tmpModel&&(properties.forEach(function(prop){tmpModel=tmpModel[prop]}),value=value.replace(new RegExp(match,"g"),tmpModel)),scope.$watch("model."+property,function(newValue,oldValue){newValue!==oldValue&&(value=value.replace(new RegExp(match,"g"),newValue),element[0].textContent=getTextContent(value))})}),element[0].textContent=getTextContent(value),hasHelpText&&appendHelpTextIcon();var openTranslation=function(e){e.preventDefault(),e.stopPropagation(),scope.$root.translationMode=!1,$modal.open({templateUrl:"app/translation/views/translationModal.html",controller:"TranslationModalController",size:"lg",resolve:{params:function(){return{systemName:systemName}}}}).result.then(function(result){scope.$root.translationMode=!0;var locale=translationService.getLocale();if(result.translationUpdated||result.helpTextUpdated){var languageXWebText=_.find(result.model.LanguageXWebTexts,function(o){return o.Language.Locale===locale});languageXWebText&&(value=result.translationUpdated?languageXWebText.TranslatedValue?languageXWebText.TranslatedValue:languageXWebText.DefaultTranslatedValue:value,element[0].textContent=value?getTextContent(value):null,languageXWebText.HasHelpText&&appendHelpTextIcon(),translationService.deleteLanguageEntry(languageXWebText.Language.Locale+systemName),translationService.getTranslations())}},function(){scope.$root.translationMode=!0})};scope.disableTranslation||scope.$watch("$root.translationMode",function(newValue,oldValue){newValue?($animate.addClass(element,"translation-mode"),$(element).bind("click",openTranslation)):($animate.removeClass(element,"translation-mode"),$(element).unbind("click",openTranslation))})}}}])}(),function(){function controller($scope,ngTableParams,repository,translationService){$scope.alarmLogsIsLoading=!0,$scope.showAlarmLog=!1,$scope.search={focus:!1},$scope.$watch("reload",function(newValue,oldValue){if(newValue===oldValue)return void(!0===newValue&&($scope.reload=!1));$scope.reload&&($scope.alarmLogTable.reload(),$scope.reload=!1)}),$scope.useList=!0,$scope.alarmLogTable=new ngTableParams({page:1,count:5,sorting:{CreationDate:"desc"},filter:{}},{total:0,counts:[5,10,20],filterDelay:50,paginationMaxBlocks:6,getData:function($defer,params){if($scope.guid){$scope.alarmLogsIsLoading=!0,$scope.activateProjectFilter?(params.filter().GuidProject=$scope.guid,params.filter().ChildEmailsOnProject=[],$scope.showProjectEmails&¶ms.filter().ChildEmailsOnProject.push(repository.commonService.prefix.Project),$scope.showWorkOrderEmails&¶ms.filter().ChildEmailsOnProject.push(repository.commonService.prefix.WorkOrder),$scope.showPurchaseOrderEmails&¶ms.filter().ChildEmailsOnProject.push(repository.commonService.prefix.PurchaseOrder),params.filter().PropertyFilter=[{Property:"Alarm.Action",Operator:"<>",Value:"1"}]):params.filter().PropertyFilter=[{Property:"GuidEntity",Operator:"=",Value:$scope.guid},{Property:"Alarm.Action",Operator:"<>",Value:"1"}];var columns=["EmailTo","EmailCopyTo","EmailSubject","Status","CreationDate","EmailBody"];repository.GetPaginated(repository.apiData.alarmLog.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){if(null!==result){for($scope.alarmLogTable.settings().total=result.TotalCount,$scope.alarmLogTable.settings().filterDelay=500,$scope.alarmLogs||($scope.alarmLogs=[]);$scope.alarmLogs.length>0;)$scope.alarmLogs.pop();result.List.forEach(function(alarmLog){$scope.alarmLogs.push(alarmLog)}),$defer.resolve(result.List),$scope.alarmLogsIsLoading=!1,$scope.showAlarmLog=result.List.length>0||!!params.filter().searchString||!!$scope.activateProjectFilter}},function(error){repository.growl(error,"danger")})}}}),$scope.showProjectEmails=!0,$scope.showWorkOrderEmails=!0,$scope.showPurchaseOrderEmails=!0;var setFiltername=function(){var activeFilters=[];$scope.showProjectEmails&&activeFilters.push(translationService.translate("web-enum-prefix-project","Prosjekt")),$scope.showWorkOrderEmails&&activeFilters.push(translationService.translate("web-enum-prefix-workorder","Arbeidsordre")),$scope.showPurchaseOrderEmails&&activeFilters.push(translationService.translate("web-enum-prefix-purchaseorder","Bestilling")),$scope.selectedFilterName=activeFilters.join(", ")};setFiltername(),$scope.SetChildOptions=function(option){switch(option){case"Project":$scope.showProjectEmails=!$scope.showProjectEmails;break;case"WorkOrder":$scope.showWorkOrderEmails=!$scope.showWorkOrderEmails;break;case"PurchaseOrder":$scope.showPurchaseOrderEmails=!$scope.showPurchaseOrderEmails}setFiltername(),$scope.alarmLogTable.reload()},$scope.getStatusIcon=function(status){switch(status){case"Outbox":return"fa-inbox c-blue";case"Sent":return"fa-paper-plane-top c-green";default:return"fa-circle-x c-red"}}}angular.module("Plania").directive("alarmLog",function(){return{restrict:"E",scope:{reload:"=reload",alarmLogs:"=alarmLogs",guid:"=guid",activateProjectFilter:"=activateProjectFilter"},controller:["$scope","ngTableParams","Repository","TranslationService",controller],link:function(scope,element,attrs){},templateUrl:"app/common/directives/views/alarmLogDirective.html"}})}(),function(){function controller($scope,$modal,repository,translationService,$rootScope){$scope.renderSelf=!1,$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasEditAccess=$rootScope.hasEditAccess;var getGuidBuilding=function(){return $scope.entity?$scope.entity.GuidBuilding:null},hasBuildingBimModel=function(){if(getGuidBuilding()){var filter={PropertyFilter:[{Property:"GuidBuilding",Operator:"=",Value:getGuidBuilding()},{Property:"BimFile.ProcessingStatus",Operator:"=",Value:3}]};repository.GetPaginated(repository.apiData.buildingXBimFile.url,0,1,{},filter,null,JSON.stringify(["Id"])).then(function(result){$scope.renderSelf=!!result.TotalCount},function(){})}},loadIfcProductData=function(){if($scope.entity.GuidIfc){var url=repository.apiData.planiaBim.url;url+="building/"+getGuidBuilding(),url+="/products/"+$scope.entity.GuidIfc,repository.getWithUrlParameter(url).then(function(result){if(result&&result.attributes){var longName=result.attributes.LongName,name=result.attributes.Name;longName&&name&&($scope.productName=[longName.value,name.value].filter(function(x){return!!x}).join(" - "))}},function(error){repository.growl(error,"danger")})}};hasBuildingBimModel(),loadIfcProductData();var reloadWatcher=$scope.$watch("reload",function(newValue){newValue&&(hasBuildingBimModel(),loadIfcProductData(),reloadWatcher())});$scope.openEdit=function(){$modal.open({templateUrl:"app/common/modal/views/bimConnectionEditModal.html",controller:"BimConnectionEditModalController",resolve:{params:function(){return{guidIfc:$scope.entity.GuidIfc,prefix:$scope.prefix,guid:$scope.guid,guidBuilding:getGuidBuilding()}}}}).result.then(function(guidIfc){$scope.entity.GuidIfc=guidIfc,loadIfcProductData()})}}angular.module("Plania").directive("bimConnectionDirective",function(){return{restrict:"E",scope:{guid:"=guid",entity:"=entity",prefix:"=prefix",reload:"=reload"},controller:["$scope","$modal","Repository","TranslationService","$rootScope",controller],link:function(scope,element,attrs){},templateUrl:"app/common/directives/views/bimConnectionDirective.html"}})}(),angular.module("Plania").directive("calendarWidget",function($compile,Repository,$timeout,TranslationService,$rootScope){return{restrict:"A",scope:{select:"&",control:"=",edit:"=",eventSource:"=",viewType:"=",editFunction:"=",removeFunction:"=",excludeResourceGroup:"=",excludeCompletedWorkOrders:"=",excludePeriodicTasks:"="},link:function(scope,element){scope.internalControl=scope.control||{};var toolbarHeight=76,calendarHeight=360;scope.actionLinks='";var setHeight=function(height){calendarHeight=height,element.fullCalendar("option","height",calendarHeight),element.fullCalendar("option","contentHeight",calendarHeight-toolbarHeight)},language=TranslationService.getLocale();language&&"nb-no"!==language||(language="nb");var toDate=function(date){return new Date(date.toDateString())},today=toDate(new Date);element.fullCalendar({popoverIgnoreWindowScroll:!0,theme:!0,defaultView:scope.viewType,eventLimit:!0,header:{right:"",center:"prev, title, next",left:""},defaultDate:new Date,editable:!1,lang:language,viewRender:function(view,element){setHeight(calendarHeight)},events:function(start,end,timezone,callback){element.find(".fc-prev-button").css("color","");var endDate=new Date(end);endDate.setDate(endDate.getDate()-1);var guidPerson=$rootScope.userInfo.guidPerson,guidPersonResourceGroup=$rootScope.userInfo.guidPersonResourceGroup;if(guidPerson||guidPersonResourceGroup){var workOrderFilter=Repository.getFilter({StartDate:new Date(start).toISOString(),EndDate:endDate.toISOString(),GuidPerson:guidPerson,GuidResourceGroup:guidPersonResourceGroup,ExcludeResource:scope.excludeResourceGroup,ExcludeCompletedWorkOrders:scope.excludeCompletedWorkOrders,ExcludePeriodicTasks:scope.excludePeriodicTasks});Repository.getWithUrlParameter(Repository.apiData.maintenance.endpoint.calendar,"",workOrderFilter).then(function(response){var result=response.Data;result.HasWorkOrdersOnOlderPage&&element.find(".fc-prev-button").css("color","#f44336"),callback(result.Items.map(function(item){var eventColor="wo-active";if(item.IsCompleted||item.IsHistoric)eventColor="wo-completed";else if(item.IsOverdue)eventColor="wo-overdue";else if(item.IsPlanned)eventColor="wo-planned";else{var startDate=item.StartDate?toDate(new Date(item.StartDate)):null,dueDate=item.DueDate?toDate(new Date(item.DueDate)):null;(startDate&&startDate>today||!startDate&&dueDate&&dueDate>today)&&(eventColor="wo-default")}var itemEndDate;if(item.DueDate){var date=new Date(item.DueDate);date.setDate(date.getDate()+1),itemEndDate=date}var title="",titleLabel="";return item.Building&&!Repository.commonService.getFilterData().selectedBuilding.Guid?(title=item.Building.Id+" - "+item.Description,titleLabel=TranslationService.translate("web-calendar-building","Bygg:")):!item.Estate||Repository.commonService.getFilterData().selectedBuilding.Guid||Repository.commonService.getFilterData().selectedEstate.Guid||(title=item.Estate.Id+" - "+item.Description,titleLabel=TranslationService.translate("web-calendar-estate","Eiendom:")),title||(title=item.Description,titleLabel=item.IsPlanned?TranslationService.translate("web-calendar-periodicTask","Periodisk:"):TranslationService.translate("web-calendar-workOrder","AO:")),{id:item.Guid,title:title,titleLabel:titleLabel,start:item.StartDate,end:itemEndDate,allDay:!0,className:eventColor,data:item}}))},function(error){Repository.showError(error)})}},eventRender:function(event,element){var content="
    "+event.data.Description+"
    ";if(event.data.Building&&!Repository.commonService.getFilterData().selectedBuilding.Guid?content=content+'
    '+TranslationService.translate("web-calendar-building","Bygg:")+" "+event.data.Building.Caption+"
    ":!event.data.Estate||Repository.commonService.getFilterData().selectedBuilding.Guid||Repository.commonService.getFilterData().selectedEstate.Guid||(content=content+'
    '+TranslationService.translate("web-calendar-estate","Eiendom:")+" "+event.data.Estate.Caption+"
    "),event.data.Area&&(content=content+'
    '+TranslationService.translate("web-calendar-area","Areal:")+" "+event.data.Area.Caption+"
    "),event.data.Equipment&&(content=content+'
    '+TranslationService.translate("web-calendar-equipment","Anlegg:")+" "+event.data.Equipment.Caption+"
    "),event.data.Customer&&(content=content+'
    '+TranslationService.translate("web-calendar-customer","Kunde:")+" "+event.data.Customer.Description+"
    "),event.data.ResourceGroup&&(content=content+'
    '+TranslationService.translate("web-calendar-resourceGroup","Ressurs:")+" "+event.data.ResourceGroup.Caption+"
    "),event.data.ResponsiblePerson&&(content=content+'
    '+TranslationService.translate("web-calendar-responsiblePerson","Ansvarlig:")+" "+event.data.ResponsiblePerson.Caption+"
    "),event.data.EstimatedTime&&(content=content+'
    '+TranslationService.translate("web-calendar-estimatedTime","Estimert tid:")+" "+event.data.EstimatedTime+"
    "),event.data.StartDate){var startDate=new Date(event.data.StartDate),formattedStartDate=("0"+startDate.getDate()).slice(-2)+"."+("0"+(startDate.getMonth()+1)).slice(-2)+"."+startDate.getFullYear();content=content+'
    '+TranslationService.translate("web-calendar-startDate","Startdato:")+" "+formattedStartDate+"
    "}if(event.data.DueDate){var dueDate=new Date(event.data.DueDate),formattedDueDate=("0"+dueDate.getDate()).slice(-2)+"."+("0"+(dueDate.getMonth()+1)).slice(-2)+"."+dueDate.getFullYear();content=content+'
    '+TranslationService.translate("web-calendar-dueDate","Antatt sluttdato:")+" "+formattedDueDate+"
    "}if(event.data.EndDate){var endDate=new Date(event.data.EndDate),formattedEndDate=("0"+endDate.getDate()).slice(-2)+"."+("0"+(endDate.getMonth()+1)).slice(-2)+"."+endDate.getFullYear();content=content+'
    '+TranslationService.translate("web-calendar-endDate","Ferdigdato:")+" "+formattedEndDate+"
    "}$(element).popover({placement:"top",trigger:"mouseenter",container:"body",html:!0,title:"
    "+TranslationService.translate("web-calendar-id","Id:")+" "+event.data.Id+"
    ",content:content})},eventMouseover:function(event,jsEvent,view){$(this).popover("show")},eventMouseout:function(event,jsEvent,view){$(this).popover("hide")},eventClick:function(event,jsEvent,view){$(this).popover("hide");var state=event.data.IsPlanned?"periodicTask.edit":"workOrder.edit";scope.$root.navigation.go(state,{ guid:event.data.Guid})}}),scope.internalControl.resizeCalendar=function(height){setHeight(height)},scope.$watch("viewType",function(newValue,oldValue){newValue!==oldValue&&element.fullCalendar("changeView",scope.viewType)}),scope.$on($rootScope.events.newSelection,function(){element.fullCalendar("refetchEvents")}),element.find(".fc-toolbar").append($compile(scope.actionLinks)(scope))}}}).directive("calendarView",function(){return{restrict:"A",link:function(scope,element,attrs){element.on("click",function(){$("#calendar-widget").fullCalendar("changeView",attrs.calendarView)})}}}),function(){function controller(scope,repository,translationService,ngTableParams,listService,$rootScope){scope.model={},scope.titleSystemName="web-childEntities-"+scope.entity+"-title",scope.titleDefaultName=translationService.translate("web-"+scope.entity,scope.entity).replace(":",""),scope.search={},scope.collapse={isEntitiesCollapsed:!1},scope.hasCreatePermission=repository.authService.hasCreateAccess(scope.entity),scope.translatedEntity=translationService.translate("web-"+scope.entity,scope.entity).toLowerCase();var filter={searchString:""};scope.totalCount={total:0},scope.bools={showTreeView:!1},"Equipment"===scope.entity&&(scope.bools.showTreeView=!0);var apiData=_.find(repository.apiData,function(o){return o.prefix===scope.entity});scope.columns||(scope.columns=[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}]);var sorting={};scope.sortDirection||"asc"===scope.sortDirection&&"desc"===scope.sortDirection||(scope.sortDirection="asc"),scope.sortColumn?sorting[scope.sortColumn]=scope.sortDirection:sorting={Id:scope.sortDirection},scope.getPropertyValue=function(column,row){return listService.GetPropertyValue(column,row)},scope.goToEdit=function(entity,event){scope.onClick?scope.onClick(entity,event):scope.$root.go(apiData.navigationState,{guid:entity.Guid},event)},scope.createNewEntity=function(){if(scope.createEntity&&"function"==typeof scope.createEntity)scope.createEntity();else{var persistedData={};persistedData[scope.guidColumn]=scope.parent.Guid,persistedData[scope.guidColumn.replace("Guid","")]=scope.parent.Id+" - "+scope.parent.Description,scope.parent.Building&&scope.parent.GuidBuilding&&(persistedData.GuidBuilding=scope.parent.GuidBuilding,persistedData.Building=scope.parent.Building.Id+" - "+scope.parent.Building.Description),repository.persistedData.setPersistedData(scope.entity.toLowerCase()+".create",persistedData),scope.$parent.navigation.go(apiData.navigationState.replace(".edit",".create"),{showPersistantData:!0},{reload:!0})}},scope.addExistingEntity=function(){scope.addEntity&&"function"==typeof scope.addEntity&&scope.addEntity(scope.entityTable.data)},filter.PropertyFilter=[{Property:scope.guidColumn,Operator:"=",Value:scope.parent.Guid}],scope.entity===repository.commonService.prefix.WorkOrder&&(filter.ActivityStatus="Undefined"),scope.entityTable=new ngTableParams({page:1,count:10,sorting:sorting,filter:filter},{total:0,counts:[10,20,50],filterDelay:50,paginationMaxBlocks:6,getData:function($defer,params){var filter=params.filter();if("function"==typeof scope.applyFilter){var modified=scope.applyFilter(angular.copy(filter));modified&&(filter=modified)}scope.entitiesAreLoading=!0;var columns=[];scope.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(apiData.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){scope.entityTable.settings().total=result.TotalCount,scope.entityTable.settings().filterDelay=500,scope.totalCount=result.TotalCount,scope.entities||(scope.entities=[]),$defer.resolve(result.List),scope.entitiesAreLoading=!1},function(error){repository.growl(error,"danger")})}}),scope.entity===repository.commonService.prefix.WorkOrder&&(scope.showFilterDropdown=!0,scope.filterTypes=[{value:"-1",name:translationService.translate("web-workorder-filterType-all","Alle")},{value:"0",name:translationService.translate("web-workorder-filterType-project","Prosjekt")},{value:"1",name:translationService.translate("web-workorder-filterType-open","Aktive")},{value:"2",name:translationService.translate("web-workorder-filterType-closed","Historiske")}],scope.setFilter=function(filter){scope.selectedFilter=filter;var propertyFilter=scope.entityTable.filter().PropertyFilter;propertyFilter?_.remove(propertyFilter,function(obj){return"Stage"===obj.Property}):propertyFilter=[],filter.value>=0&&propertyFilter.push({Property:"Stage",Operator:"=",Value:filter.value}),scope.entityTable.filter().PropertyFilter=propertyFilter},scope.setFilter(["GuidEstate","GuidBuilding","GuidEquipment","GuidArea","GuidCustomer"].includes(scope.guidColumn)?scope.filterTypes[2]:scope.filterTypes[0]));var getMenuLink=function(url,icon,text){return{html:' '+text+"",isHref:!0}};scope.childContextMenuOptions=function(entity){var options=[];return scope.contextMenuOptions?scope.contextMenuOptions(entity):(options.push(getMenuLink($rootScope.navigation.href(apiData.navigationState,{guid:entity.Guid}),"fa-eye",translationService.translate("web-childEntities-contextMenu-open","Åpne"))),options)},scope.$watch("reloadTable",function(newVal,oldVal){newVal!==oldVal&&scope.entityTable.reload()})}angular.module("Plania").directive("childEntities",function(){return{restrict:"E",scope:{parent:"=parent",guidColumn:"=guidColumn",entity:"=entity",columns:"=columns",sortColumn:"=sortColumn",sortDirection:"=sortDirection",onClick:"=onClick",createEntity:"=createEntity",disableAdd:"=disableAdd",totalCount:"=totalCount",addEntity:"=addEntity",reloadTable:"=reloadTable",useContextMenu:"=useContextMenu",contextMenuOptions:"=contextMenuOptions",applyFilter:"=applyFilter"},controller:["$scope","Repository","TranslationService","NgTableParams","ListService","$rootScope",controller],templateUrl:"app/common/directives/views/childEntities.html"}})}(),function(){function controller($scope,repository,translationService,ngTableParams,listService,$rootScope){$scope.search={},$scope.collapse={isEntitiesCollapsed:!1},$scope.apiData=_.find(repository.apiData,function(o){return o.prefix===$scope.prefix}),$scope.title||$scope.titleSystemName&&$scope.titleDefaultName||($scope.titleSystemName="web-childEntities-"+$scope.prefix+"-title",$scope.titleDefaultName=translationService.translate("web-"+$scope.prefix,$scope.prefix).replace(":","")),$scope.onEntityClick=function(entity,event){$scope.onClick&&"function"==typeof $scope.onClick&&$scope.onClick(entity,event)},$scope.onDropdownFilterClick=function(filter){$scope.selectedDropdownFilter=filter,$scope.entityTable&&$scope.entityTable.reload()};var initTable=function(){$scope.entityTable||($scope.entityTable=new ngTableParams({page:1,count:10,sorting:$scope.selectedListSetup.Sorting,filter:$scope.filter},{total:0,counts:[10,20,50],filterDelay:50,paginationMaxBlocks:6,getData:function($defer,params){$scope.entitiesAreLoading=!0;var columns=[];$scope.selectedListSetup.VisibleColumns.forEach(function(col){columns.push(col.Property)}),$scope.columns&&$scope.columns.forEach(function(col){var prop=col;prop.Property&&(prop=prop.Property),columns.includes(prop)||columns.push(prop)});var sorting=params.sorting();if($scope.selectedListSetup.GroupBy){var groupSort={};groupSort[$scope.selectedListSetup.GroupBy]="asc";for(var attrname in sorting)groupSort[attrname]=sorting[attrname];sorting=groupSort,$scope.entityTable.$params.sorting=groupSort}var filter=angular.copy(params.filter());$scope.applyDropdownFilter&&"function"==typeof $scope.applyDropdownFilter&&$scope.applyDropdownFilter($scope.selectedDropdownFilter,filter),repository.GetPaginated($scope.apiData.url,params.page()-1,params.count(),sorting,filter,null,JSON.stringify(columns)).then(function(result){$scope.entityTable.settings().total=result.TotalCount,$scope.entityTable.settings().filterDelay=500,$scope.totalCount=result.TotalCount,$defer.resolve(result.List),$scope.entitiesAreLoading=!1},function(error){$scope.entitiesAreLoading=!1,repository.growl(error,"danger")})}}))};$scope.getGroupedByHeaderValue=function(groupByColumnValue){if($scope.selectedListSetup.GroupBy){var column=_.find($scope.selectedListSetup.Columns,function(c){return c.Property===$scope.selectedListSetup.GroupBy});if(column&&column.PropertyType&&column.PropertyType.startsWith("enum.")){var enumType=column.PropertyType.split(".")[1];if(enumType)return translationService.translate("web-enum-"+enumType+"-"+groupByColumnValue)}}return groupByColumnValue},$scope.getWebListViews=function(selectedSetup,overwriteSelected){listService.getWebListViews(selectedSetup,$scope.apiData.prefix,!1,$scope.listContext,{}).then(function(result){$scope.listOptions=result.listOptions,$scope.selectedListSetup=result.selectedListSetup,$scope.entityTable?$scope.entityTable.reload():initTable()})},$scope.getWebListViews(),$scope.$watch("selectedListSetup",function(newValue,oldValue){oldValue!==newValue&&$scope.entityTable&&($scope.entityTable.$params.sorting=$scope.selectedListSetup.Sorting,$scope.selectedListSetup.GroupBy?$scope.entityTable.settings().groupBy=function(obj){return!!$scope.selectedListSetup.GroupBy&&($scope.selectedListSetup.GroupBy.split(".").forEach(function(attr){obj=obj?obj[attr]:""}),obj)}:$scope.entityTable.settings().groupBy=null,listService.updateSelectedListSetup($scope.apiData.prefix,$scope.selectedListSetup),$scope.entityTable.reload())}),$scope.$watch("reloadTable",function(newVal,oldVal){newVal!==oldVal&&$scope.entityTable.reload()}),$scope.getPropertyValue=function(column,row){return listService.GetPropertyValue(column,row)}}angular.module("Plania").directive("childEntitiesListSetup",function(){return{restrict:"E",scope:{prefix:"=prefix",titleSystemName:"=titleSystemName",titleDefaultName:"=titleDefaultName",title:"=title",subtitleSystemName:"=subtitleSystemName",subtitleDefaultName:"=subtitleDefaultName",subtitle:"=subtitle",reloadTable:"=reloadTable",columns:"=columns",filter:"=filter",selectedDropdownFilter:"=selectedDropdownFilter",dropdownFilters:"=dropdownFilters",applyDropdownFilter:"=applyDropdownFilter",listContext:"=listContext",contextMenuOptions:"=contextMenuOptions",onClick:"=onClick",actions:"=actions",canPrint:"=canPrint"},controller:["$scope","Repository","TranslationService","NgTableParams","ListService","$rootScope",controller],templateUrl:"app/common/directives/views/childEntitiesListSetup.html"}})}(),function(){function controller($scope,$modal,ngTableParams,repository,translationService,documentService,$rootScope,$window,$localStorage){$scope.documentsIsLoading=!0,$scope.search={},$scope.enableWebNavigation=$rootScope.userInfo.enableWebNavigation;var supportedAttachmentTypes=["PurchaseOrder","Request","WorkOrder"];$localStorage.generalOptions.IsBBY&&(supportedAttachmentTypes.push("Condition"),supportedAttachmentTypes.push("Deviation")),$scope.canMarkAsAttachment=$localStorage.generalOptions.CanSetDocumentAsAttachment&&supportedAttachmentTypes.includes($scope.entityType),$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.$watch("reload",function(newValue,oldValue){$scope.reload&&!0===$scope.reload&&($scope.documentTable.filter().GuidArea=$scope.guidArea,$scope.documentTable.filter().GuidCleaningTask=$scope.guidCleaningTask,$scope.documentTable.filter().GuidComponent=$scope.guidComponent,$scope.documentTable.filter().GuidCustomer=$scope.guidCustomer,$scope.documentTable.filter().GuidEquipment=$scope.guidEquipment,$scope.documentTable.filter().GuidEstateDocuments=$scope.guidEstate,$scope.documentTable.filter().GuidPeriodicTask=$scope.guidPeriodicTask,$scope.documentTable.filter().GuidPurchaseOrder=$scope.guidPurchaseOrder,$scope.documentTable.filter().GuidRequest=$scope.guidRequest,$scope.documentTable.filter().GuidWorkOrder=$scope.guidWorkOrder,$scope.documentTable.filter().GuidDeviation=$scope.guidDeviation,$scope.documentTable.filter().GuidCondition=$scope.guidCondition,$scope.documentTable.filter().GuidBuildingDocuments=$scope.guidBuilding,$scope.documentTable.filter().GuidSupplier=$scope.guidSupplier,$scope.documentTable.filter().GuidCost=$scope.guidCost,$scope.documentTable.filter().GuidPaymentOrder=$scope.guidPaymentOrder,$scope.documentTable.filter().GuidContract=$scope.guidContract,$scope.documentTable.filter().EntityType=$scope.entityType,$scope.reload=!1)}),$scope.$watch("reloadList",function(){$scope.reloadList&&!$scope.documentsIsLoading&&$scope.documentTable.reload()}),$scope.sortingProperty="Document.Description",$scope.sortingDirection="asc",function(){var properties=[{value:"Document.Description",label:translationService.translate("web-document-description","Beskrivelse")},{value:"Document.DocumentCategory.Description",label:translationService.translate("web-document-DocumentCategory","Kategori")},{value:"Document.DocumentType.Id",label:translationService.translate("web-document-DocumentType","Type")},{value:"Document.Supplier.Description",label:translationService.translate("web-document-Supplier","Leverandør")}];$rootScope.hasModule("DataAcquisition")&&properties.push({value:"DataAcquisitionStatus",label:translationService.translate("web-document-dataAcquisition")}),properties.push({value:"Document.CreationDate",label:translationService.translate("web-documentDirective-creationDate","Sist opprettet")}),properties.push({value:"Document.UpdatedDate",label:translationService.translate("web-documentDirective-updatedDate","Sist oppdatert")}),$scope.sortingProperties=properties}(),$scope.setSorting=function(item){$scope.sortingProperty===item.value?$scope.sortingDirection="desc"===$scope.sortingDirection?"asc":"desc":($scope.sorting={},$scope.sortingProperty=item.value,$scope.sortingDirection="desc"),$scope.documentTable.sorting($scope.sortingProperty,$scope.sortingDirection)},$scope.columns=[{Position:1,Title:translationService.translate("web-document-id"),Property:"Document.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-document-description"),Property:"Document.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-document-filename"),Property:"Document.FilePath",PropertyType:"string"},{Position:4,Title:translationService.translate("web-document-documentType"),Property:"Document.DocumentType.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-document-documentCategory"),Property:"Document.DocumentCategory.Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-document-supplier"),Property:"Document.Supplier.Description",PropertyType:"string"},{Position:7,Title:translationService.translate("web-document-updatedDate"),Property:"Document.UpdatedDate",PropertyType:"string"},{Position:8,Title:translationService.translate("web-document-creationDate"),Property:"Document.CreationDate",PropertyType:"string"}],$rootScope.hasModule("DataAcquisition")&&$scope.columns.push({Position:9,Title:translationService.translate("web-document-dataAcquisition"),Property:"DataAcquisitionStatus",PropertyType:"enum.DataAcquisitionStatus"});var countArray=[],countNumber=1e3;void 0===$scope.printView&&(countArray=[10,20,50],countNumber=10),$scope.useList&&(countArray=[]),$scope.documentTable=new ngTableParams({page:1,count:countNumber,sorting:{"Document.Description":"asc"}},{total:0,counts:countArray,filterDelay:50,paginationMaxBlocks:$scope.useList?6:8,getData:function($defer,params){if(params.filter().GuidArea||params.filter().GuidBuildingDocuments||params.filter().GuidCleaningTask||params.filter().GuidComponent||params.filter().GuidCustomer||params.filter().GuidEquipment||params.filter().GuidEstateDocuments||params.filter().GuidPeriodicTask||params.filter().GuidPurchaseOrder||params.filter().GuidRequest||params.filter().GuidWorkOrder||params.filter().GuidDeviation||params.filter().GuidCondition||params.filter().GuidSupplier||params.filter().GuidCost||params.filter().GuidPaymentOrder||params.filter().GuidContract){$scope.documentsIsLoading=!0;var columns=[];$scope.columns.forEach(function(col){columns.push(col.Property)}),columns.push("ArchiveStatus","IsAttachment","JournalId","Document.DocumentCategory.ArchiveType"),repository.GetPaginated(repository.apiData.documentXEntity.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){if($scope.documentTable.settings().total=result.TotalCount,$scope.totalCount=result.TotalCount,$scope.documentTable.settings().filterDelay=500,$scope.documents||($scope.documents=[]),$scope.documents)for(;$scope.documents.length>0;)$scope.documents.pop();result.List.forEach(function(document){$scope.documents.push(document)}),$defer.resolve(result.List),$scope.documentsIsLoading=!1,$scope.enableWebNavigation=$rootScope.userInfo.enableWebNavigation},function(error){repository.growl(error,"danger")})}}}),$scope.getPropertyValue=function(row,column){var properties=column.Property.split("."),temp=row;if(properties.forEach(function(prop){temp&&(temp=temp[prop])}),"date"===column.PropertyType&&temp){var date=new Date(temp);return("0"+date.getDate()).slice(-2)+"."+("0"+(date.getMonth()+1)).slice(-2)+"."+date.getFullYear()}return temp};var resolveParams=function(){return{guidArea:$scope.guidArea,guidBuilding:$scope.guidBuilding,guidCleaningTask:$scope.guidCleaningTask,guidComponent:$scope.guidComponent,guidCustomer:$scope.guidCustomer,guidEquipment:$scope.guidEquipment,guidEstate:$scope.guidEstate,guidPeriodicTask:$scope.guidPeriodicTask,guidPurchaseOrder:$scope.guidPurchaseOrder,guidRequest:$scope.guidRequest,guidWorkOrder:$scope.guidWorkOrder,guidDeviation:$scope.guidDeviation,guidCondition:$scope.guidCondition,guidSupplier:$scope.guidSupplier,guidCost:$scope.guidCost,guidPaymentOrder:$scope.guidPaymentOrder,guidContract:$scope.guidContract,defaultCategory:$scope.defaultCategory}};$scope.addNewDocument=function(){$scope.isCollapsed=!1,$modal.open({templateUrl:"app/document/views/createDocumentModal.html",controller:"CreateDocumentXEntityController",size:"lg",resolve:{params:resolveParams}}).result.then(function(){$scope.documentTable.reload(),$scope.isCollapsed=!1},function(msg){$scope.isCollapsed=!1})},$scope.addExistingDocument=function(){$scope.isCollapsed=!1,$modal.open({templateUrl:"app/document/views/addExistingDocument.html",controller:"AddExistingDocumentController",resolve:{params:resolveParams}}).result.then(function(){$scope.documentTable.reload(),$scope.isCollapsed=!1},function(msg){$scope.isCollapsed=!1})},$scope.removeDocument=function(document){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-document-message","Dokumentet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-document-button-confirm","Ja, fjern dokumentet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.documentXEntity.url,document.Guid).then(function(result){swal(translationService.translate("web-swal-document-success","Dokumentet ble fjernet!"),result,"success"),repository.growl("Dokumentet har blitt fjernet","success"),$scope.documentTable.reload()})})},$scope.editDocument=function(document){$modal.open({templateUrl:"app/document/views/editDocumentMetadataModal.html",size:"lg",controller:"EditDocumentController",resolve:{$stateParams:function(){return{guid:document.GuidDocument,isModal:!0}}}}).result.then(function(){$scope.documentTable.reload(),$scope.isCollapsed=!1},function(reloadTable){reloadTable&&$scope.documentTable.reload(),$scope.isCollapsed=!1})},$scope.goToMainEditPage=function(document){$rootScope.navigation.go("document.edit",{guid:document.Document.Guid})},$scope.openDocument=function(document){documentService.openDocument(document.Document).then(function(result){$scope.isCollapsed=!1})},$scope.setDataAcquisitionStatus=function(document,status){swal({title:translationService.translate("web-swal-document-setStatus-title","Vil du sette datafangst status til "+translationService.translate("web-enum-DataAcquisitionStatus-"+status,status)+"?"),text:translationService.translate("web-swal-equipment-approval-message","Status vil bli til "+translationService.translate("web-enum-DataAcquisitionStatus-"+status,status)+"!"),type:"info",showCancelButton:!0,confirmButtonColor:"#337ab7",confirmButtonText:translationService.translate("web-swal-equipment-button-confirm-set-dataAcquisitionStatus","Ja, endre status!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null;var success=function(result){$scope.documentTable.reload(),repository.growl(translationService.translate("web-document-dataAcquisition-status-updated","Status har blitt satt!"),"success")},updateError=function(result){repository.growl(result,"danger")};repository.runAction(repository.apiData.documentXEntity.endpoint.setDataAcquisitionStatus+document.Guid,null,"status="+status).then(success,updateError)})},$scope.setArchiveStatus=function(documentXEntity,archiveStatus){var properties={ArchiveStatus:archiveStatus};repository.patch(repository.apiData.documentXEntity.url,documentXEntity.Guid,properties).then(function(){$scope.documentTable.reload(),repository.growl(translationService.translate("web-documentDirective-setArchiveStatus-success","Arkivstatus oppdatert"),"success")},function(error){repository.growl(error,"danger")})},$scope.openDocumentInArchiveSystem=function(xRef){$window.open(xRef.JournalId,"_blank")},$scope.markAsAttachment=function(documentXEntity,mark){if($scope.canMarkAsAttachment){var value=mark?1:0,properties={IsAttachment:value};repository.patch(repository.apiData.documentXEntity.url,documentXEntity.Guid,properties).then(function(){$scope.documentTable.reload(),repository.growl(translationService.translate("web-documentDirective-markAsAttachment-success","Dokumentet er markert som vedlegg"),"success")},function(error){repository.growl(error,"danger")})}}}angular.module("Plania").directive("document",function(){return{restrict:"E",scope:{isCollapsed:"=isCollapsed",reload:"=reload",reloadList:"=reloadList",documents:"=documents",entityType:"=entityType",defaultCategory:"=defaultCategory",disableActions:"=disableActions",totalCount:"=totalCount",guidArea:"=guidArea",guidBuilding:"=guidBuilding",guidCleaningTask:"=guidCleaningTask",guidComponent:"=guidComponent",guidCustomer:"=guidCustomer",guidEquipment:"=guidEquipment",guidEstate:"=guidEstate",guidPeriodicTask:"=guidPeriodicTask",guidPurchaseOrder:"=guidPurchaseOrder",guidRequest:"=guidRequest",guidWorkOrder:"=guidWorkOrder",guidDeviation:"=guidDeviation",guidCondition:"=guidCondition",guidSupplier:"=guidSupplier",guidCost:"=guidCost",guidPaymentOrder:"=guidPaymentOrder",guidContract:"=guidContract",printView:"=print",useList:"=useList",inline:"=inline"},controller:["$scope","$modal","ngTableParams","Repository","TranslationService","DocumentService","$rootScope","$window","$localStorage",controller],link:function(scope,element,attrs){},templateUrl:"app/common/directives/views/DocumentDirective.html"}})}(),angular.module("Plania").directive("dragDropPreventDefault",["$window",function($window){return{restrict:"A",link:function(scope,element,attrs){$window.addEventListener("dragover",function(e){e=e||event,e.preventDefault()},!1),$window.addEventListener("drop",function(e){e=e||event,e.preventDefault()},!1)}}}]),function(){function controller($scope,$localStorage,$modal,$filter,$sce,dynamicPropertyService,$rootScope){$scope.isExternalUser=$localStorage.userData.isExternalUser,$scope.isCollapsed=$localStorage.dynamicPropertiesIsCollapsed,$scope.disabledFields={},$scope.toggleCollapsed=function(){$scope.isCollapsed=!$scope.isCollapsed,$localStorage.dynamicPropertiesIsCollapsed=$scope.isCollapsed},$scope.getClassStyle=function(property,isLast,properties){if("Category"===property.Type)return"dynamic-property-item-width-12";var classes=["dynamic-property-item"];if(property.WebLayout&&(12===property.WebLayout.Width?classes.push("dynamic-property-item-width-12"):8===property.WebLayout.Width&&classes.push("dynamic-property-item-width-8")),isLast&&3===properties.length)classes.push("dynamic-property-item-wrap-fix");else if(2===properties.length){var mediumWidthProp=properties.find(function(prop){return prop.WebLayout&&8===prop.WebLayout.Width});mediumWidthProp&&property!==mediumWidthProp&&classes.push("dynamic-property-item-wrap-fix")}return classes.join(" ")},$scope.openHelpModal=function(text){$modal.open({templateUrl:"app/common/directives/dynamicProperty/dynamicPropertyHelpModal.html",controller:"DynamicPropertyHelpController",size:"m",resolve:{params:function(){return{text:text}}}})};var getItems=function(){return $scope.model&&$scope.model.DynamicProperty&&$scope.model.DynamicProperty.Groups?dynamicPropertyService.getItems($scope.model.DynamicProperty.Groups):[]},reinitDynamicFieldDefaultValues=function(){getItems().forEach(function(item){if("Combo"===item.Type){_.find(item.NamedSelectionOptions,function(option){return option===$scope.model[item.PropertyName]})||(item.NamedSelectionDefaultOption?$scope.model[item.PropertyName]=item.NamedSelectionDefaultOption:$scope.model[item.PropertyName]=null)}})},oldPropertyValue=$scope.model[$scope.guidProperty],oldAutoCompleteValue=$scope.autoCompleteProperty;$scope.getPropertyValue=function(property){var value=$scope.model[property.PropertyName];return value&&"Date"===property.Type?$filter("date")(value,"dd.MM.yyyy"):value};var updateDisabledFields=function(){var disabledFields={};return $rootScope.customization.isCustomer("KA")&&"GuidBuildingCategory"===$scope.guidProperty&&$scope.model.ExternalId?(disabledFields={Text01:!0,Text07:!0,Text11:!0,Text13:!0,Text14:!0,Combo01:!0,Combo12:!0,Number05:!0,Number06:!0,Number07:!0},void($scope.disabledFields=disabledFields)):void($scope.disabledFields=disabledFields)};$rootScope.customization.isCustomer("KA")&&"GuidBuildingCategory"===$scope.guidProperty&&$scope.$watch("model.ExternalId",function(){updateDisabledFields()}),$scope.$watch("model."+$scope.guidProperty,function(newValue,oldValue){if(newValue!==oldValue&&newValue!==oldPropertyValue)return void 0===oldPropertyValue?(oldPropertyValue=newValue,oldAutoCompleteValue=$scope.autoCompleteProperty,void((!$scope.model.DynamicProperty||$scope.model.DynamicProperty.Groups.length<=0)&&($scope.model.DynamicProperty=$scope.newDynamicProperty,reinitDynamicFieldDefaultValues(),updateDisabledFields()))):void($scope.model.DynamicProperty&&$scope.model.DynamicProperty.Groups.length>0?$modal.open({templateUrl:"app/common/views/confirmationBox.html",controller:"ConfirmationBoxController",resolve:{confirmation:function(){return{header:"Bekreft handling",message:"Du endrer en kategori som har egendefinerte felter, ønsker du å fortsette?"}}}}).result.then(function(){oldPropertyValue=newValue,oldAutoCompleteValue=$scope.autoCompleteProperty,$scope.model.DynamicProperty=$scope.newDynamicProperty,reinitDynamicFieldDefaultValues(),updateDisabledFields()},function(){$scope.model[$scope.guidProperty]=oldPropertyValue,$scope.autoCompleteProperty=oldAutoCompleteValue}):(oldPropertyValue=newValue,oldAutoCompleteValue=$scope.autoCompleteProperty,$scope.model.DynamicProperty=$scope.newDynamicProperty,reinitDynamicFieldDefaultValues(),updateDisabledFields()))})}var app=angular.module("Plania");app.directive("dynamicProperties",function(){return{restrict:"E",scope:{model:"=model",isCollapsed:"=isCollapsed",guidProperty:"=guidProperty",newDynamicProperty:"=newDynamicProperty",autoCompleteProperty:"=autoCompleteProperty",viewMode:"=viewMode",restrictEdit:"=restrictEdit",delayMandatoryFields:"=delayMandatoryFields"},controller:["$scope","$localStorage","$modal","$filter","$sce","DynamicPropertyService","$rootScope",controller],templateUrl:"app/common/directives/dynamicProperty/dynamicPropertyDirective.html"}}),app.controller("DynamicPropertyHelpController",["$scope","params","$modalInstance",function($scope,params,$modalInstance){$scope.text=params.text,$scope.cancel=function(){$modalInstance.dismiss("canceled")}}])}(),function(){function controller($scope){$scope.values=[];var setValues=function(){var values=[];$scope.item.NamedSelectionOptions&&(values=$scope.item.NamedSelectionOptions.map(function(val){return val})),$scope.values=values};setValues(),$scope.$watchGroup(["item.NamedSelectionOptions"],function(){setValues()})}angular.module("Plania").directive("dynamicPropertySelect",[function(){return{restrict:"E",require:"^dynamicProperties",scope:{ngModel:"=",ngDisabled:"=",item:"=",multiple:"="},compile:function(element,attrs){var select=element.find("string-value-select");select&&attrs.multiple&&select.attr("multiple","true")},controller:["$scope",controller],template:''}}])}(),function(){function controller($scope,repository,$modal,signalR){var fetchData=function(){var columns=["UserCreatedBy.RealName","UserCreatedBy.UserName","UserCreatedBy.GuidImage","Comment","ReadDate","CreationDate"];repository.GetPaginated(repository.apiData.entityComment.url,-1,-1,{CreationDate:"desc"},{PropertyFilter:[{Property:"Guid"+$scope.entity,Operator:"=",Value:$scope.guid}]},"",JSON.stringify(columns)).then(function(result){$scope.entityComments=result.List,$scope.entityCommentCount=result.TotalCount},function(error){repository.growl(error,"danger")})};fetchData(),$scope.newComment={text:""},$scope.searchString="",$scope.addComment=function(){if(!$scope.newComment.text)return void swal("Mangler kommentartekst","Skriv inn en kommentar i tekstfeltet for å få lagt til en kommentar","info");var newComment={Comment:$scope.newComment.text};newComment["Guid"+$scope.entity]=$scope.guid,repository.createSingle(repository.apiData.entityComment.url,newComment).then(function(result){$scope.newComment={text:""},fetchData()},function(error){repository.growl(error,"danger")})},$scope.readComment=function(comment){comment.ReadDate||comment.GuidUserCreatedBy===repository.authService.getUserData().guidUser||(comment.ReadDate=(new Date).toISOString(),repository.updateSingle(repository.apiData.entityComment.url,comment).then(function(result){},function(error){repository.growl("Kunne ikke oppdatere kommentaren","danger"),comment.ReadDate=null}));var date=new Date(comment.CreationDate);$modal.open({templateUrl:"app/common/views/messageModal.html",controller:"MessageModalController",resolve:{content:function(){return{header:"Kommentar",message:comment.Comment,timestamp:date}}}})},signalR.on("EntityCommentChangedForEntityGuid"+$scope.guid,function(){fetchData()}),$scope.$on("$destroy",function(){signalR.off("EntityCommentChangedForEntityGuid"+$scope.guid)}),$scope.$watch("entitySearch",function(newVal,oldVal){newVal!==oldVal&&($scope.searchString=newVal)}),$scope.filterComment=function(comment){if(void 0===$scope.searchString||null===$scope.searchString||""===$scope.searchString.trim())return!0;var searchString=$scope.searchString.toLowerCase(),match=!1;return match||void 0===comment.Comment||null===comment.Comment||(match=comment.Comment.toLowerCase().includes(searchString)),!match&&comment.UserCreatedBy&&void 0!==comment.UserCreatedBy.RealName&&null!==comment.UserCreatedBy.RealName&&(match=comment.UserCreatedBy.RealName.toLowerCase().includes(searchString)),!match&&comment.UserCreatedBy&&void 0!==comment.UserCreatedBy.Username&&null!==comment.UserCreatedBy.Username&&(match=comment.UserCreatedBy.Username.toLowerCase().includes(searchString)),match}} angular.module("Plania").directive("entityComment",function(){return{restrict:"E",scope:{entity:"=entity",guid:"=guid",entityComments:"=entityComments",entitySearch:"="},controller:["$scope","Repository","$modal","SignalR",controller],templateUrl:"app/common/directives/views/entityComment.html"}})}(),function(){function controller($scope,repository,translationService){function getEntityLinks(){repository.getWithUrlParameter(repository.apiData.entityLink.url+"actionsForEntity","guidEntity="+$scope.guidEntity+"&prefix="+$scope.entityType).then(function(result){$scope.totalCount=result.length,$scope.entityLinks=result},function(error){repository.showError(error)})}$scope.guidEntity&&$scope.entityType&&($scope.entityLinks=[],getEntityLinks(),$scope.getStatusColor=function(status){if("Created"===status)return"info";switch(status){case"Created":return"info";case"Error":return"danger"}},$scope.runAction=function(link){swal({title:"Bekreft",text:translationService.translate("web-entityTask-confirmAction","Vil du opprette handling %Name%?",link),type:"info",showCancelButton:!0,confirmButtonColor:"#337ab7",confirmButtonText:"Ja",cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null;var params={GuidEntity:$scope.guidEntity},guidEntityLink=link.Guid;repository.runAction(repository.apiData.entityLink.url+guidEntityLink+"/doAction",params).then(function(response){repository.growl("Utført","success"),getEntityLinks(),swal.close()}).catch(function(error){repository.growl(error,"danger"),getEntityLinks(),swal.close()})})})}angular.module("Plania").directive("entityTask",function(){return{restrict:"E",scope:{reload:"=reload",entityType:"=entityType",guidEntity:"=guidEntity",disableActions:"=disableActions"},controller:["$scope","Repository","TranslationService",controller],templateUrl:"app/common/directives/views/entityTaskDirective.html"}})}(),function(){angular.module("Plania").directive("filterOperatorSelect",["TranslationService",function(translationService){return{restrict:"E",scope:{ngModel:"=",ngDisabled:"=",propertyType:"=",property:"=",useSearch:"=",callbackObject:"=",onUpdateOperators:"="},link:function(scope,element,attrs){scope.operators=[];var availableOperators=["=","<>",">","<",">=","<=","&","startswith","in","notin","contains"],isOperatorSupported=function(operator,propertyType){var isSupported=!1;switch(propertyType){case"string":isSupported=["=","<>","startswith","in","notin","contains"].includes(operator);break;case"boolean":case"bool":isSupported=["=","<>"].includes(operator);break;case"double":case"int":case"number":case"decimal":case"date":isSupported=["=","<>",">","<",">=","<="].includes(operator);break;case"autocomplete":isSupported="&"!==operator;break;case"enum":isSupported=["=","<>",">","<",">=","<=","in","notin"].includes(operator);break;default:isSupported="&"!==operator}return isSupported||"&"!==operator||"DocumentationContext"!==scope.property&&"AccessType"!==scope.property||(isSupported=!0),isSupported},getOperatorName=function(operator,propertyType){var name="Ukjent funksjon";switch(operator){case"=":name=translationService.translate("web-filterOperatorSelect-operator-equal","=");break;case"<>":name=translationService.translate("web-filterOperatorSelect-operator-notEqual","<>");break;case">":name=translationService.translate("web-filterOperatorSelect-operator-greaterThan",">");break;case"<":name=translationService.translate("web-filterOperatorSelect-operator-lessThan","<");break;case">=":name=translationService.translate("web-filterOperatorSelect-operator-greaterThanOrEqual",">=");break;case"<=":name=translationService.translate("web-filterOperatorSelect-operator-lessThanOrEqual","<=");break;case"&":name=translationService.translate("web-filterOperatorSelect-operator-bitwiseAnd","&");break;case"startswith":name=translationService.translate("web-filterOperatorSelect-operator-startswith","startswith");break;case"in":name=translationService.translate("web-filterOperatorSelect-operator-in","in");break;case"notin":name=translationService.translate("web-filterOperatorSelect-operator-notin","notin");break;case"contains":name=translationService.translate("web-filterOperatorSelect-operator-contains","contains")}return name},setOperators=function(){var operators=[],basePropertyType=scope.propertyType.split(".")[0];if(availableOperators.forEach(function(operator){isOperatorSupported(operator,basePropertyType)&&operators.push({value:operator,name:getOperatorName(operator,basePropertyType)})}),scope.onUpdateOperators&&"function"==typeof scope.onUpdateOperators&&scope.onUpdateOperators(operators,scope.callbackObject),scope.ngModel&&!_.find(operators,{value:scope.ngModel})){var notSupportedOperatorName=translationService.translate("web-filterOperatorSelect-operator-notSupportedForProperty","Ikke støttet for felttype")+": "+scope.ngModel;operators.unshift({value:scope.ngModel,name:notSupportedOperatorName})}scope.operators=operators};setOperators(),scope.$watch("propertyType",function(newVal,oldVal){newVal!==oldVal&&setOperators()})},template:''}}])}(),angular.module("Plania").directive("fgLine",function(){return{restrict:"C",link:function(scope,element){$(element[0]).on("focus",".form-control",function(){$(this).closest(".fg-line").addClass("fg-toggled")}),$(element[0]).on("blur",".form-control",function(){var p=$(this).closest(".form-group"),i=p.find(".form-control").val();p.hasClass("fg-float")?($(this).closest(".fg-line").removeClass("fg-toggled"),i.length>0?$(this).closest(".fg-line").addClass("floated-label"):$(this).closest(".fg-line").removeClass("floated-label")):$(this).closest(".fg-line").removeClass("fg-toggled")})}}}).directive("autoSize",function($timeout){return{restrict:"A",require:"ngModel",scope:!1,link:function(scope,element,attrs,ngModel){$timeout(function(){autosize(element[0]),scope.$watch(function(){return ngModel.$modelValue},function(newValue,oldValue){newValue!==oldValue&&autosize.update(element[0])}),$(element[0]).on("focus",function(){autosize.update(element[0])})})}}}).directive("selectPicker",[function(){return{restrict:"A",scope:{items:"=selectPickerData",selected:"=ngModel",onChange:"=selectPickerOnChange"},link:function(scope,element,attrs){element.selectpicker(),scope.$watch("items",function(newValue,oldValue){element.selectpicker("refresh")},!0),scope.$watch("selected",function(newValue,oldValue){scope.onChange&&("function"==typeof scope.onChange?scope.onChange(scope.selected):scope.onChange=scope.selected),element.selectpicker("refresh")},!0)}}}]).directive("angularMask",function(){return{restrict:"A",require:"ngModel",link:function($scope,el,attrs,model){function mask(val){var format=attrs.angularMask,arrFormat=format.split("|");if(arrFormat.length>1&&arrFormat.sort(function(a,b){return a.length-b.length}),null===val||""===val)return"";var value=String(val).replace(/\D/g,"");if(arrFormat.length>1)for(var a in arrFormat)if(value.replace(/\D/g,"").length<=arrFormat[a].replace(/\D/g,"").length){format=arrFormat[a];break}for(var newValue="",nmI=0,mI=0;mI"+image.Description+""];return image.UserCreatedByName&&elements.push(["
    ","",translationService.translate("web-imageGalleryItem-userCreatedByName","Opprettet av"),""," ",image.UserCreatedByName,""," ",$filter("date")(image.CreationDate,"dd.MM.yyyy"),"","
    "].join("")),'
    '+elements.join("")+"
    "},$scope.addNewImage=function(){$modal.open({templateUrl:"app/document/views/createImageModal.html",controller:"CreateDocumentXEntityController",size:"lg",resolve:{params:resolveParams}}).result.then(function(images){if(images){images.forEach(function(image){$scope.images.push(image)}),$scope.imageGalleryTable.reload();var lastPage=Math.ceil($scope.imageGalleryTable.settings().total/$scope.imageGalleryTable.count());$scope.imageGalleryTable.page(lastPage)}},function(msg){})};var getGuidEntity=function(){return $scope.guidBuilding?$scope.guidBuilding:$scope.guidEquipment?$scope.guidEquipment:$scope.guidEstate?$scope.guidEstate:$scope.guidPeriodicTask?$scope.guidPeriodicTask:$scope.guidRequest?$scope.guidRequest:$scope.guidWorkOrder?$scope.guidWorkOrder:$scope.guidDeviation?$scope.guidDeviation:$scope.guidCondition?$scope.guidCondition:$scope.guidArea?$scope.guidArea:null},getEntityType=function(){return $scope.guidBuilding?"Building":$scope.guidEquipment?"Equipment":$scope.guidEstate?"Estate":$scope.guidPeriodicTask?"PeriodicTask":$scope.guidRequest?"Request":$scope.guidWorkOrder?"WorkOrder":$scope.guidDeviation?"Deviation":$scope.guidCondition?"Condition":$scope.guidArea?"Area":null},onChange=function(image){$scope.images.forEach(function(img){image.IsDefault&&img.Guid!==image.Guid&&(img.IsDefault=!1),img.Guid===image.Guid&&(img.IsDefault=image.IsDefault,img.IsAttachment=image.IsAttachment)}),$scope.images=_.sortBy($scope.images,function(img){return!img.IsDefault}),$scope.imageGalleryTable.reload()};$scope.editImage=function(image){$modal.open({templateUrl:"app/document/views/editImageModal.html",controller:"EditImageController",size:"lg",resolve:{params:function(){return{image:image,guidEntity:getGuidEntity(),entityType:getEntityType(),deleteAccess:$scope.delete,onChange:onChange}}}}).result.then(function(result){var index=_.findIndex($scope.images,{Guid:image.Guid});"Deleted"===result?$scope.images.splice(index,1):(planiaUtils.copyProperties(result,image),$scope.images.splice(index,1),image.timestamp=(new Date).toISOString(),$scope.images.splice(index,0,image)),$scope.imageGalleryTable.reload();var currentPage=$scope.imageGalleryTable.page(),lastPage=Math.ceil($scope.imageGalleryTable.settings().total/$scope.imageGalleryTable.count());currentPage>lastPage&&$scope.imageGalleryTable.page(lastPage)})}}angular.module("Plania").directive("imageGallery",function(){return{restrict:"E",scope:{reload:"=reload",edit:"=edit",delete:"=delete",images:"=images",inline:"=inline",columnSize:"=columnSize",guidBuilding:"=guidBuilding",guidComponent:"=guidComponent",guidEquipment:"=guidEquipment",guidEstate:"=guidEstate",guidPeriodicTask:"=guidPeriodicTask",guidRequest:"=guidRequest",guidWorkOrder:"=guidWorkOrder",guidCondition:"=guidCondition",guidDeviation:"=guidDeviation",guidArea:"=guidArea"},controller:["$scope","$modal","ngTableParams","config","Repository","$filter","TranslationService",controller],templateUrl:"app/common/directives/views/imageGallery.html"}})}(),function(){angular.module("Plania").directive("imageGalleryItem",[function(){return{restrict:"A",link:function(scope,element,attrs){element.on("load",function(event){var image=$(element);image[0].height+44>image[0].width?(image.css("height","100%"),image.css("width","auto")):(image.css("position","absolute"),image.css("transform","translate(0%, -50%)"),image.css("top","50%"),image.css("height","auto"),image.css("width","100%"))})}}}])}(),angular.module("Plania").directive("inlinePdf",["$window",function($window){return{restrict:"E",replace:!0,scope:{url:"="},link:function(scope,element,attrs){scope.$watch("url",function(newValue,oldValue){newValue!==oldValue&&(element[0].innerHTML='')}),$(element[0]).height($("html").height()-70)},template:'
    '}}]),angular.module("Plania").directive("focusMe",["$timeout",function($timeout){return{link:function(scope,element,attrs){scope.$watch(attrs.focusMe,function(value){!0===value&&$timeout(function(){element[0].focus(),scope[attrs.focusMe]=!1})})}}}]),function(){var app=angular.module("Plania");app.directive("changeLayout",function(){return{restrict:"A",scope:{changeLayout:"="},link:function(scope,element){"1"===scope.changeLayout&&element.prop("checked",!0),element.on("change",function(){element.is(":checked")?(localStorage.setItem("ma-layout-status",1),scope.$apply(function(){scope.changeLayout="1"})):(localStorage.setItem("ma-layout-status",0),scope.$apply(function(){scope.changeLayout="0"}))})}}}),app.directive("toggleSidebar",function(){return{restrict:"A",scope:{modelLeft:"=",modelRight:"="},link:function(scope,element){element.on("click",function(){"mainmenu"===element.data("target")&&(!1===scope.modelLeft?scope.$apply(function(){scope.modelLeft=!0}):scope.$apply(function(){scope.modelLeft=!1})),"chat"===element.data("target")&&(!1===scope.modelRight?scope.$apply(function(){scope.modelRight=!0}):scope.$apply(function(){scope.modelRight=!1}))})}}}),app.directive("toggleSubmenu",function(){return{restrict:"A",link:function(scope,element){element.click(function(){element.next().slideToggle(200),element.parent().toggleClass("toggled")})}}}),app.directive("stopPropagate",function(){return{restrict:"C",link:function(scope,element){element.on("click",function(event){event.stopPropagation()})}}}),app.directive("aPrevent",function(){return{restrict:"C",link:function(scope,element){element.on("click",function(event){event.preventDefault()})}}}),app.directive("print",function(){return{restrict:"A",link:function(scope,element){element.click(function(){window.print()})}}}),app.directive("toggle",function(){return{restrict:"A",link:function(scope,element,attrs){var x=attrs.toggle;"tooltip"===x&&element.tooltip(),"popover"===x&&element.popover()}}}),app.directive("collapse",function(){return{restrict:"C",link:function(scope,element){element.on("show.bs.collapse",function(){$(this).closest(".panel").find(".panel-heading").addClass("active")}),element.on("hide.bs.collapse",function(){$(this).closest(".panel").find(".panel-heading").removeClass("active")}),$(".collapse.in").each(function(){$(this).closest(".panel").find(".panel-heading").addClass("active")})}}}),app.directive("maDropdown",function(){return{restrict:"C",link:function(scope,element,attrs){var $animation=attrs.animation,$animArray=$animation.split(","),$animationIn="animated "+$animArray[0],$animationOut="animated "+$animArray[1],$animationDuration=500;$animArray[2]&&($animationDuration=$animArray[2]),element.on("shown.bs.dropdown",function(){$(this).data("animation")&&($(this).find(".dropdown-menu").removeClass($animationOut),$(this).find(".dropdown-menu").addClass($animationIn))}),element.on("hide.bs.dropdown",function(e){if($(this).data("animation")){e.preventDefault();var $this=$(this);$this.find(".dropdown-menu").addClass($animationOut),setTimeout(function(){$this.removeClass("open")},$animationDuration)}})}}}),app.directive("weatherWidget",function(){return{restrict:"A",link:function(){$.simpleWeather({location:"Austin, TX",woeid:"",unit:"f",success:function(weather){var html='
    '+weather.temp+"°"+weather.units.temp+"
    ";html+='
    • '+weather.city+", "+weather.region+"
    • ",html+='
    • '+weather.currently+"
    ",html+='
    ',html+='",$("#weather-widget").html(html)},error:function(error){$("#weather-widget").html("

    "+error+"

    ")}})}}}),app.directive("animDemo",["$timeout",function($timeout){return{restrict:"A",link:function(scope,element){element.click(function(){var animation=$(this).text(),cardImg=$(this).closest(".card").find("img"),animationDuration=1200;"hinge"===animation&&(animationDuration=2100),cardImg.removeAttr("class"),cardImg.addClass("animated "+animation),$timeout(function(){cardImg.removeClass(animation)},animationDuration)})}}}]),app.directive("swalBasic",function(){return{restrict:"A",link:function(scope,element){element.click(function(){swal("Here's a message!")})}}}),app.directive("swalText",function(){return{restrict:"A",link:function(scope,element){element.click(function(){swal("Here's a message!","Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lorem erat, tincidunt vitae ipsum et, pellentesque maximus enim. Mauris eleifend ex semper, lobortis purus sed, pharetra felis")})}}}),app.directive("swalSuccess",function(){return{restrict:"A",link:function(scope,element){element.click(function(){swal("Good job!","Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lorem erat, tincidunt vitae ipsum et, pellentesque maximus enim. Mauris eleifend ex semper, lobortis purus sed, pharetra felis","success")})}}}),app.directive("swalWarning",function(){return{restrict:"A",link:function(scope,element){element.click(function(){swal({title:"Er du sikker?",text:"Dataen vil bli permanent slettet!",type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:"Slett",closeOnConfirm:!1},function(){swal("Slettet!","Your imaginary file has been deleted.","success")})})}}}),app.directive("swalParams",function(){return{restrict:"A",link:function(scope,element){element.click(function(){swal({title:"Are you sure?",text:"You will not be able to recover this imaginary file!",type:"warning",showCancelButton:!0,confirmButtonColor:"#DD6B55",confirmButtonText:"Yes, delete it!",cancelButtonText:"No, cancel plx!",closeOnConfirm:!1,closeOnCancel:!1},function(isConfirm){isConfirm?swal("Deleted!","Your imaginary file has been deleted.","success"):swal("Cancelled","Your imaginary file is safe :)","error")})})}}}),app.directive("swalImg",function(){return{restrict:"A",link:function(scope,element){element.click(function(){swal({title:"Sweet!",text:"Here's a custom image.",imageUrl:"img/thumbs-up.png"})})}}}),app.directive("swalTimer",function(){return{restrict:"A",link:function(scope,element){element.click(function(){swal({title:"Auto close alert!",text:"I will close in 2 seconds.",timer:2e3,showConfirmButton:!1})})}}}),app.directive("growlDemo",function(){return{restrict:"A",link:function(scope,element,attrs){function notify(from,align,icon,type,animIn,animOut){$.growl({icon:icon,title:" Bootstrap Growl ",message:"Turning standard Bootstrap alerts into awesome notifications",url:""},{element:"body",type:type,allow_dismiss:!0,placement:{from:from,align:align},offset:{x:20,y:85},spacing:10,z_index:1031,delay:2500,timer:1e3,url_target:"_blank",mouse_over:!1,animate:{enter:animIn,exit:animOut},icon_type:"class",template:''})}element.on("click",function(e){e.preventDefault(),notify(attrs.from,attrs.align,attrs.icon,attrs.type,attrs.animationIn,attrs.animationOut)})}}}),app.directive("modalColor",function(){return{restrict:"A",link:function(scope,element,attrs){element.click(function(){var color=attrs.targetColor;$("#modalColor").attr("data-modal-color",color)})}}}),app.directive("mediaElement",function(){return{restrict:"A",link:function(scope,element){element.mediaelementplayer({success:function(mediaElement,originalNode){mediaElement.play()}})}}}).directive("lightgallery",function(){return{restrict:"A",link:function(scope,element){if(scope.$last){var lg=element.parent();lg.data&&lg.data("lightGallery")&&lg.data("lightGallery").destroy(!0),lg.lightGallery()}}}})}(),function(){function controller($scope,translationService){$scope.icon||$scope.hideIcon||("info"===$scope.severity?$scope.icon="fa-circle-info":"danger"===$scope.severity?$scope.icon="fa-circle-exclamation":"warning"===$scope.severity?$scope.icon="fa-triangle-exclamation":"success"===$scope.severity&&($scope.icon="fa-check-circle")),$scope.hideHeader||$scope.header||("info"===$scope.severity?$scope.header=translationService.translate("web-plAlert-info-header","Info"):"danger"===$scope.severity?$scope.header=translationService.translate("web-plAlert-danger-header","Fare"):"warning"===$scope.severity?$scope.header=translationService.translate("web-plAlert-warning-header","Advarsel"):"success"===$scope.severity&&($scope.header=translationService.translate("web-plAlert-success-header","Vellykket")))}angular.module("Plania").directive("plAlert",function(){return{restrict:"E",scope:{severity:"=severity",header:"@header",hideHeader:"=hideHeader",hideIcon:"=hideIcon",text:"@text"},controller:["$scope","TranslationService",controller],templateUrl:"app/common/directives/views/plAlert.html"}})}(),function(){function controller($scope,constants){$scope.colors=constants.defaultLikertScaleColors,$scope.setColor=function(num){$scope.ngModel=num}}angular.module("Plania").directive("plColorPickerDirective",function(){return{restrict:"E",scope:{ngModel:"=",ngDisabled:"="},controller:["$scope","Constants",controller],templateUrl:"app/common/directives/views/plColorPickerDirective.html"}})}(),angular.module("Plania").directive("plCurrencyInput",["$window","$filter",function($window,$filter){return{restrict:"A",require:"ngModel",link:function(scope,element,attrs,ctrl){function updateView(hasFocus){if(ctrl.$modelValue){var displayValue=hasFocus?ctrl.$modelValue:$filter("number")(ctrl.$modelValue,2);rawElement.value=displayValue}}var rawElement=element[0];element.on("focus",updateView.bind(null,!0)),element.on("blur",updateView.bind(null,!1)),scope.$watch("viewMode",function(){updateView(!1)});var loadListener=scope.$watch(attrs.ngModel,function(newValue){if(void 0!==newValue&&!Number.isNaN(newValue)){try{updateView($(element).is(":focus"))}catch(ex){}loadListener()}})}}}]),function(){function controller($scope,constants){$scope.datepickerProps={isOpen:!1,focus:!1},$scope.id||($scope.id=$scope.name),$scope.name||($scope.name=$scope.id),$scope.dateOptions=constants.dateOptions,"month"===$scope.calendarMode?($scope.placeholder="mm.yyyy",$scope.mode="'month'",$scope.popup="MMMM yyyy",$scope.dateOptions.minMode="month"):($scope.placeholder="dd.mm.yyyy",$scope.mode="'day'",$scope.popup="dd.MM.yyyy",$scope.dateOptions.minMode="day"),$scope.floatingLabel&&($scope.placeholder=""),$scope.dateOptions.plIgnoreFocus=!0,$scope.open=function($event){$scope.ngDisabled||($event.preventDefault(),$event.stopPropagation(),$scope.datepickerProps.isOpen=!$scope.datepickerProps.isOpen)}}angular.module("Plania").directive("plDatepicker",function(){return{restrict:"E",scope:{id:"@",name:"@",ngModel:"=",ngDisabled:"=",floatingLabel:"@",calendarMode:"@"},require:"^ngModel",controller:["$scope","Constants",controller],templateUrl:"app/common/directives/views/plDatepickerDirective.html",link:linkFunction}});var linkFunction=function(scope,element,attrs,ngModelCtrl){var attr="";scope.attrs={class:"",id:"",inputclass:"",inputid:""};for(var a in attrs)attr=a.replace("attr","").toLowerCase(),0===a.indexOf("attr")&&(scope.attrs[attr]=attrs[a]);scope.updateModel=function(item){ngModelCtrl.$setViewValue(item)}}}(),function(){angular.module("Plania").directive("plDeactivatedWarning",function(){return{restrict:"E",replace:!0,template:' Deaktivert for fremtidig bruk'}})}(),function(){angular.module("Plania").directive("plEntityNavigation",["Repository","$rootScope","$q",function(repository,$rootScope,$q){return{restrict:"E",scope:{entity:"=entity",guid:"=guid",model:"=model",context:"=context",target:"=target",allowEntityNavigation:"=allowEntityNavigation"},templateUrl:"app/common/directives/views/entityNavigation.html",link:function(scope,element,attrs){var loadedEntity={guid:"",context:""},isElementVisible=function(){return!element||"function"!=typeof element.css||"none"!==element.css("display")};scope.isVisible=isElementVisible(),scope.$watch(function(){return isElementVisible()},function(){scope.isVisible=isElementVisible()});var getContext=function(){var deferred=$q.defer();return scope.isVisible&&"Customer"===scope.entity&&scope.canNavigate&&scope.guid&&!scope.context&&scope.$parent.$root.hasModule("Housing")?loadedEntity.guid===scope.Guid?$.Deferred().resolve(loadedEntity.context).promise():(scope.navigationState=null,repository.getSingle(repository.apiData.customer.url,scope.guid).then(function(response){response&&response.Data&&response.Data.Guid===scope.guid?(context=response&&response.Data&&response.Data.CustomerType&&"Person"===response.Data.CustomerType?planiaUtils.contextIds.housingCustomer:void 0,loadedEntity.guid=scope.guid,loadedEntity.context=context,deferred.resolve(context)):deferred.resolve(scope.context)},function(){deferred.resolve(scope.context)}),deferred.promise):$.Deferred().resolve(scope.context).promise()},refreshNavigationState=function(){getContext().then(function(context){var apiData=_.find(repository.apiData,function(o){return o.prefix===scope.entity&&(!context||o.contextId===context)});if(scope.navigationState=apiData.navigationState,scope.guid){var allowEntityNavigation=scope.allowEntityNavigation;void 0===allowEntityNavigation&&(allowEntityNavigation=apiData.allowEntityNavigation),scope.canNavigate=scope.$parent.$root.hasReadAccess(scope.entity)&&$rootScope.userInfo.enableWebNavigation&&allowEntityNavigation}else scope.canNavigate=!1,scope.model=null})};refreshNavigationState(),scope.$watchGroup(["entity","guid","context","isVisible"],function(){refreshNavigationState()})}}}])}(),function(){function controller($scope,enumService,translationService){var enumNumberToString=function(enumValue){if(enumValue&&$scope.enumType){if("string"==typeof enumValue&&-1!==enumValue.indexOf(",")){var translatedValues=_.map(enumValue.split(","),function(s){return s=s.trim(),translationService.translate("web-enum-"+$scope.enumType+"-"+s,s)});return void($scope.translatedEnumValue=translatedValues.join(", "))}"number"==typeof enumValue?enumService.EnumNumberToString($scope.enumType,enumValue).then(function(res){$scope.translatedEnumValue=translationService.translate("web-enum-"+$scope.enumType+"-"+res,res)}):$scope.translatedEnumValue=translationService.translate("web-enum-"+$scope.enumType+"-"+enumValue,enumValue)}};$scope.translatedEnumValue||enumNumberToString($scope.enumValue),$scope.$watch("enumValue",function(newValue,oldValue){newValue!==oldValue&&enumNumberToString(newValue)})}angular.module("Plania").directive("plEnum",function(){return{restrict:"E",scope:{enumType:"=enumType",enumValue:"=ngModel"},controller:["$scope","EnumService","TranslationService",controller],template:"{{translatedEnumValue}}"}})}(),function(){function controller($scope,enumService,$localStorage){$scope.internalValue=$scope.multiple?[]:"",$scope.ngDisabled||($scope.ngDisabled=!1),$scope.placeholder||($scope.placeholder="Velg fra listen..."),void 0===$scope.disableSearch&&($scope.disableSearch=!0),$scope.selectedValueProperty||($scope.selectedValueProperty="Value");var isNull=function(val){return void 0===val||null===val||""===val},limitEnumOptions=function(enumOptions){var options=enumOptions.slice(0);if(!$scope.limitEnumOptions)return options;var validOptions=[];return"PeriodicTask.Period"===$scope.limitEnumOptions&&(validOptions=["Day","Week","Month","Year","HourOfUse"]),"PeriodicTask.deadlinePeriodUnit"===$scope.limitEnumOptions&&(validOptions=$localStorage.generalOptions.EnableWorkingDaysOnPriority?["WorkDay","Day","Week","Month","Year"]:["Day","Week","Month","Year"]),"CleaningTask.TimePeriodUnit"===$scope.limitEnumOptions&&(validOptions=["Day","Week","Month"]),"GeneralOptions.ContractTypeRentalPeriod"===$scope.limitEnumOptions&&(validOptions=["Day","Week","Month","Year","Hour","Once","Undefined","Udefinert"]),"Deviation.ClosedReason"===$scope.limitEnumOptions&&(validOptions=["Duplicate","AsExpected","WillNotBeSolved","NotRelevant"]),"DataOwner.EnergyPeriodUnit"!==$scope.limitEnumOptions&&"DataOwner.ActivityPeriodUnit"!==$scope.limitEnumOptions||(validOptions=["Day","Week","Month","Year","Hour","Once"]),"ComponentXSupplier.DeliveryTimePeriodUnit"===$scope.limitEnumOptions&&(validOptions=["Undefined","Day","Week","Month","Year","Hour"]),"ReferenceType.Context"!==$scope.limitEnumOptions||$localStorage.generalOptions.ExtendedDeviationControl?validOptions.length>0?(_.remove(options,function(option){return!validOptions.some(function(o){return o===option.StringValue})}),options):options:options.filter(function(option){return"DeviationClassification"!==option.StringValue&&"DeviationCause"!==option.StringValue})};$scope.applyChange=function(newValue){$scope.selectedValue=newValue,$scope.onChange&&"function"==typeof $scope.onChange&&$scope.onChange(newValue)};var findValue=function(val){if(isNull($scope.enumSelectOptions))return val ;var selectedEnumValue=_.find($scope.enumSelectOptions,function(enumValue){var isFound=enumValue[$scope.selectedValueProperty].toString()===val.toString();return isFound||(isFound=enumValue["StringValue"===$scope.selectedValueProperty?"Value":"StringValue"].toString()===val.toString()),isFound});return isNull(selectedEnumValue)?val:selectedEnumValue[$scope.selectedValueProperty]},setInternalValue=function(newValue){var internalValue=$scope.multiple?[]:"";if(isNull(newValue))return void($scope.internalValue=internalValue);internalValue=$scope.multiple?null===newValue||void 0===newValue?[]:Array.isArray(newValue)?newValue:"string"==typeof newValue?_.map(newValue.split(","),function(i){return i.trim()}):_.map(newValue.toString().split(","),function(i){return i.trim()}):newValue,$scope.enumSelectOptions&&Array.isArray($scope.enumSelectOptions)&&(internalValue=Array.isArray(internalValue)?internalValue.map(function(val){return findValue(val)||val}):findValue(internalValue)||internalValue),$scope.internalValue=internalValue};setInternalValue($scope.selectedValue),$scope.$watch("selectedValue",function(newVal){setInternalValue(newVal)}),$scope.enumType&&enumService.GetEnumValues($scope.enumType).then(function(result){var enumSelectOptions=limitEnumOptions(result);$scope.includeUndefined||_.remove(enumSelectOptions,function(option){return"Undefined"===option.StringValue||"Udefinert"===option.StringValue}),!$scope.enumType||"prefix"!==$scope.enumType.toLowerCase()&&"documentationcontext"!==$scope.enumType.toLowerCase()||enumSelectOptions.sort(function(a,b){return a.TranslatedValueb.TranslatedValue?1:0}),$scope.enumSelectOptions=enumSelectOptions.map(function(opt){return{Value:opt.Value,StringValue:opt.StringValue,TranslatedValue:opt.TranslatedValue}}),setInternalValue($scope.selectedValue)})}angular.module("Plania").directive("plEnumDropdown",function($compile){return{restrict:"E",scope:{enumType:"=enumType",selectedValue:"=selectedValue",selectedValueProperty:"=selectedValueProperty",limitEnumOptions:"=limitEnumOptions",includeUndefined:"=includeUndefined",multiple:"=multiple",onChange:"=onChange",ngDisabled:"=ngDisabled",disableSearch:"=disableSearch",placeholder:"=placeholder"},controller:["$scope","EnumService","$localStorage",controller],templateUrl:"app/common/directives/views/plEnumDropdown.html",compile:function(element,attrs){var select=element.find("select");select&&attrs.multiple&&select.attr("multiple","true")}}})}(),function(){angular.module("Plania").directive("plFieldrule",["$animate","$localStorage","RegisteredFieldService","Repository",function($animate,$localStorage,registeredFieldService,repository){return{restrict:"A",scope:{fieldRule:"=plFieldrule",customRule:"=customRule",ignoreViewMode:"=ignoreViewMode",onGetValidityRules:"=onGetValidityRules"},link:function(scope,element,attrs){var isViewMode=function(){return!scope.ignoreViewMode&&(scope.$parent&&scope.$parent.viewMode)},applyRule=function(fieldRule){if(fieldRule.Hidden||fieldRule.ExternallyHidden&&$localStorage.userData.isExternalUser?$animate.addClass(element,"ng-hide"):element.hasClass("ng-hide")&&$animate.removeClass(element,"ng-hide"),fieldRule.Mandatory){var labelElement=element.find("label");if(labelElement.length>0)isViewMode()?$animate.removeClass(labelElement,"mandatory"):$animate.addClass(labelElement,"mandatory");else{var cardElement=element.find("h2");cardElement&&cardElement.length>0&&(isViewMode()?$animate.removeClass(cardElement,"mandatory"):$animate.addClass(cardElement,"mandatory"))}}if(fieldRule.MaxLength&&fieldRule.MaxLength>0){var inputLengthElement=element.find("input");inputLengthElement&&inputLengthElement.length>0&&inputLengthElement.attr("maxlength",fieldRule.MaxLength),inputLengthElement=element.find("textarea"),inputLengthElement&&inputLengthElement.length>0&&inputLengthElement.attr("maxlength",fieldRule.MaxLength)}if(fieldRule.Disabled&&!isViewMode()){var inputElement=element.find("input");inputElement&&inputElement.length>0&&inputElement.attr("disabled","disabled"),inputElement=element.find("textarea"),inputElement&&inputElement.length>0&&inputElement.attr("disabled","disabled"),inputElement=element.find("select"),inputElement&&inputElement.length>0&&inputElement.attr("disabled","disabled").trigger("chosen:updated")}},checkFieldrule=function(){if(scope.customRule)return void applyRule(scope.customRule);scope.fieldRule&®isteredFieldService.getFieldRuleByEntityAndColumn(scope.fieldRule).then(function(fieldRule){applyRule(scope.onGetValidityRules?scope.onGetValidityRules(fieldRule):fieldRule)},function(error){console.log(error)})};scope.ignoreViewMode||scope.$watch("$parent.viewMode",function(newValue,oldValue){newValue!==oldValue&&checkFieldrule()}),scope.$watch("$parent.modelDto.dataOwner",function(newValue,oldValue){newValue!==oldValue&&checkFieldrule()}),checkFieldrule()}}}])}(),function(){angular.module("Plania").directive("plFieldruleVisbility",["$animate","$localStorage","RegisteredFieldService","Repository",function($animate,$localStorage,registeredFieldService,repository){return{restrict:"A",scope:{fieldRules:"=plFieldruleVisbility",plFieldRuleMode:"=plFieldRuleMode"},link:function(scope,element,attrs){var isVisible=function(fieldRule){return!(fieldRule.Hidden||fieldRule.ExternallyHidden&&$localStorage.userData.isExternalUser)},applyVisibilityRules=function(visibleRules){scope.plFieldRuleMode&&"all"===scope.plFieldRuleMode.toLowerCase()?_.every(visibleRules)?element.hasClass("ng-hide")&&$animate.removeClass(element,"ng-hide"):$animate.addClass(element,"ng-hide"):_.some(visibleRules)?element.hasClass("ng-hide")&&$animate.removeClass(element,"ng-hide"):$animate.addClass(element,"ng-hide")},checkFieldrule=function(){if(scope.fieldRules&&0!==scope.fieldRules.length){var visibleRules=[],nrOfRuns=0;scope.fieldRules.forEach(function(fieldRule){registeredFieldService.getFieldRuleByEntityAndColumn(fieldRule).then(function(fieldRule){nrOfRuns++;var visible=isVisible(scope.onGetValidityRules?scope.onGetValidityRules(fieldRule):fieldRule);visibleRules.push(visible),nrOfRuns===scope.fieldRules.length&&applyVisibilityRules(visibleRules)},function(error){nrOfRuns++,visibleRules.push(!0),nrOfRuns===scope.fieldRules.length&&applyVisibilityRules(visibleRules),console.log(error)})})}};scope.$watch("$parent.viewMode",function(newValue,oldValue){newValue!==oldValue&&checkFieldrule()}),scope.$watch("$parent.modelDto.dataOwner",function(newValue,oldValue){newValue!==oldValue&&checkFieldrule()}),checkFieldrule()}}}])}(),function(){function controller($scope,constants){$scope.colors=constants.defaultLikertScaleColors}angular.module("Plania").directive("plLikertScale",function(){return{restrict:"E",scope:{ngModel:"="},controller:["$scope","Constants",controller],template:''}})}(),function(){angular.module("Plania").directive("plMaxLength",["$animate","$localStorage","RegisteredFieldService","Repository",function($animate,$localStorage,registeredFieldService,repository){return{restrict:"A",scope:{plMaxLength:"=",ignoreViewMode:"="},link:function(scope,element,attrs){var applyRule=function(fieldRule){if(fieldRule.MaxLength&&fieldRule.MaxLength>0){var inputLengthElement=element.find("input");inputLengthElement&&inputLengthElement.length>0&&inputLengthElement.attr("maxlength",fieldRule.MaxLength),inputLengthElement=element.find("textarea"),inputLengthElement&&inputLengthElement.length>0&&inputLengthElement.attr("maxlength",fieldRule.MaxLength)}};!function(){scope.plMaxLength&®isteredFieldService.getFieldRuleByEntityAndColumn(scope.plMaxLength).then(function(plMaxLength){applyRule(scope.onGetValidityRules?scope.onGetValidityRules(plMaxLength):plMaxLength)},function(error){repository.showError(error)})}()}}}])}(),function(){function controller($scope,colorService){$scope.selected="",$scope.colors=colorService.getRainbowPalette(),$scope.selectColor=function(color){if(!color)return void($scope.ngModel="");$scope.ngModel=($scope.useHex?color.hexColor:color.name).toLowerCase()};var updateSelectedValue=function(){if(!$scope.ngModel)return void($scope.selected="");var found=$scope.colors.find(function(color){return!(!$scope.useHex||color.hexColor!==$scope.ngModel.toLowerCase())||color.name===$scope.ngModel.toLowerCase()});$scope.selected=found?found.name:""};updateSelectedValue(),$scope.$watch("ngModel",function(){updateSelectedValue()})}angular.module("Plania").directive("plPaletteSelect",[function(){return{restrict:"E",require:"ngModel",scope:{ngModel:"=",ngDisabled:"=",useHex:"="},controller:["$scope","ColorService",controller],template:'
    '}}])}(),function(){angular.module("Plania").directive("plPrintExcelListDirective",function(){return{restrict:"E",scope:{domainName:"=domainName",table:"=table",selectedListSetup:"=selectedListSetup"},controller:["$scope","Repository","$window","TranslationService","config","$rootScope",printController],replace:!0,templateUrl:"app/common/directives/views/plPrintExcelListDirective.html"}});var printController=function($scope,repository,$window,translationService,config,$rootScope){$scope.options=[],$scope.canExportToExcel=repository.authService.getUserData().canExportToExcel,$scope.dropdownMenu=new function(){var me=this;this.addDefaultPrintOptions=function(options){options.push({text:translationService.translate("web-printExcelList-exportCurrentPageToExcel","Last ned gjeldende side som excel fil"),onClick:function(){$scope.printToExcel()}}),$scope.table.total()>$scope.table.count()&&options.push({text:translationService.translate("web-printExcelList-exportEveryPageToExcel","Last ned alle sider som excel fil"),onClick:function(){$scope.printToExcel(!0)}})},this.updateOptions=function(){var options=[];if($scope.canExportToExcel){var getOptions=me[$scope.domainName];getOptions&&getOptions(options),me.addDefaultPrintOptions(options),$scope.options=options}}},$scope.toggled=function(open){open&&$scope.dropdownMenu.updateOptions()},$scope.printToExcel=function(getAll){if($scope.canExportToExcel){var url=config.baseUrlApi+"exportExcel?prefix="+$scope.domainName,tmpfilter=repository.getFilter($scope.table.filter());tmpfilter.PropertyFilter||(tmpfilter.PropertyFilter=[]),$scope.selectedListSetup.Columns.forEach(function(col){col.Filter&&(tmpfilter.PropertyFilter=tmpfilter.PropertyFilter.concat(col.Filter))}),tmpfilter.PropertyFilter&&(tmpfilter.PropertyFilter=repository.GetKeywordFilters(tmpfilter.PropertyFilter),_.remove(tmpfilter.PropertyFilter,function(f){return"@GuidCurrentBuilding"===f.Value}));var columns=[];if($scope.selectedListSetup.VisibleColumns.forEach(function(col){columns.push({Property:col.Property,PropertyType:col.PropertyType,Title:col.Title})}),url+="&access_token="+repository.authService.getPlaniaToken().access,url+="&page="+($scope.table.page()-1),url+=getAll?"&pageSize=-1":"&pageSize="+$scope.table.count(),url+="&sorting="+JSON.stringify($scope.table.sorting()),url+="&filter="+encodeURIComponent(JSON.stringify(tmpfilter)),url+="&webListViews="+angular.toJson(columns),url+="&webListTitle="+$scope.selectedListSetup.Id,url+=repository.getUrlParameters("&"),url.length>=8e3)return void swal(translationService.translate("web-printExcelList-swal-urlTooLong-title","Feil ved eksport"),translationService.translate("web-printExcelList-swal-urlTooLong-text","Det er for mange kolonner, eller for komplisert filtre for å kunne eksportere til excel."),"error");$window.open(url,"_self")}}}}(),function(){angular.module("Plania").directive("plShowMore",[function(){return{restrict:"AE",replace:!0,scope:{text:"=",textLimit:"=",rowLimit:"="},templateUrl:"app/common/directives/views/plShowMoreDirective.html",link:function(scope,element,attrs){scope.textLimit||(scope.textLimit=500),scope.rowLimit||(scope.rowLimit=10);var fallbackTextLimit=angular.copy(scope.textLimit),fallbackRowLimit=angular.copy(scope.rowLimit);scope.showMoreClicked=!1,scope.shouldShowMoreButton=function(){return scope.text&&scope.text.length>scope.textLimit||scope.numberOfLineBreaks(scope.text)>scope.rowLimit&&scope.rowLimit>0},scope.showMore=function(){scope.textLimit=scope.text.length,scope.rowLimit=0,scope.showMoreClicked=!0},scope.showLess=function(){scope.textLimit=fallbackTextLimit,scope.rowLimit=fallbackRowLimit,scope.showMoreClicked=!1,planiaUtils.isElementInViewport(element)||window.scrollTo(0,element[0].offsetTop-100)},scope.numberOfLineBreaks=function(text){return text?(text.match(/\r\n|\r|\n|
    /g)||[]).length:0}}}}])}(),function(){angular.module("Plania").directive("plWizardStepper",function(){return{restrict:"E",scope:{steps:"=steps",currentStep:"=currentStep",onStepClick:"=onStepClick",completedStepIndex:"=completedStepIndex"},controller:["$scope","Repository","$window","TranslationService","config",controller],templateUrl:"app/common/directives/views/plWizardStepper.html"}});var controller=function($scope,repository,$window,translationService,config){$scope.stepClick=function(step){step.stepIndex!==$scope.currentStep.stepIndex&&(step.onClick&&"function"==typeof step.onClick?step.onClick(step):$scope.onStepClick&&"function"==typeof $scope.onStepClick&&$scope.onStepClick(step))},$scope.stepFilter=function(step){return!step.hidden}}}(),function(){var app=angular.module("Plania");app.directive("suggestion",function(){return{restrict:"A",require:"^autocomplete",link:function(scope,element,attrs,autoCtrl){element.bind("mouseenter",function(){autoCtrl.setIndex(attrs.index)})}}}),app.directive("autocomplete",function(){return{restrict:"E",scope:{searchParam:"=ngModel",suggestions:"=data",ngDisabled:"=ngDisabled",onType:"=onType",onSelect:"=onSelect",singleValue:"=isSingleValue",descriptionModel:"=descriptionModel",filter:"=filter",validation:"=validation",validate:"=validate",active:"=active",floatingLabel:"=floatingLabel",createHandler:"=createHandler",displayColumnsHandler:"=displayColumnsHandler",fillIfMandatory:"=fillIfMandatory",defaultSort:"=defaultSort"},controller:["$scope","$timeout","AutoCompleteService","$modal","TranslationService","Repository","$log","RegisteredFieldService","$localStorage",planiaAutoCompleteController],link:linkFunction,templateUrl:"app/common/directives/views/planiaAutocomplete.html"}});var planiaAutoCompleteController=function($scope,$timeout,autoCompleteService,$modal,translationService,repository,$log,registeredFieldService,$localStorage){function fillIfMandatory(){registeredFieldService.getFieldRuleByEntityAndColumn($scope.fillIfMandatory).then(function(fieldrule){fieldrule&&fieldrule.Mandatory&&tryFillSingleResult()})}function tryFillSingleResult(){getService()(getParams()).then(function(result){result.dropdown&&1===result.dropdown.length&&($scope.completing=!1,$scope.select(result.dropdown[0]))})}function addSearchParamWatcher(){initializing=!0,searchParamWatcher=$scope.$watch("searchParam",function(newValue,oldValue){if(initializing)return void(initializing=!1);newValue||(newValue=""),oldValue||(oldValue=""),oldValue!==newValue&&!1!==$scope.active&&($scope.checkValid(),$scope.searchParam?($scope.completing=!0,$scope.searchFilter=$scope.searchParam,$scope.selectedIndex=-1,autoCompleteResult(getService())):($scope.searchParam="",$scope.searchFilter="",$scope.select(null),$scope.setIndex(-1)))})}$scope.selectedIndex=-1,$scope.modalSize="md";var initializing=!1;$scope.setIndex=function(i){$scope.selectedIndex=parseInt(i)},this.setIndex=function(i){$scope.setIndex(i),$scope.$apply()},$scope.getIndex=function(i){return $scope.selectedIndex},$scope.completing=!1,$scope.apiDataType=null;var getParams=function(){var params;return $scope.filter&&"function"==typeof $scope.filter&&(params=$scope.filter($scope.onType)),params||(params={}),params.dropdown=$scope.searchParam,params.onType=$scope.onType,params},autoCompleteResult=function(service){service(getParams()).then(function(result){if($scope.suggestions=result.dropdown,$scope.totalCount=result.totalCount,1===result.dropdown.length&&"postal"===$scope.onType)result.dropdown[0].id!==$scope.searchParam?$scope.completing=!0:$scope.select($scope.suggestions[0]);else if("controlListLogItem"===$scope.onType)_.some($scope.suggestions,{id:$scope.searchParam.toLowerCase().replace("\n","")})&&($scope.completing=!1);else if(1===result.dropdown.length){var dropdown=$scope.suggestions[0],id=dropdown.id.toString().toLowerCase(),description=dropdown.description?dropdown.description.toLowerCase():null,strippedSearchParam=$scope.searchParam.toLowerCase();id!==strippedSearchParam&&description!==strippedSearchParam&&getSearchParamValue(dropdown).toLowerCase()!==strippedSearchParam||($scope.completing=!1,$scope.select($scope.suggestions[0]))}}).catch(function(error){repository.growl(error,"danger")})},lookupId=translationService.translate("autocomplete-lookup-header-id","Id"),displayColumns=null;$scope.openDialog=function(){var params=getParams();params.dropdown="",$scope.isValid=!0,$modal.open({templateUrl:"app/common/views/tableModal.html",controller:"TableModalController",size:$scope.modalSize,resolve:{content:function(){return{header:translationService.translate("web-lookup-title","Oppslagsliste"),idTitle:lookupId,displayColumns:$scope.displayColumnsHandler?$scope.displayColumnsHandler():displayColumns,data:getService(),params:params,singleValue:$scope.singleValue,onType:$scope.onType,createHandler:$scope.createHandler,defaultSort:$scope.defaultSort}}}}).result.then(function(selected){$scope.select(selected),setTimeout($scope.checkValid(),200)},function(){setTimeout(function(){$scope.checkValid(),$scope.isValid||($scope.showError=!0)},200)})};var getService=function(){switch($scope.onType.toLowerCase()){case"estate":return autoCompleteService.estates;case"area":return autoCompleteService.areas;case"article":return autoCompleteService.article;case"accounting0":case"accounting1":case"accounting2":case"accounting3":case"accounting4":return autoCompleteService.accounting;case"building":return autoCompleteService.buildings;case"buildingcategory":return autoCompleteService.buildingCategory;case"component":return autoCompleteService.component;case"componentcategory":return autoCompleteService.componentCategory;case"contactperson":return autoCompleteService.contactPerson;case"costcenter":return autoCompleteService.costCenter;case"rentalgroup":return autoCompleteService.rentalGroup;case"constructiontype":return autoCompleteService.constructionType;case"deliveryterm":return autoCompleteService.deliveryTerm;case"workorderdescription":return lookupId=translationService.translate("autocomplete-lookup-header-description","Beskrivelse"),autoCompleteService.workOrderDescriptions;case"periodictaskdescription":return lookupId=translationService.translate("autocomplete-lookup-header-description","Beskrivelse"),autoCompleteService.periodicTaskDescriptions;case"equipment":return"SvvTunnel"!==$localStorage.generalOptions.CustomerId&&"Fylkeskommuner"!==$localStorage.generalOptions.CustomerId||(displayColumns=[{Property:"Id",Title:translationService.translate("autocomplete-lookup-header-id","Id")},{Property:"Description",Title:translationService.translate("autocomplete-lookup-header-description","Beskrivelse")},{Property:"Text20",Title:translationService.translate("autocomplete-lookup-header-equipment-svv-text20","Driftsmerking")}]),autoCompleteService.equipments;case"equipmentcategories":case"equipmentcategory":return autoCompleteService.equipmentCategories;case"paymentterm":return autoCompleteService.paymentTerm;case"invoicingterm":return autoCompleteService.invoicingTerm;case"contracttype":return autoCompleteService.contractType;case"contractcategory":return autoCompleteService.contractCategory;case"person":case"responsibleperson":return lookupId=translationService.translate("autocomplete-lookup-header-person","Navn"),$scope.apiDataType="person",autoCompleteService.persons;case"purchaseorder":return autoCompleteService.purchaseOrder;case"purchaseorderitem":return autoCompleteService.purchaseOrderItem;case"report":return autoCompleteService.report;case"resourceresponsible":return lookupId=translationService.translate("autocomplete-lookup-header-person","Navn"),autoCompleteService.resourceResponsibles;case"supplier":return autoCompleteService.suppliers;case"resourcegroup":return autoCompleteService.resourceGroups;case"cause":return autoCompleteService.cause;case"cleaningquality":return autoCompleteService.cleaningQuality;case"cleaningtask":return autoCompleteService.cleaningTask;case"cleaningtype":return autoCompleteService.cleaningType;case"department":return autoCompleteService.department;case"document":return autoCompleteService.document;case"documentcategory":return autoCompleteService.documentCategory;case"documenttype":return autoCompleteService.documentType;case"drawing":return autoCompleteService.drawing;case"priority":return autoCompleteService.priority;case"account":return autoCompleteService.account;case"postal":return displayColumns=[{Property:"ZipCode",Title:translationService.translate("autocomplete-lookup-header-postal-zipcode","Postnummer")},{Property:"PostalArea",Title:translationService.translate("autocomplete-lookup-header-postal-PostalArea","Poststed")},{Property:"MunicipalityName",Title:translationService.translate("autocomplete-lookup-header-postal-MunicipalityName","Kommune")},{Property:"County",Title:translationService.translate("autocomplete-lookup-header-postal-County","Fylke")}],autoCompleteService.postal;case"service":return autoCompleteService.service;case"supplierlineofbusiness":return autoCompleteService.supplierLineOfBusiness;case"areacategory":return autoCompleteService.areaCategory;case"areatype":return autoCompleteService.areaType;case"status":return autoCompleteService.statusCategory;case"activitycategory":return autoCompleteService.activityCategory;case"organization":return autoCompleteService.organization;case"organizationunit":return autoCompleteService.organizationUnit;case"organizationsection":return autoCompleteService.organizationSection;case"personrole":return autoCompleteService.PersonRole;case"deviationtype":return autoCompleteService.deviationType;case"hourtype":return autoCompleteService.hourType;case"checklist":return autoCompleteService.checklist;case"estatecategory":return autoCompleteService.EstateCategory;case"dataowner":return autoCompleteService.dataOwner;case"entitypermissionprofile":return autoCompleteService.entityPermissionProfile;case"mobilemenuprofile":return autoCompleteService.mobileMenuProfile;case"buildingselection":return autoCompleteService.buildingSelection;case"systemadministrator":return displayColumns=[{Property:"Username",Title:translationService.translate("web-user-username")},{Property:"RealName",Title:translationService.translate("web-user-realname")}],$scope.apiDataType="user",autoCompleteService.systemAdministrator;case"usergroup":return lookupId=translationService.translate("autocomplete-lookup-header-userGroup","Navn"),autoCompleteService.userGroup;case"customer":return autoCompleteService.customer;case"customergroup":return autoCompleteService.customerGroup;case"customercategory":return autoCompleteService.customerCategory;case"customerlineofbusiness":return autoCompleteService.customerLineOfBusiness;case"activitygroup":return autoCompleteService.activityGroup;case"entityattribute":return autoCompleteService.entityAttribute;case"purchaseorderform":return autoCompleteService.purchaseOrderForm;case"paymentorderform":return autoCompleteService.paymentOrderForm;case"sparepart":return autoCompleteService.sparePart;case"workorder":return autoCompleteService.workOrder;case"consumable":return autoCompleteService.consumable;case"region":return autoCompleteService.region;case"controllistlogitem":return autoCompleteService.controlListLogItem;case"projecttype":return autoCompleteService.projectType;case"projectcategory":return autoCompleteService.projectCategory;case"project":return autoCompleteService.project;case"equipmentoperatinghourtype":return autoCompleteService.equipmentOperatingHourType;case"referencedata":case"buildingtype":case"businessunit":case"deviationclassification":return autoCompleteService.referenceData;case"referencetype":return autoCompleteService.referenceType;case"periodictask":return autoCompleteService.periodicTask;case"workordertemplate":return autoCompleteService.workOrderTemplate;case"webmenu":return $scope.modalSize="lg",$scope.defaultSort||($scope.defaultSort={Name:"asc"}),displayColumns=[{Property:"Name",Title:translationService.translate("web-webmenu-name")},{Property:"Description",Title:translationService.translate("web-webmenu-description")},{Property:"Context",Title:translationService.translate("web-webmenu-context")}],autoCompleteService.webmenu}return""};getService();var getSearchParamValue=function(suggestion){return $scope.singleValue?suggestion.id:"postal"===$scope.onType?suggestion.id:suggestion.description?suggestion.id+" - "+suggestion.description:suggestion.id},getGuid=function(){return $scope.onSelect&&"function"!=typeof $scope.onSelect?$scope.onSelect:$scope.validation},getCaptionTextIfNull=function(){if(!$scope.searchParam){var guid=getGuid();if(guid){var apiDataType=$scope.apiDataType?$scope.apiDataType:$scope.onType,apiData=repository.apiData.getApiDataByName(apiDataType);apiData?repository.getSingle(apiData.url,guid).then(function(result){searchParamWatcher(),$scope.searchParam=result.Data.Caption,addSearchParamWatcher()}):$log.warn("Could not find apiData for "+$scope.onType+". Check why object is missing in getApiDataByName")}}};$scope.checkValid=function(){$scope.onSelect?"function"==typeof $scope.onSelect?$scope.isValid=!!$scope.validation&&$scope.validation.length>0:$scope.isValid=$scope.onSelect.length>0:$scope.isValid=!!$scope.validation&&$scope.validation.length>0},$scope.$watch("validation",function(newValue,oldValue){newValue&&(newValue!==oldValue&&($scope.checkValid(),$scope.showError=!$scope.isValid&&$scope.searchParam&&$scope.searchParam.length>0),$scope.active&&getCaptionTextIfNull())}),$scope.$watch("validate",function(newValue,oldValue){newValue!==oldValue&&newValue&&($scope.checkValid(),$scope.validate=!1,$scope.showError=!$scope.isValid&&$scope.searchParam&&$scope.searchParam.length>0)});var searchParamWatcher=function(){},forceInitActive=!$scope.fillIfMandatory;$scope.$watch("active",function(newValue,oldValue){newValue===oldValue&&forceInitActive||(forceInitActive=!0,!0===newValue?(addSearchParamWatcher(),getCaptionTextIfNull(),$scope.fillIfMandatory&&!$scope.completing&&fillIfMandatory()):$scope.completing=!1)}),addSearchParamWatcher(),$scope.select=function(suggestion){searchParamWatcher(),suggestion?($scope.searchParam=getSearchParamValue(suggestion),$scope.searchFilter=suggestion,"function"==typeof $scope.onSelect?$scope.onSelect(suggestion.object):$scope.onSelect=suggestion.guid,$scope.descriptionModel&&($scope.descriptionModel=suggestion.description),$scope.checkValid()):($scope.onSelect&&("function"==typeof $scope.onSelect?$scope.onSelect(null):$scope.onSelect=""),$scope.descriptionModel&&($scope.descriptionModel="")),$scope.completing=!1,$scope.setIndex(-1),addSearchParamWatcher()};var key={left:37,up:38,right:39,down:40,enter:13,esc:27,tab:9};$scope.keydown=function($event){if($scope.suggestions){var keycode=$event.keyCode||$event.which,l=$scope.suggestions.length;switch(keycode){case key.esc:$scope.select(),$scope.setIndex(-1);break;case key.up:if(index=$scope.getIndex()-1,index<-1)index=l-1;else if(index>=l){index=-1,$scope.setIndex(index);break}$scope.setIndex(index);break;case key.down:if(index=$scope.getIndex()+1,index<-1)index=l-1;else if(index>=l){index=-1,$scope.setIndex(index);break}$scope.setIndex(index);break;case key.left:break;case key.right:case key.tab:case key.enter:index=$scope.getIndex(),-1!==index&&$scope.select($scope.suggestions[index]),$scope.setIndex(-1);break;default:return}}}},linkFunction=function(scope,element,attrs){var attr="";scope.attrs={class:"",id:"",inputclass:"",inputid:""};for(var a in attrs)attr=a.replace("attr","").toLowerCase(),0===a.indexOf("attr")&&(scope.attrs[attr]=attrs[a]);attrs.clickactivation&&(element[0].onclick=function(e){scope.searchParam||(scope.completing=!0,scope.$apply())}),element[0].addEventListener("blur",function(e){scope.completing&&scope.suggestions&&1===scope.suggestions.length&&scope.select(scope.suggestions[0]),setTimeout(function(){scope.setIndex(-1),"postal"===scope.onType?scope.showError=!1:(void 0===scope.isValid&&scope.checkValid(),scope.showError=!scope.isValid&&scope.searchParam&&scope.searchParam.length>0),scope.$apply()},200)},!0)}}(),function(){angular.module("Plania").directive("plAutofocus",["$timeout",function($timeout){return{restrict:"A",link:function($scope,$element){$timeout(function(){$element[0].focus()})}}}])}(),function(){"use strict";function planiaDecimal($filter){return{restrict:"A",require:"ngModel",scope:{maxDecimals:"=maxDecimals"},link:function(scope,element,attrs,ngModelController){function updateView(hasFocus){if(ngModelController.$modelValue){var displayValue=hasFocus?ngModelController.$modelValue:$filter("number")(ngModelController.$modelValue,scope.maxDecimals);rawElement.value=displayValue}}if(void 0!==scope.maxDecimals&&scope.maxDecimals>=0){var rawElement=element[0];element.on("focus",updateView.bind(null,!0)),element.on("blur",updateView.bind(null,!1)),scope.$watch("viewMode",function(){updateView(!1)});var loadListener=scope.$watch(attrs.ngModel,function(newValue){if(void 0!==newValue&&!Number.isNaN(newValue)){try{updateView($(element).is(":focus"))}catch(ex){}loadListener()}})}ngModelController.$parsers.push(function(input){if(!input)return input;var transformedInput=input.replace(/[^\d.,-]/g,"");transformedInput!==input&&(ngModelController.$setViewValue(transformedInput),ngModelController.$render());var ret=transformedInput.toString().trim().replace(",",".");return parseFloat(ret)}),ngModelController.$formatters.push(function(input){return input?input.toString().replace(".",","):null})}}}angular.module("Plania").directive("planiaDecimal",["$filter",planiaDecimal])}(),angular.module("Plania").directive("planiaEnter",[function(){return function(scope,element,attrs){element.bind("keydown keypress",function(event){13===event.which&&(scope.$apply(function(){scope.$eval(attrs.planiaEnter)}),event.preventDefault())})}}]),function(){angular.module("Plania").directive("plFileTypeIcon",function(){return{restrict:"E",scope:{filePath:"=filePath"},link:function(scope,element,attrs){if(!scope.filePath)return void(scope.iconClass="fa fa-file-text-o");switch(scope.filePath.split(".").pop().toLowerCase()){case"doc":case"docx":scope.iconClass="far fa-file-word c-blue";break;case"pdf":scope.iconClass="far fa-file-pdf c-red";break;case"txt":scope.iconClass="far fa-file-text c-gray";break;case"wma":case"mp3":scope.iconClass="far fa-file-audio c-purple";break;case"csv":case"xls":case"xlsx":scope.iconClass="far fa-file-excel c-green";break;case"zip":scope.iconClass="far fa-file-archive c-brown";break;case"jpg":case"jpeg":case"png":scope.iconClass="far fa-file-image c-teal";break;case"eml":scope.iconClass="far fa-envelope c-blue";break;case"ppt":case"pptx":scope.iconClass="far fa-file-powerpoint c-teal";break;case"mp4":scope.iconClass="far fa-play-circle c-deeporange";break;default:scope.iconClass="far fa-file-text"}0===scope.filePath.indexOf("http")&&(scope.iconClass="fa fa-link-simple c-blue")},template:''}})}(),function(){function controller($scope,$modal,$rootScope,repository,translationService,$localStorage,listService,$state,listCompressionService){$scope.userData=repository.authService.getUserData(), $scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.WebListView,!1),$scope.restrictDefaultViewChange=!repository.authService.hasEditAccess("UserXWebListView"),$scope.runningAction=!1,$scope.isSelectedListSetupOverridenByWebMenu=!1,$scope.isSelectedListSetupOverridenByUrlFilter=!1;var selectedListSetupWatcher=$scope.$watch("selectedListSetupBinding",function(newVal,oldVal){if(newVal!==oldVal&&newVal){var filterString=repository.location.search().filter;if($scope.isSelectedListSetupOverridenByWebMenu||$scope.isSelectedListSetupOverridenByUrlFilter)$scope.isSelectedListSetupOverridenByWebMenu=!1,$scope.isSelectedListSetupOverridenByUrlFilter=!1,selectedListSetupWatcher();else if($rootScope.navigation&&$rootScope.navigation.params&&$rootScope.navigation.params.menuGuid)menuParams=repository.getMenuParameters($rootScope.navigation.params.menuGuid),menuParams&&menuParams.selectedWebListView&&menuParams.selectedWebListView.Guid===newVal.Guid&&($scope.isSelectedListSetupOverridenByWebMenu=!0);else if(filterString)try{var urlFilter=listCompressionService.decodeListUri(filterString);urlFilter&&urlFilter.selectedListSetup&&urlFilter.selectedListSetup.Guid===newVal.Guid&&($scope.isSelectedListSetupOverridenByUrlFilter=!0)}catch(e){}}});$scope.$watch("listTable.filter().searchString",function(newValue,oldValue){newValue!==oldValue&&($localStorage.listFilters||($localStorage.listFilters={}),$localStorage.listFilters[$scope.selectedListSetupBinding.EntityType]=newValue)}),$scope.$watch("listTable.filter().ActivityStatus",function(newValue,oldValue){if(newValue!==oldValue){var prefix=$scope.prefix;switch(prefix||(prefix=$state.params.entityData.prefix),prefix){case"WorkOrder":$localStorage.workOrderActivityStatus=newValue;break;case"Project":"projectTemplate.list"!==$state.current.name&&($localStorage.projectActivityStatus=newValue)}}}),$scope.getSelectDefaultViewTooltipText=function(){if($scope.selectedListSetupBinding){var tooltipText="";return $scope.selectedListSetupBinding.IsDefaultView?(tooltipText+=translationService.translate("web-planiaListToolbar-tooltip-isDefaultView","Dette er din standard visning.")+"\n",tooltipText+=translationService.translate("web-planiaListToolbar-tooltip-removeDefaultView","Trykk for å tilbakestille til Plania Standard.")+"\n"):tooltipText+=translationService.translate("web-planiaListToolbar-tooltip-addDefaultView","Sett som standardvisning.")+"\n",$scope.isSelectedListSetupOverridenByWebMenu&&!$scope.selectedListSetupBinding.IsDefaultView&&(tooltipText+=translationService.translate("web-planiaListToolbar-tooltip-selectedListSetupOverridenByWebMenu","Visning ble overstyrt av webmeny.")),$scope.isSelectedListSetupOverridenByUrlFilter&&!$scope.selectedListSetupBinding.IsDefaultView&&(tooltipText+=translationService.translate("web-planiaListToolbar-tooltip-selectedListSetupOverridenByUrlFilter","Visning ble overstyrt av systemet.")),tooltipText}},$scope.setSelectedListSetupAsDefaultView=function(){if($scope.selectedListSetupBinding){$scope.runningAction=!0;var selectedListCopy=_.cloneDeep($scope.selectedListSetupBinding);selectedListCopy.Columns=[],delete selectedListCopy.VisibleColumns,repository.runAction(repository.apiData.webListView.url+"setDefaultView/",selectedListCopy).then(function(result){$scope.runningAction=!1,$scope.isSelectedListSetupOverridenByWebMenu=!1,$scope.isSelectedListSetupOverridenByUrlFilter=!1,result&&($scope.selectedListSetupBinding.IsDefaultView=result.IsDefaultView,$scope.listOptions.forEach(function(option){"Plania standard"===result.Id&&option.Id===result.Id?option.IsDefaultView=result.IsDefaultView:result.Guid===option.Guid?option.IsDefaultView=result.IsDefaultView:option.IsDefaultView=!1}),_.every($scope.listOptions,{IsDefaultView:!1})&&($scope.listOptions[0].IsDefaultView=!0))},function(error){repository.growl(error,"danger"),$scope.runningAction=!1})}},$scope.openListSetupModal=function(){var size=$scope.restrictEdit?"md":"lg";$modal.open({size:size,controller:"ListSetupModalController",templateUrl:"app/common/directives/views/editListSetupModal.html",resolve:{params:function(){return{listSetup:$scope.selectedListSetupBinding,hideFilters:!1}}}}).result.then(function(result){return"saved"===result||"ok"===result?($scope.listTable.$params.sorting=$scope.selectedListSetupBinding.Sorting,$scope.selectedListSetupBinding.Columns.forEach(function(column){"CleaningEstimateYear"!==column.Property&&"EstimateTimeYear"!==column.Property&&"NextCleaning"!==column.Property||(column.SortingDisabled=!0)}),$scope.selectedListSetupBinding.GroupBy?$scope.listTable.settings().groupBy=function(obj){var prefix=$scope.prefix;return prefix||(prefix=$state.params.entityData.prefix),listService.getGroupName(prefix,obj)}:$scope.listTable.settings().groupBy=null,$scope.selectedListSetupBinding.VisibleColumns=_.filter($scope.selectedListSetupBinding.Columns,function(c){return!c.Filter||!c.Filter.some(function(f){return f.Hidden})}),$scope.selectedListSetupBinding.IsPublicView?$scope.selectedListSetupBinding.isPublicViewText=translationService.translate("web-webListView-isPublicViewText-common","Felles"):$scope.selectedListSetupBinding.isPublicViewText=translationService.translate("web-webListView-isPublicViewText-personal","Personlig"),"Plania standard"!==$scope.selectedListSetupBinding.Id&&$scope.listOptions.forEach(function(option){option.Guid&&option.Guid===$scope.selectedListSetupBinding.Guid&&(option.IsDefaultView=$scope.selectedListSetupBinding.IsDefaultView,option.IsPublicView=$scope.selectedListSetupBinding.IsPublicView,option.isPublicViewText=$scope.selectedListSetupBinding.isPublicViewText,option.VisibleColumns=$scope.selectedListSetupBinding.VisibleColumns,option.Columns=$scope.selectedListSetupBinding.Columns,option.Id=$scope.selectedListSetupBinding.Id,option.Sorting=$scope.selectedListSetupBinding.Sorting,option.GuidDataOwner=$scope.selectedListSetupBinding.GuidDataOwner)}),void $scope.listTable.reload()):"deleted"===result?($scope.updateListView(null,!0),void $scope.listTable.reload()):"savedNew"===result?($scope.updateListView($scope.selectedListSetupBinding,!0),void $scope.listTable.reload()):void 0},function(){})}}angular.module("Plania").directive("plListToolbar",function(){return{restrict:"E",scope:{listTable:"=listTable",listOptions:"=listOptions",selectedListSetupBinding:"=selectedListSetupBinding",updateListView:"=updateListView",prefix:"=prefix",hideSettings:"=hideSettings",hideSearch:"=hideSearch"},controller:["$scope","$modal","$rootScope","Repository","TranslationService","$localStorage","ListService","$state","ListCompressionService",controller],link:function(scope,element,attrs){},templateUrl:"app/common/directives/views/planiaListToolbar.html"}})}(),function(){function planiaMapController($scope,repository,leafletData,$localStorage,$modal,translationService,constants,$rootScope,iconService){function getGisEntityFromModal(){$modal.open({controller:"CoordinateSelectionController",templateUrl:"app/common/directives/views/planiaMapCoordinateSelectionModal.html",resolve:{entity:function(){return $scope.entity}}}).result.then(function(response){if(response.useMapClick)$scope.showMap=!0,$scope.mapClickable=!0,setMapZoom(),$scope.$on("leafletDirectiveMap.click",function(event,args){if($scope.mapClickable){var newGisEntity={Coordinates:[{lat:args.leafletEvent.latlng.lat,lng:args.leafletEvent.latlng.lng}]};createGisEntity(newGisEntity),$scope.mapClickable=!1}});else if(response.lat&&response.lng){var newGisEntity={Coordinates:[{lat:response.lat,lng:response.lng}]};createGisEntity(newGisEntity)}else{if(!response.address)return;geoSearchProvider.GetLocations(response.address,function(data){if(data.length>0){var newGisEntity={Coordinates:[{lat:data[0].Y,lng:data[0].X}]};createGisEntity(newGisEntity)}else repository.showError("No result with given address: ",response.address)})}})}$scope.showMap=!1,$scope.directiveReady=!1,$scope.mapData={Norge:{lat:63.43,lng:10.4,zoom:3},defaults:{scrollWheelZoom:!1,zoom:1}},$scope.rootScope=$rootScope,window.plania={GoogleApiKey:$localStorage.generalOptions.GoogleApiKey};var geoSearchProvider=new L.GeoSearch.Provider.Google,entityInfos={};$scope.mapData.markers={},$scope.mapData.paths={},$scope.$watch("reload",function(newValue,oldValue){!0===newValue&&leafletData.getMap("editMap").then(function(map){map._onResize()})}),$scope.emptyMarkers=function(){return _.isEmpty($scope.mapData.markers)},$scope.shouldShowMap=function(){return(!_.isEmpty($scope.entityModel.GuidGisEntity)||!_.isEmpty($scope.gisEntity)||$scope.showMap)&&$rootScope.hasReadAccess("GisEntity")},$scope.setNewCoordinatesFromInput=function(){updateMarker(),setMapZoom(),repository.updateSingle(repository.apiData.gisEntity.url,$scope.gisEntity).then(function(){repository.growl("Koordinater oppdatert","info"),$scope.updateMode=!1})},$scope.$on("leafletDirectiveMarker.dragend",function(event,target){$scope.gisEntity.Coordinates[0].lat=target.model.lat,$scope.gisEntity.Coordinates[0].lng=target.model.lng,updateMarker(),repository.updateSingle(repository.apiData.gisEntity.url,$scope.gisEntity).then(function(){repository.growl("Koordinater oppdatert","info")})}),$scope.$watch("updateMode",function(newValue,oldValue){newValue!==oldValue&&(updateMarker(),$scope.gisEntity&&$scope.gisEntity.Guid&&($scope.mapData.markers[$scope.gisEntity.Guid.replace(/-/g,"")].draggable=newValue))});var updateMarker=function(){if($scope.gisEntity&&$scope.gisEntity.Guid){var marker=$scope.mapData.markers[$scope.gisEntity.Guid.replace(/-/g,"")];marker&&(marker.lat=$scope.gisEntity.Coordinates[0].lat,marker.lng=$scope.gisEntity.Coordinates[0].lng)}};$scope.toggleUpdateMode=function(){$scope.updateMode=!$scope.updateMode};var getMarker=function(guidGisEntity){repository.getSingle(repository.apiData.gisEntity.url,guidGisEntity).then(function(result){$scope.gisEntity=result.Data;var entityInfo=entityInfos[$scope.entity];if("marker"===entityInfo.displayType){var iconName=entityInfo.marker.icon,markerColor=entityInfo.marker.color;$scope.entityModel&&($scope.entityModel.EstateCategory&&($scope.entityModel.EstateCategory.Icon&&(iconName=$scope.entityModel.EstateCategory.Icon),$scope.entityModel.EstateCategory.Color&&(markerColor=$scope.entityModel.EstateCategory.Color)),$scope.entityModel.BuildingCategory&&($scope.entityModel.BuildingCategory.Icon&&(iconName=$scope.entityModel.BuildingCategory.Icon),$scope.entityModel.BuildingCategory.Color&&(markerColor=$scope.entityModel.BuildingCategory.Color)),$scope.entityModel.EquipmentCategory&&($scope.entityModel.EquipmentCategory.Icon&&(iconName=$scope.entityModel.EquipmentCategory.Icon),$scope.entityModel.EquipmentCategory.Color&&(markerColor=$scope.entityModel.EquipmentCategory.Color)));var marker={icon:iconService.getMapIcon(iconName),markerColor:markerColor,svg:markerColor&&markerColor.startsWith("#"),shape:entityInfo.marker.shape,prefix:"fa",type:"extraMarker",class:"test"};$scope.mapData.markers[$scope.gisEntity.Guid.replace(/-/g,"")]={icon:marker,weight:entityInfo.weight,lat:$scope.gisEntity.Coordinates?$scope.gisEntity.Coordinates[0].lat:void 0,lng:$scope.gisEntity.Coordinates?$scope.gisEntity.Coordinates[0].lng:void 0,focus:!0,draggable:$scope.updateMode},setMapZoom()}$localStorage.generalOptions.DrawPathsOnMap&&$scope.gisEntity.Coordinates.length>1&&($scope.mapData.paths[$scope.gisEntity.Guid.replace(/-/g,"")]={latlngs:$scope.gisEntity.Coordinates,opacity:.8,weight:6,color:"#2196f3"}),$scope.directiveReady=!0},function(error){repository.growl(error,"danger"),$scope.directiveReady=!0})},setMapZoom=function(){leafletData.getMap("editMap").then(function(map){var zoom;$scope.mapData.defaults.tileLayerOptions&&(zoom=$scope.mapData.defaults.tileLayerOptions.maxZoom-3),$scope.gisEntity&&$scope.gisEntity.Coordinates&&$scope.gisEntity.Coordinates.length>0?(zoom?map.setView(new L.latLng($scope.gisEntity.Coordinates[0].lat,$scope.gisEntity.Coordinates[0].lng),zoom):map.setView(new L.latLng($scope.gisEntity.Coordinates[0].lat,$scope.gisEntity.Coordinates[0].lng)),map.invalidateSize()):(map.setView(new L.latLng($scope.mapData.Norge.lat,$scope.mapData.Norge.lng),$scope.mapData.Norge.zoom),map._onResize())})};if($scope.$watch("entityModel",function(newValue,oldValue){newValue&&1!==Object.keys(newValue).length&&(newValue.GuidGisEntity?getMarker(newValue.GuidGisEntity):$scope.directiveReady=!0)}),$localStorage.generalOptions.MapSettings){var settings=JSON.parse($localStorage.generalOptions.MapSettings);settings.TileLayer||settings.TileLayerOptions||settings.GoogleApiKey||(settings.TileLayer=constants.availableMaps[0].mapData.TileLayer,settings.TileLayerOptions=constants.availableMaps[0].mapData.TileLayerOptions);var options={};settings.Options&&(settings.Options.Origin&&(options.origin=JSON.parse(settings.Options.Origin)),settings.Options.Resolution&&(options.resolutions=JSON.parse(settings.Options.Resolution))),$scope.mapData.defaults={tileLayer:settings.TileLayer,tileLayerOptions:settings.TileLayerOptions?JSON.parse(settings.TileLayerOptions):null},settings.CrsCode&&settings.Proj4Def&&options&&($scope.mapData.defaults.crs=new L.Proj.CRS(settings.CrsCode,settings.Proj4Def,options)),entityInfos=settings.entityInfo}$scope.mapData.defaults?$scope.mapData.defaults.scrollWheelZoom=!1:$scope.mapData.defaults={scrollWheelZoom:!1},$scope.addNewMarker=function(){var address="";if($scope.entityModel.Address&&$scope.entityModel.PostalCode&&$scope.entityModel.PostalArea&&(address=$scope.entityModel.Address+" "+$scope.entityModel.PostalCode+" "+$scope.entityModel.PostalArea),!address)return void getGisEntityFromModal();geoSearchProvider.GetLocations(address,function(data){if(data.length>0){var newGisEntity={Coordinates:[{lat:data[0].Y,lng:data[0].X}]};createGisEntity(newGisEntity)}else getGisEntityFromModal()})};var createGisEntity=function(newGisEntity){"estate"===$scope.entity&&(newGisEntity.GuidEstate=$scope.entityModel.Guid),"building"===$scope.entity&&(newGisEntity.GuidBuilding=$scope.entityModel.Guid),"equipment"===$scope.entity&&(newGisEntity.GuidEquipment=$scope.entityModel.Guid),"request"===$scope.entity&&(newGisEntity.GuidRequest=$scope.entityModel.Guid),"workOrder"===$scope.entity&&(newGisEntity.GuidWorkOrder=$scope.entityModel.Guid),newGisEntity.EntityType=$scope.entityModel.Prefix,newGisEntity.GuidEntity=$scope.entityModel.Guid,repository.createSingle(repository.apiData.gisEntity.url,newGisEntity).then(function(result){repository.growl("Koordinater opprettet","info"),$scope.entityModel.GuidGisEntity=result.Guid,$scope.showMap=!0,getMarker(result.Guid)},function(error){repository.growl(error,"danger")})};$scope.deleteGisEntity=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-gisentity-message","Kartpunktet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-gisentity-button-confirm","Ja, fjern kartpunktet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.patch(repository.apiData[$scope.entity].url,$scope.entityModel.Guid,{GuidGisEntity:null}).then(function(patchResult){repository.deleteSingle(repository.apiData.gisEntity.url,$scope.gisEntity.Guid).then(function(result){$scope.entityModel.GuidGisEntity=null,$scope.gisEntity={},$scope.showMap=!1,$scope.updateMode=!1,$scope.mapData.markers={},swal(translationService.translate("web-swal-gisentity-success","Kartpunktet ble slettet!"),result,"success")},function(error){repository.growl(error,"danger")})},function(error){repository.growl(error,"danger")})})}}angular.module("Plania").directive("planiaMap",["$animate",function($animate){return{restrict:"E",scope:{entity:"=",entityModel:"=",height:"=",hideEdit:"=",reload:"="},controller:["$scope","Repository","leafletData","$localStorage","$modal","TranslationService","Constants","$rootScope","IconService",planiaMapController],link:function(scope,element,attrs){},templateUrl:"app/common/directives/views/planiaMapDirective.html"}}]),angular.module("Plania").controller("CoordinateSelectionController",["$scope","$modalInstance","entity",function($scope,$modalInstance,entity){$scope.entity=entity,$scope.model={};var selectedTab="";$scope.select=function(selected){selectedTab=selected},$scope.ok=function(){var response={};"MapClick"===selectedTab?response.useMapClick=!0:"Coordinates"===selectedTab?(response.lat=$scope.model.lat,response.lng=$scope.model.lng):"Address"===selectedTab&&(response.address=$scope.model.address),$modalInstance.close(response)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}])}(),function(){angular.module("Plania").directive("plTableHeader",function(){return{restrict:"A",scope:{columns:"=columns",table:"=table",list:"=list",selectable:"=selectable",hideContext:"=hideContext",useObjects:"=useObjects",showEmptyEndColumn:"=showEmptyEndColumn",showEmptyStartColumn:"=showEmptyStartColumn"},controller:["$scope",tableHeaderController],templateUrl:"app/common/directives/views/planiaTableHeader.html"}});var tableHeaderController=function($scope){$scope.allRowsSelected=!1,$scope.showFilterValues=!1,$scope.$watch("columns",function(newValue,oldValue){newValue!==oldValue&&$scope.columns&&$scope.columns.forEach(function(column){"CleaningEstimateYear"!==column.Property&&"EstimatedTimeYear"!==column.Property&&"NextCleaning"!==column.Property||(column.SortingDisabled=!0)})}),$scope.selectAllRows=function(){$scope.allRowsSelected?($scope.table.data.forEach(function(row){if(row.data)row.data.forEach(function(row){var index=_.findIndex($scope.list,function(o){return $scope.useObjects?o.Guid===row.Guid:o===row.Guid});$scope.list.splice(index,1)});else{var index=_.findIndex($scope.list,function(o){return $scope.useObjects?o.Guid===row.Guid:o===row.Guid});$scope.list.splice(index,1)}}),$scope.allRowsSelected=!1):($scope.table.data.forEach(function(row){row.data?row.data.forEach(function(row){$scope.useObjects?_.find($scope.list,function(o){return o.Guid===row.Guid})||$scope.list.push(row):_.contains($scope.list,row.Guid)||$scope.list.push(row.Guid)}):$scope.useObjects?_.find($scope.list,function(o){return o.Guid===row.Guid})||$scope.list.push(row):_.contains($scope.list,row.Guid)||$scope.list.push(row.Guid)}),$scope.allRowsSelected=!0)},$scope.$watch("table.data",function(newValue,oldValue){if(newValue!==oldValue){if(0===newValue.length)return void($scope.allRowsSelected=!1);for(var i=0;i'+translationService.translate("web-button-goTo","Gå til")+"",isHref:!0}};$scope.menuOptions=function(item){var options=[],url=getHref(item);return options.push(getMenuLink(url)),!$scope.disableAdd&&item.Prefix===equipmentPrefix&&item.IsEquipmentGroup&&repository.authService.hasCreateAccess(repository.commonService.prefix.Equipment)&&"DataAcquisition"!==$scope.treeViewContext&&options.push({html:''+translationService.translate("web-button-add","Legg til ny")+"",click:function(){$scope.addNewChild(item)}}),!$scope.disableAdd&&item.Prefix===equipmentPrefix&&"DataAcquisition"===$scope.treeViewContext&&repository.authService.hasCreateAccess(repository.commonService.prefix.Document)&&(options.push({html:''+translationService.translate("web-equipment-treeview-addDocument","Last opp dokument")+"",click:function(){$scope.addNewDocument(item)}}),options.push({html:''+translationService.translate("web-equipment-treeview-addExistingDocument","Legg til eksisterende dokument")+"",click:function(){$scope.addExistingDocument(item)}})),options},$scope.addNewDocument=function(item){$modal.open({templateUrl:"app/document/views/createDocumentModal.html",controller:"CreateDocumentXEntityController",size:"lg",resolve:{params:function(){return{guidEquipment:item.Guid}}}}).result.then(function(){$scope.itemTable.reload()},function(msg){})},$scope.addExistingDocument=function(item){$modal.open({templateUrl:"app/document/views/addExistingDocument.html",controller:"AddExistingDocumentController",resolve:{params:function(){return{guidEquipment:item.Guid}}}}).result.then(function(){$scope.itemTable.reload()},function(msg){})},$scope.counts={totalCount:0};var searchDelay;$scope.filterTopLevelEntity=function(){clearTimeout(searchDelay),searchDelay=setTimeout(function(){filter.searchString=$scope.searchString,getTreeModel()},800)};var findTreeElementFromGuid=function(guid){var object;return $scope.treeModel.some(function f(a){return a.Guid===guid?(object=a,!0):Array.isArray(a.children)?a.children.some(f):void 0}),object},updateSelectedTreeViewSection=function(){switch($scope.selectedItem.Prefix){case equipmentPrefix:$scope.selectedItem.GuidEquipmentGroup?getChildEntities(findTreeElementFromGuid($scope.selectedItem.GuidEquipmentGroup)):$scope.selectedItem.GuidBuilding&&getChildEntities(findTreeElementFromGuid($scope.selectedItem.GuidBuilding));break;case buildingPrefix:getChildEntities(findTreeElementFromGuid($scope.selectedItem.GuidEstate));break;case estatePrefix:getChildEntities($scope.selectedItem)}},getChildUrl=function(item){switch(item.Prefix){case equipmentPrefix:case areaPrefix:case buildingPrefix:return"Area"===$scope.filterEntity||"CleaningCompletion"===$scope.filterEntity?repository.apiData.area.url:repository.apiData.equipment.url;case estatePrefix:return repository.apiData.building.url}},getChildFilter=function(item){var filter;switch(item.Prefix){case equipmentPrefix:return filter={PropertyFilter:[{Property:"GuidEquipmentGroup",Operator:"=",Value:item.Guid}]},"DataAcquisition"===$scope.treeViewContext||"filter"===$scope.usage&&"Equipment"===$scope.filterEntity&&filter.PropertyFilter.push({Property:"IsEquipmentGroup",Operator:"=",Value:!0}),filter;case areaPrefix:return{};case buildingPrefix:return filter={PropertyFilter:[{Property:"GuidBuilding",Operator:"=",Value:item.Guid}]},"Equipment"===$scope.filterEntity&&filter.PropertyFilter.push({Property:"GuidEquipmentGroup",Operator:"=",Value:null}),"DataAcquisition"!==$scope.treeViewContext&&"filter"===$scope.usage&&"Equipment"===$scope.filterEntity&&filter.PropertyFilter.push({Property:"IsEquipmentGroup",Operator:"=",Value:!0}),filter;case estatePrefix:return{PropertyFilter:[{Property:"GuidEstate",Operator:"=",Value:item.Guid}]}}},getChildColumns=function(item){var childColumns=["Id","Description"];switch(item.Prefix){case buildingPrefix:case equipmentPrefix:childColumns.push("Building.Id","Building.Description","IsEquipmentGroup"),childColumns.push("ChildEquipmentCount","ChildEquipmentGroupCount","ChildAllAreaCount"),"DataAcquisition"===$scope.treeViewContext&&childColumns.push("ChildDocumentCount");break;case estatePrefix:"filter"===$scope.usage?childColumns.push("ChildAllEquipmentCount","IsGround"):childColumns.push("ChildEquipmentCount"),"DataAcquisition"===$scope.treeViewContext&&childColumns.push("ChildEquipmentDocumentCount")}return childColumns},getChildEntities=function(item){if(item){item.isExpanded=!0,item.isLoading=!0;var childColumns=getChildColumns(item),childFilter=getChildFilter(item);if(childFilter||(childFilter={}),"function"==typeof $scope.applyFilter){var modified=$scope.applyFilter(angular.copy(childFilter));modified&&(childFilter=modified)}repository.GetPaginated(getChildUrl(item),-1,-1,{Id:"asc"},childFilter,"",JSON.stringify(childColumns)).then(function(result){item.isLoading=!1,item.children=result.List,saveTreeView(),$scope.totalCount+=result.List.length},function(error){repository.growl(error,"error"),item.isLoading=!1})}},setTableFilter=function(filter,item){if(item)switch(item.Prefix){case equipmentPrefix:item.IsEquipmentGroup?filter.PropertyFilter.push({Property:"GuidEquipmentGroup",Operator:"=",Value:item.Guid}):filter.PropertyFilter.push({Property:"Guid",Operator:"=",Value:item.Guid});break;case areaPrefix:filter.PropertyFilter.push({Property:"GuidArea",Operator:"=",Value:item.Guid});break;case buildingPrefix:filter.PropertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:item.Guid});break;case estatePrefix:"Equipment"===$scope.filterEntity?filter.PropertyFilter.push({Property:"Building.GuidEstate",Operator:"=",Value:item.Guid}):filter.PropertyFilter.push({Property:"GuidEstate",Operator:"=",Value:item.Guid})}},setPersistentData=function(item){isTreeViewStored()&&($sessionStorage.storedTreeView[$state.current.name].selectedTreeViewItem=$scope.selectedItem),"Equipment"===$scope.filterEntity&&($scope.selectedItem.Prefix===estatePrefix?repository.persistedData.setPersistedData("equipment.create",{}):repository.persistedData.setPersistedData("equipment.create",{GuidBuilding:$scope.selectedItem.Prefix===buildingPrefix?$scope.selectedItem.Guid:$scope.selectedItem.GuidBuilding,Building:$scope.selectedItem.Prefix===buildingPrefix?{Caption:$scope.selectedItem.Caption}:$scope.selectedItem.Building,GuidEquipmentGroup:$scope.selectedItem.Prefix===equipmentPrefix&&$scope.selectedItem.IsEquipmentGroup?$scope.selectedItem.Guid:null,EquipmentGroup:$scope.selectedItem.Prefix===equipmentPrefix&&$scope.selectedItem.IsEquipmentGroup?$scope.selectedItem:null}))};if("filter"===$scope.usage&&isTreeViewStored()&&(!$scope.fromState||$scope.fromState===$scope.filterEntity.toLowerCase()+".edit"||$scope.fromState===$scope.filterEntity.toLowerCase()+".create"||"CleaningCompletion"===$scope.filterEntity&&$scope.fromState.toLowerCase()===$scope.filterEntity.toLowerCase()+".list")){$scope.treeModel=$sessionStorage.storedTreeView[$state.current.name].treeView,$scope.counts.totalCount=$sessionStorage.storedTreeView[$state.current.name].treeViewTotal,$scope.selectedItem=$sessionStorage.storedTreeView[$state.current.name].selectedTreeViewItem;var selectedSelectionGuid=$sessionStorage.storedTreeView[$state.current.name].selectedSelectionGuid,selectedBuildingGuid=$sessionStorage.storedTreeView[$state.current.name].selectedBuildingGuid;$scope.fromState&&$scope.selectedItem&&updateSelectedTreeViewSection();var filterData=repository.commonService.getFilterData();filterData.selectedBuilding.Guid===selectedBuildingGuid&&filterData.selectedSelection.Guid===selectedSelectionGuid||getTreeModel()}else getTreeModel(),$scope.selectedItem=null;$scope.clickAction=function(item){if(!1!==$scope.isActive){if(("filter"===$scope.usage||"DataAcquisition"===$scope.treeViewContext)&&($scope.selectedItem!==item&&($scope.selectedItem=item,setPersistentData(item)),$scope.itemTable)){var filter=$scope.itemTable.filter();filter||(filter={}),filter.PropertyFilter?(_.remove(filter.PropertyFilter,function(o){return"Guid"===o.Property||"GuidEstate"===o.Property||"Building.GuidEstate"===o.Property||"GuidBuilding"===o.Property||"GuidEquipmentGroup"===o.Property||"GuidArea"===o.Property}),setTableFilter(filter,$scope.selectedItem)):(filter.PropertyFilter=[],setTableFilter(filter,$scope.selectedItem))}if(item.isExpanded)return item.isExpanded=!1,void saveTreeView();$scope.isExpandable(item)&&!item.isExpanded&&(item.children?(item.isExpanded=!0,saveTreeView()):getChildEntities(item))}},$scope.clearSelectedItem=function(){$scope.selectedItem=null,"filter"===$scope.usage&&setPersistentData(),saveTreeView()},$scope.isExpandable=function(item){switch(item.Prefix){case equipmentPrefix:case areaPrefix:case buildingPrefix:return item.IsEquipmentGroup&&"DataAcquisition"===$scope.treeViewContext?item.ChildEquipmentCount>0:"filter"===$scope.usage?item.ChildEquipmentGroupCount>0||item.ChildAllEquipmentCount>0||item.ChildAreaCount>0:item.ChildEquipmentCount>0;case estatePrefix:return item.ChildBuildingCount>0}},$scope.getChildCount=function(item){ switch(item.Prefix){case equipmentPrefix:return"DataAcquisition"===$scope.treeViewContext?item.ChildDocumentCount:item.ChildEquipmentCount;case areaPrefix:return item.ChildAreaCount;case buildingPrefix:return"DataAcquisition"===$scope.treeViewContext?item.ChildEquipmentDocumentCount:"filter"===$scope.usage?item.ChildAllEquipmentCount:item.ChildEquipmentCount;case estatePrefix:return item.ChildBuildingCount}},$scope.getEntityIcon=function(item){switch(item.Prefix){case equipmentPrefix:return"fa-gear c-bluegray";case areaPrefix:return"fa-layer-group c-lightblue";case buildingPrefix:return item.IsGround?"KA"===$localStorage.generalOptions.CustomerId?"fa-tombstone":"far fa-golf-flag-hole":"KA"===$localStorage.generalOptions.CustomerId?"fa-church ":"fa-building-columns c-brown";case estatePrefix:return"fa-city c-teal"}},$scope.addNewChild=function(item){switch(item.Prefix){case equipmentPrefix:repository.persistedData.setPersistedData("equipment.create",{GuidBuilding:item.GuidBuilding,Building:item.Building,GuidEquipmentGroup:item.Guid,EquipmentGroup:item}),$state.go("equipment.create",{showPersistantData:!0});break;case buildingPrefix:repository.persistedData.setPersistedData("equipment.create",{GuidBuilding:item.Guid,Building:item}),$state.go("equipment.create",{showPersistantData:!0});break;case estatePrefix:repository.persistedData.setPersistedData("building.create",{GuidEstate:item.Guid,Estate:item}),$state.go("building.create",{showPersistantData:!0});break;case areaPrefix:repository.persistedData.setPersistedData("area.create",{GuidBuilding:item.Guid,Building:item}),$state.go("area.create",{showPersistantData:!0})}},$scope.$watch("isActive",function(newVal,oldVal){if(void 0!==oldVal&&newVal!==oldVal)if(!1===newVal){if($scope.itemTable){var filter=$scope.itemTable.filter();filter.PropertyFilter&&_.remove(filter.PropertyFilter,function(o){return"Guid"===o.Property||"GuidEstate"===o.Property||"Building.GuidEstate"===o.Property||"GuidBuilding"===o.Property||"GuidEquipmentGroup"===o.Property||"GuidArea"===o.Property})}}else $scope.selectedItem&&(!0===$scope.selectedItem.isExpanded&&($scope.selectedItem.isExpanded=!1),$scope.clickAction($scope.selectedItem))}),$scope.$on($rootScope.events.newSelection,function(){topLevelEntity=""!==repository.commonService.getFilterData().selectedBuilding.Guid?"Building":$scope.topLevelEntity,setTopLevelEntity(),getTreeModel()})}angular.module("Plania").directive("plTreeView",function(){return{restrict:"E",scope:{isActive:"=isActive",topLevelEntity:"=topLevelEntity",parentGuid:"=parentGuid",filterEntity:"=filterEntity",totalCount:"=totalCount",filterProperty:"=filterProperty",usage:"=usage",itemTable:"=itemTable",selectedItem:"=selectedItem",fromState:"=navigationFromState",canSelectNone:"=canSelectNone",treeViewContext:"=treeViewContext",applyFilter:"=applyFilter",disableAdd:"=disableAdd"},controller:["$scope","$rootScope","Repository","$state","$sessionStorage","$localStorage","TranslationService","$modal",controller],templateUrl:"app/common/directives/views/planiaTreeViewDirective.html"}})}(),function(){angular.module("Plania").directive("plPrintDetails",function(){return{restrict:"A",scope:{guids:"=guids",domainName:"=domainName",onPrint:"=onPrint"},controller:["$scope","$rootScope","$window","TranslationService","$localStorage",printController],template:''}});var printController=function($scope,$rootScope,$window,translationService,$localStorage){$scope.printDetails=function(){if(0===$scope.guids.length)return void swal("Ingen valg",translationService.translate("list-printdetails-missingSelect","Ingen valg. Velg en eller flere rader fra listen for å skrive ut detaljert rapport"),"error");for(var params={},i=0;i<$scope.guids.length;i++)params["reports("+i+").Guid"]=$scope.guids[i];$localStorage.reportParams=JSON.stringify(params);var url=$rootScope.navigation.href("report.print",{reportName:JSON.stringify({prefix:$scope.domainName,numberOfReports:$scope.guids.length}),reportParams:JSON.stringify(params)});$window.open(url,"_blank")}}}(),function(){angular.module("Plania").directive("plPrint",function(){return{restrict:"A",scope:{columns:"=columns",table:"=table",guids:"=guids",domainName:"=domainName",sorting:"=sorting"},controller:["$scope","$rootScope","$window","$localStorage","$timeout","TranslationService",printController],link:linkFunction,template:''}});var printController=function($scope,$rootScope,$window,$localStorage,$timeout,translationService){$scope.printList=function(){var columns=[];$scope.columns.forEach(function(col){columns.push({Title:col.Title,Property:col.Property})}),0===$scope.guids.length&&$scope.table.data.forEach(function(row){row.Guid?_.contains($scope.guids,row.Guid)||$scope.guids.push(row.Guid):row.data&&row.data.forEach(function(data){data.Guid&&(_.contains($scope.guids,data.Guid)||$scope.guids.push(data.Guid))})});var systemName="print-"+$scope.domainName.toLowerCase()+"-list-header",translatedHeader=translationService.translate(systemName);if(translatedHeader===systemName){var prefixSystemName="web-enum-prefix-"+$scope.domainName.toLowerCase();translatedHeader=translationService.translate("web-enum-prefix-"+$scope.domainName),translatedHeader===prefixSystemName&&(translatedHeader=systemName)}$localStorage.reportParams=JSON.stringify({DomainName:$scope.domainName,Header:translatedHeader,Guids:JSON.stringify($scope.guids),Columns:JSON.stringify(columns),Sorting:JSON.stringify($scope.sorting)});var url=$rootScope.navigation.href("report.print",{reportName:"Plania.API.Reports.EntityPrintList, Plania.API"});$timeout(function(){$window.open(url,"_blank")},100)}},linkFunction=function(scope,element,attrs){}}(),function(){angular.module("Plania").directive("plPrintLabel",function(){return{restrict:"A",scope:{guids:"=guids",domainName:"=domainName",onPrint:"=onPrint"},controller:["$scope","$rootScope","$window","TranslationService","$localStorage",printController],templateUrl:"app/common/directives/views/printLabelDirective.html"}});var printController=function($scope,$rootScope,$window,translationService,$localStorage){$scope.printDetails=function(){if(0===$scope.guids.length)return void swal("Ingen valg",translationService.translate("list-printlabel-missingSelect","Ingen valg. Velg en eller flere rader fra listen for å skrive ut etikett"),"error");var params={Guids:JSON.stringify($scope.guids),GuidBarcode:null};$localStorage.reportParams=JSON.stringify(params),"Component"===$scope.domainName&&($scope.domainName="SparePart");var reportName="PrintLabel"+$scope.domainName,url=$rootScope.navigation.href("report.print",{reportName:reportName,reportParams:JSON.stringify(params)});$window.open(url,"_blank")}}}(),function(){function controller($scope,$modal,ngTableParams,repository,$rootScope,translationService){$scope.isLoading=!1,$scope.search={},$scope.reloads={reloadQrCode:!1},$scope.hasReadAccess=$rootScope.hasReadAccess("Barcode");var columns=["Id","IsDefault","UpdatedDate","CreationDate"],getQrCodes=function(){$scope.guid&&repository.GetPaginated(repository.apiData.barcode.prefix,0,50,{IsDefault:"desc",CreationDate:"desc"},{PropertyFilter:[{Property:"Guid"+$scope.parentEntity,Operator:"=",Value:$scope.guid}]},"",JSON.stringify(columns)).then(function(response){response||(response={}),$scope.qrCodes=response.List,$scope.totalCount=response.TotalCount,$scope.reloads.reloadQrCode=!0,$scope.guidSparePart?$scope.printGuids=[$scope.guidSparePart]:$scope.printGuids=[$scope.guid]})};$scope.$watch("reload",function(newValue,oldValue){newValue!==oldValue&&$scope.reload&&!0===$scope.reload&&(getQrCodes(),$scope.reload=!1)}),getQrCodes(),$scope.create=function(){var qrCode={};qrCode["Guid"+$scope.parentEntity]=$scope.guid,$modal.open({templateUrl:"app/common/modal/views/editQrCodeModal.html",controller:"EditQrCodeModalController",resolve:{params:function(){return{isUpdate:!1,qrCode:qrCode,domainName:$scope.parentEntity,guidSparePart:$scope.guidSparePart,hidePrint:$scope.hidePrint}}}}).result.then(function(response){getQrCodes()},function(){})},$scope.generateBarcode=function(){var qrCode={};qrCode["Guid"+$scope.parentEntity]=$scope.guid,repository.createSingle(repository.apiData.barcode.url,qrCode).then(function(result){getQrCodes(),repository.growl("Qr-kode generert","success")},function(error){error===translationService.translate("web-barcode-not-unique","QR-koden må være unik")?repository.growl(translationService.translate("web-barcode-alreadyExists","Det finnes allerede en generert qr-kode med samme id, ta kontakt med systemadministrator for å endre format til å sikre unik"),"danger"):repository.growl(error,"danger")})},$scope.update=function(qrCode){$modal.open({templateUrl:"app/common/modal/views/editQrCodeModal.html",controller:"EditQrCodeModalController",resolve:{params:function(){return{isUpdate:!0,qrCode:qrCode,domainName:$scope.parentEntity,guidSparePart:$scope.guidSparePart,hidePrint:$scope.hidePrint}}}}).result.then(function(response){getQrCodes()},function(){})},$scope.remove=function(item){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-barcode-message","QR-koden vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-barcode-button-confirm","Ja, fjern qr-koden!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.deleteSingle(repository.apiData.barcode.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-barcode-success","QR-koden ble fjernet!"),result,"success"),getQrCodes()},function(error){swal("Error",error,"error")})})},$scope.$on($rootScope.events.newSelection,function(){getQrCodes()})}angular.module("Plania").directive("qrCodeList",function(){return{restrict:"E",scope:{isCollapsed:"=isCollapsed",reload:"=reload",qrCodes:"=qrCodes",disableActions:"=disableActions",parentEntity:"=parentEntity",guid:"=guid",hidePrint:"=hidePrint",guidSparePart:"=guidSparePart",restrictEdit:"=restrictEdit"},controller:["$scope","$modal","ngTableParams","Repository","$rootScope","TranslationService",controller],link:function(scope,element,attrs){},templateUrl:"app/common/directives/views/qrCodeListDirective.html"}})}(),function(){angular.module("Plania").directive("qrCode",["$timeout","$window",function($timeout,$window){return{restrict:"E",scope:{data:"=data",width:"=width",height:"=height",reload:"=reload"},templateUrl:"app/common/directives/views/qrcode.html",link:function(scope,element,attrs){var qrcode,maxHeight=180,width=scope.width;$timeout(function(){0===width&&(width=element.find(".qr-code").innerWidth()-24)>maxHeight&&(width=maxHeight),createQrCode()});var createQrCode=function(){qrcode=new QRCode(element.find(".qr-code")[0],{text:scope.data,width:width||128,height:width||128,colorDark:"#000000",colorLight:"#ffffff",correctLevel:QRCode.CorrectLevel.H})},resize=function(){element.find(".qr-code img").remove(),element.find(".qr-code canvas").remove(),qrcode.clear(),createQrCode()};scope.$watch("reload",function(newValue,oldValue){newValue!==oldValue&&scope.reload&&(0===scope.width&&(width=element.find(".qr-code").innerWidth()-24),resize(),scope.reload=!1)})}}}])}(),function(){function controller($scope,constants,$filter){function convertWeekdayArray(array){var i=0;if("string"==typeof array[0])for(i;i-1?array.splice(idx,1):(array.push(weekday),convertWeekdayArray(array),array.sort(sortNumberArray),convertWeekdayArray(array)),$scope.model.RecurrenceRule.ByDay=array},$scope.setWeekDay=function(weekday){var array=[weekday];convertWeekdayArray(array),array.sort(sortNumberArray),convertWeekdayArray(array),$scope.model.RecurrenceRule.ByDay=array},$scope.onDailySelect=function(value){1===value?($scope.model.RecurrenceRule.Interval=1,$scope.model.RecurrenceRule.ByDay=["Monday","Tuesday","Wednesday","Thursday","Friday"]):$scope.model.RecurrenceRule.ByDay=[]},$scope.onUnitSelect=function(){"Day"===$scope.model.RecurrenceRule.Unit&&$scope.onDailySelect($scope.selectedDaily),$scope.model.RecurrenceRule.ByMonthDay=[],$scope.model.RecurrenceRule.ByMonth=[],$scope.model.RecurrenceRule.ByDay=[],"Week"!==$scope.model.RecurrenceRule.Unit&&"Month"!==$scope.model.RecurrenceRule.Unit&&"Year"!==$scope.model.RecurrenceRule.Unit||($scope.model.RecurrenceRule.Interval=1),$scope.isPeriod&&"Week"===$scope.model.RecurrenceRule.Unit&&$scope.setWeekDay("Monday"),"Month"===$scope.model.RecurrenceRule.Unit&&($scope.model.RecurrenceRule.ByMonthDay=[1]),"Year"===$scope.model.RecurrenceRule.Unit&&($scope.model.RecurrenceRule.ByMonthDay=[1],$scope.model.RecurrenceRule.ByMonth=[1])};var setEndDateFromPeriod=function(){if(!$scope.repeatPeriod&&$scope.model.RecurrenceRule.PeriodUnit&&$scope.model.RecurrenceRule.PeriodNumber&&void 0!==$scope.model.RecurrenceRule.StartDate){var date=new Date($scope.model.RecurrenceRule.StartDate);"Day"===$scope.model.RecurrenceRule.PeriodUnit?date.setDate(date.getDate()+$scope.model.RecurrenceRule.PeriodNumber):"Week"===$scope.model.RecurrenceRule.PeriodUnit?date.setDate(date.getDate()+7*$scope.model.RecurrenceRule.PeriodNumber):"Month"===$scope.model.RecurrenceRule.PeriodUnit&&(date=addMonths(date,$scope.model.RecurrenceRule.PeriodNumber)),$scope.model.RecurrenceRule.EndDate=date}};$scope.setValueLimits=function(){$scope.model.RecurrenceRule.ByMonthDay&&($scope.model.RecurrenceRule.ByMonthDay[0]<1?$scope.model.RecurrenceRule.ByMonthDay[0]=1:$scope.model.RecurrenceRule.ByMonthDay[0]>31&&($scope.model.RecurrenceRule.ByMonthDay[0]=31)),void 0!==$scope.model.RecurrenceRule.Interval&&$scope.model.RecurrenceRule.Interval<1&&($scope.model.RecurrenceRule.Interval=1)},$scope.model.RecurrenceRule&&($scope.rruleText=$filter("plRecurrenceRuleFilter")($scope.model.RecurrenceRule)),$scope.useModelDates&&($scope.$watch("model.StartDate",function(newVal){$scope.model&&$scope.model.RecurrenceRule&&($scope.model.RecurrenceRule.StartDate=newVal)}),$scope.$watch("model.UntilDate",function(newVal){$scope.model&&$scope.model.RecurrenceRule&&($scope.model.RecurrenceRule.Until=newVal)})),$scope.$watch("model.RecurrenceRule",function(newValue,oldValue){newValue&&($scope.setValueLimits(),$scope.rruleText=$filter("plRecurrenceRuleFilter")(newValue),$scope.selectedDaily="Day"===newValue.Unit&&1===newValue.Interval&&JSON.stringify(newValue.ByDay)===JSON.stringify(["Monday","Tuesday","Wednesday","Thursday","Friday"]),$scope.repeatPeriod="Once"!==newValue.Unit,$scope.isPeriod&&setEndDateFromPeriod())},!0)}angular.module("Plania").directive("recurrenceRule",function(){return{restrict:"E",scope:{model:"=model",rruleText:"=rruleText",hideRuleText:"=hideRuleText",hideStartDate:"=hideStartDate",isPeriod:"=isPeriod",viewMode:"=viewMode",useModelDates:"=useModelDates",useRecurrenceDates:"=useRecurrenceDates"},controller:["$scope","Constants","$filter",controller],templateUrl:"app/common/directives/views/recurrenceRuleDirective.html"}})}(),function(){angular.module("Plania").directive("scaleFontToContainer",[function(){return{restrict:"A",scope:{scaleFontToContainer:"@"},link:function(scope,element,attrs){if(scope.scaleFontToContainer)switch(scope.scaleFontToContainer.length){case 4:element.css("font-size","16px");break;case 5:element.css("font-size","14px");break;case 6:element.css("font-size","12px");break;case 7:element.css("font-size","10px");break;default:element.css("font-size","20px")}}}}])}(),angular.module("Plania").directive("scrollToolbar",function($window,$timeout){return function(scope,element,attrs){angular.element($window).bind("scroll",function(){var isAnimating=!1,animation="fadeInUp",animationDuration=1200;this.pageYOffset>=attrs.toolbarMinHeight?(scope.showToolbar=!0,element.context.classList.contains("ng-hide")&&($timeout.cancel(),element.addClass("animated "+animation),$timeout(function(){isAnimating=!1,element.removeClass(animation)},animationDuration))):element.context.classList.contains("ng-hide")||($timeout.cancel(),animation="fadeOutDown",animationDuration=1200,element.addClass("animated "+animation),$timeout(function(){element.removeClass(animation),scope.showToolbar=!1},animationDuration)),scope.$apply()})}}),angular.module("Plania").directive("setFocus",["$timeout","$parse",function($timeout,$parse){return{link:function(scope,element,attrs){var model=$parse(attrs.setFocus);scope.$watch(model,function(value){!0===value&&$timeout(function(){element[0].focus()})}),element.bind("blur",function(){scope.$apply(model.assign(scope,!1))})}}}]),angular.module("Plania").directive("spinner",["$window",function($window){return{restrict:"A",link:function(scope,element,attrs){scope.spinner=null,scope.$watch(attrs.spinner,function(options){scope.spinner&&scope.spinner.stop(),new $window.Spinner(options).spin(element[0])},!0)}}}]),angular.module("Plania").directive("ssrs",["$window",function($window){return{restrict:"E",replace:!0,scope:{url:"="},link:function(scope,element,attrs){element.on("load",function(){var height=document.getElementsByTagName("html")[0].scrollHeight/2+"px ";element.height(height)})},template:''}}]),function(){function controller($scope,translationService){var multiple=!!$scope.multiple;$scope.dropdownOptions=[],$scope.selected=multiple?[]:"",$scope.modelValueChanged=function(){multiple?Array.isArray($scope.selected)&&($scope.ngModel=JSON.stringify($scope.selected)):$scope.ngModel=$scope.selected};var parseArray=function(value){if(value&&"string"==typeof value&&value.startsWith("[")&&value.endsWith("]"))try{var array=JSON.parse($scope.ngModel);if(Array.isArray(array))return array}catch(e){console.error("Invalid JSON in ngModel:",$scope.ngModel)}return[]},updateSelectedValue=function(){$scope.selected=multiple?parseArray($scope.ngModel):$scope.ngModel||""},setValues=function(){var dropdownOptions=[];Array.isArray($scope.options)&&(dropdownOptions=$scope.options.map(function(val){return{value:val,label:val}}));var existingValues=[];multiple?existingValues=parseArray($scope.ngModel):$scope.ngModel&&(existingValues=[$scope.ngModel]),Array.isArray(existingValues)&&existingValues.forEach(function(exValue){dropdownOptions.map(function(val){return val.value}).includes(exValue)||dropdownOptions.push({value:exValue,label:exValue+" ("+translationService.translate("web-stringValueSelect-value-deprecated","utdatert")+")"})}),$scope.dropdownOptions=dropdownOptions};setValues(),updateSelectedValue(),$scope.$watchGroup(["options","ngModel"],function(){updateSelectedValue(),setValues()})}angular.module("Plania").directive("stringValueSelect",[function(){return{restrict:"E",scope:{ngModel:"=",ngDisabled:"=",options:"=",multiple:"=",allowEmpty:"="},compile:function(element,attrs){var select=element.find("select");select&&attrs.multiple&&select.attr("multiple","true")},controller:["$scope","TranslationService",controller],template:''}}])}(),function(){function controller($scope){if($scope.values=[],$scope.isMultiple=$scope.multiple,$scope.isMultiple){var updateValue=function(){var values=[];if($scope.ngModel&&"string"==typeof $scope.ngModel&&$scope.ngModel.startsWith("[")&&$scope.ngModel.endsWith("]"))try{values=JSON.parse($scope.ngModel)}catch(e){console.error("Invalid JSON in ngModel:",$scope.ngModel),values=[]}else $scope.ngModel&&(values=[$scope.ngModel]);$scope.values=values};$scope.$watchGroup(["options","ngModel"],function(){updateValue()})}}angular.module("Plania").directive("stringValueSelectView",[function(){return{restrict:"E",scope:{ngModel:"=",multiple:"="},controller:["$scope",controller],templateUrl:"app/common/directives/views/stringValueSelectView.html"}}])}(),function(){angular.module("Plania").directive("telerik",["$injector","$timeout",function($injector,$timeout){return{restrict:"E",replace:!0,scope:{report:"=",reportParams:"=",printReport:"=",showToolbar:"=",control:"="},link:function(scope,element,attrs){scope.internalControl=scope.control||{},scope.reportId="reportViewer"+Math.random().toString(32).substring(2,10);var reportViewer,authService=$injector.get("authService"),accessToken=authService.getPlaniaToken().access,isFirstRenderingEnd=!0,kwidgetElement=function(){return $(element[0]).find(".k-widget")},commonService=$injector.get("CommonService"),localStorage=$injector.get("$localStorage"),telerikService=$injector.get("TelerikService"),dataOwner=commonService.getFilterData().selectedDataOwner.Guid;telerikService&&telerikService.setTelerikLanguage&&telerikService.setTelerikLanguage();var getParams=function(){var params=scope.reportParams||{};return params.GuidBuildingSelection=commonService.getFilterData().selectedSelection.Guid,params.GuidBuilding=commonService.getFilterData().selectedBuilding.Guid,params.GuidActiveUser=scope.$root.userInfo.guidPerson,params.GuidUser=scope.$root.userInfo.guidUser,params.GuidDataOwner=commonService.getFilterData().selectedDataOwner.Guid,params.Locale=localStorage.locale||"nb-no",params.GuidEstate=commonService.getFilterData().selectedEstate.Guid,params},alreadyPrinted=!1,refreshReport=function(){var rs=reportViewer.reportSource();rs.parameters=getParams(),rs.report=scope.report,scope.report&&(reportViewer.reportSource(rs),reportViewer.refreshReport())},setFilter=function(){if(!(accessToken=authService.getPlaniaToken().access)||-1!==accessToken.indexOf("NTLM"))return void setTimeout(setFilter,100);jQuery.ajaxPrefilter(function(options,originalOptions,jqXhr){jqXhr.setRequestHeader("Authorization",accessToken),-1===options.url.indexOf("dataOwner=")&&(options.url+="?dataOwner="+dataOwner)})};setFilter(),scope.$on("newDataOwner",function(){refreshReport()}),scope.internalControl.refresh=function(){refreshReport()},scope.internalControl.toggleFilters=function(){reportViewer.commands.toggleParametersArea.exec()},scope.internalControl.toggleZoomMode=function(){reportViewer.commands.toggleZoomMode.exec()},scope.internalControl.getReportId=function(){return scope.reportId},scope.$watch("report",function(newValue,oldValue){newValue!==oldValue&&refreshReport()});var printOptions={serviceUrl:"/api/api/reports/",templateUrl:"/scripts/telerik/templates/telerikReportViewerTemplate-FA.html",reportSource:{report:scope.report?scope.report+".trdx":void 0,parameters:getParams()},persistSession:!1,parametersAreaVisible:!1,ready:function(){!1===scope.showToolbar&&($(".trv-nav").css("display","none"),$(".trv-content").css("top","0"))},renderingEnd:function(e,args){isFirstRenderingEnd&&(this.parametersAreaVisible(!0),this.commands.toggleParametersArea.exec(),isFirstRenderingEnd=!1),scope.printReport&&!alreadyPrinted&&(this.commands.print.exec(),alreadyPrinted=!0)}};scope.printReport?(printOptions.scaleMode=0,printOptions.viewModel=telerikReportViewer.ViewModes.PRINT_PREVIEW):!1!==scope.showToolbar&&(printOptions.scaleMode=1),$timeout(function(){kwidgetElement().telerik_ReportViewer(printOptions),reportViewer=kwidgetElement().data("telerik_ReportViewer"),element.on("load",function(){var height=document.getElementsByTagName("html")[0].scrollHeight/2+"px ";element.height(height)})},10)},templateUrl:"/app/common/directives/views/telerik.html"}}])}(),angular.module("Plania").directive("chosenResults",["scrollService",function(scrollService){return{restrict:"C",link:function(scope,element){$("html").hasClass("ismobile")||scrollService.malihuScroll(element,"minimal-dark","y")}}}]).directive("cOverflow",["scrollService",function(scrollService){return{restrict:"C",link:function(scope,element){$("html").hasClass("ismobile")||scrollService.malihuScroll(element,"minimal-dark","y")}}}]).directive("easypieChart",function(){return{restrict:"A",scope:{color:"=",size:"=",percent:"="},link:function(scope,element){$(element).attr("data-percent",scope.percent?scope.percent:0),$(element).easyPieChart({trackColor:"#eee",scaleColor:"#ccc",barColor:scope.color?scope.color:"red",lineWidth:7,lineCap:"butt",size:scope.size?scope.size:148})}}}).directive("btn",function(){return{restrict:"C",link:function(scope,element){element.hasClass("btn-icon")||element.hasClass("btn-float")?Waves.attach(element,["waves-circle"]):element.hasClass("btn-light")?Waves.attach(element,["waves-light"]):Waves.attach(element),Waves.init()}}}),function(){angular.module("Plania").directive("userProfileMenu",function(){return{templateUrl:function(elem,attr){return"/app/common/directives/views/userProfileMenuList.html"},controller:["$scope","$rootScope",function($scope,$rootScope){$scope.toggleTranslationMode=function(){$rootScope.translationMode=!$rootScope.translationMode,$rootScope.$broadcast($rootScope.events.translationMode)}}]}})}(),function(){"use strict";function directive(){return{restrict:"A",link:function(scope,element,attrs){var timeoutId=0;timeoutId=setTimeout(function(){$(".mejs-controls").addClass("hideControls")},3e3);var isMouseInsideVideoElement=!1;$("body").on("mousemove",function(){clearTimeout(timeoutId),isMouseInsideVideoElement&&$(".mejs-controls").removeClass("hideControls"),timeoutId=setTimeout(function(){$(".mejs-controls").addClass("hideControls")},2500)}),element.on("mouseenter",function(){isMouseInsideVideoElement=!0,$(".mejs-controls").removeClass("hideControls")}),element.on("mouseleave",function(){isMouseInsideVideoElement=!1,$(".mejs-controls").addClass("hideControls")})}}}angular.module("Plania").directive("planiaVideoControls",[directive])}(),function(){function controller($scope,$modal,ngTableParams,config,repository,$filter,$window,translationService){$scope.videosIsLoading=!0,$scope.$watch("reload",function(newValue,oldValue){newValue===oldValue&&$scope.videoTable.filter().PropertyFilter||$scope.reload&&($scope.videoTable.filter().PropertyFilter=[{Property:"Guid"+$scope.prefix,Operator:"=",Value:$scope.guid}],$scope.reload=!1)}),$scope.columns=[{Position:1,Title:translationService.translate("web-video-id"),Property:"Video.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-video-description"),Property:"Video.Description",PropertyType:"string"}];var countArray=[],countNumber=1e3;void 0===$scope.printView&&(countArray=[10,20,50],countNumber=10),$scope.videoTable=new ngTableParams({page:1,count:countNumber,sorting:{"Video.Id":"asc"}},{total:0,counts:countArray,filterDelay:50,getData:function($defer,params){if(params.filter().PropertyFilter){$scope.videosIsLoading=!0;var columns=["Video.GuidVideoBinary"];$scope.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.videoXEntity.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.videoTable.settings().total=result.TotalCount,$scope.videoTable.settings().filterDelay=500,$scope.videos=result.TotalCount,$defer.resolve(result.List),$scope.videosIsLoading=!1},function(error){repository.growl(error,"danger"),$scope.videosIsLoading=!1})}}}),$scope.getPropertyValue=function(row,column){var properties=column.Property.split("."),temp=row;if(properties.forEach(function(prop){temp&&(temp=temp[prop])}),"date"===column.PropertyType&&temp){var date=new Date(temp);return("0"+date.getDate()).slice(-2)+"."+("0"+(date.getMonth()+1)).slice(-2)+"."+date.getFullYear()}return temp};var resolveParams=function(){var params={defaultCategory:$scope.defaultCategory};return params["guid"+$scope.prefix]=$scope.guid,params};$scope.addNewVideo=function(){$modal.open({templateUrl:"app/video/views/createVideoModal.html",controller:"CreateVideoXEntityController",resolve:{params:resolveParams}}).result.then(function(){$scope.videoTable.reload()})},$scope.addExistingVideo=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Legg til eksisterende video",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.video.url,sorting:{Id:"asc"},filter:{}}}}}).result.then(function(selectedVideos){var videoXEntities=[];selectedVideos.forEach(function(guid){var xentity={GuidVideo:guid};xentity["Guid"+$scope.prefix]=$scope.guid,videoXEntities.push(xentity)}),repository.createMultiple(repository.apiData.videoXEntity.url,videoXEntities).then(function(result){$scope.videoTable.reload()})},function(msg){})},$scope.removeVideo=function(video){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-video-message","Videoen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-video-button-confirm","Ja, fjern videoen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.videoXEntity.url,video.Guid).then(function(result){swal(translationService.translate("web-swal-video-success","Videoen ble fjernet!"),result,"success"),repository.growl("Videoen har blitt fjernet","success"),$scope.videoTable.reload()})})},$scope.editVideo=function(video){$modal.open({templateUrl:"app/video/views/editVideoMetadataModal.html",controller:"EditVideoXEntityController",resolve:{params:function(){return{guid:video.GuidVideo,isModal:!0}}}}).result.then(function(){$scope.videoTable.reload()},function(){})},$scope.playVideo=function(video){$modal.open({size:"lg",controller:"VideoPlayerModalController",templateUrl:"app/video/views/videoPlayerModal.html",resolve:{params:function(){return{video:video.Video,guidVideoBinary:video.Video.GuidVideoBinary}}}})}}angular.module("Plania").directive("videos",function(){return{restrict:"E",scope:{reload:"=reload",defaultCategory:"=defaultCategory",disableActions:"=disableActions",guid:"=guid",prefix:"=prefix",printView:"=print"},controller:["$scope","$modal","ngTableParams","config","Repository","$filter","$window","TranslationService",controller],link:function(scope,element,attrs){}, templateUrl:"app/common/directives/views/videoDirective.html"}})}(),function(){angular.module("Plania").directive("viewedit",["$localStorage",function($localStorage){return function(scope,element,attrs){var dtElement,inputElement,autocompleteElement,timepickerelement,editModeElement,viewModeElement,checkboxElement,datePickerElement,inputGroupElement,hideInputElement=function(){dtElement.removeClass("p-t-10"),checkboxElement.css("display","none"),autocompleteElement.css("display","none"),timepickerelement.css("display","none"),datePickerElement.css("display","none"),inputGroupElement.css("display","none"),inputElement.css("display","none"),editModeElement.css("display","none"),viewModeElement.css("display","inline-block")},showInputElement=function(){checkboxElement[0]&&checkboxElement[0].className.indexOf("checkbox-inline")>-1?checkboxElement.css("display","inline-block"):checkboxElement.css("display","block"),inputGroupElement[0]&&inputGroupElement[0].className.indexOf("input-group-flex")>-1?inputGroupElement.css("display","flex"):inputGroupElement.css("display","table"),dtElement.addClass("p-t-10"),autocompleteElement.css("display","block"),timepickerelement.css("display","block"),datePickerElement.css("display","block"),inputElement.css("display","inline-block"),editModeElement.css("display","inline-block"),viewModeElement.css("display","none")};scope.$watch("viewMode",function(){if(dtElement=element.find("dt"),inputElement=element.find(".fg-line"),autocompleteElement=element.find("autocomplete"),timepickerelement=element.find("timepicker"),editModeElement=element.find(".editModeElement"),viewModeElement=element.find(".viewModeElement"),checkboxElement=element.find(".checkbox"),datePickerElement=element.find("pl-datepicker"),inputGroupElement=element.find(".input-group"),scope.model&&scope.model.DynamicProperty&&$localStorage.userData.canOverridePermissions&&scope.property&&scope.property.ForceEdition)return void showInputElement();scope.viewMode?hideInputElement():showInputElement()})}}])}(),function(){angular.module("Plania").directive("viewField",function(){return{restrict:"E",scope:{ngModel:"=ngModel",logicalType:"@logicalType"},link:function(scope,element,attrs,ctrl){scope.model="-",scope.elementType="span",scope.elementData={};var isEmpty=function(value){return void 0===value||null===value||""===value},getPhoneAreaLabel=function(value){if(!isEmpty(value)){"string"!=typeof value&&(value=value.toString());var splittedNumber=value.split(""),ariaLabelText="";return splittedNumber.forEach(function(str,index){ariaLabelText+=str,index!==splittedNumber.length-1&&(ariaLabelText+=(index+1)%2==0?". ":" ")}),ariaLabelText}};scope.$watch("ngModel",function(newVal,oldVal){var ngModelAsString=isEmpty(scope.ngModel)?"":scope.ngModel.toString();if("phoneNumber"!==scope.logicalType||isEmpty(ngModelAsString))scope.elementType="span";else{scope.elementType="anchor";var phoneNumer=ngModelAsString.replace(/\s/g,"");scope.elementData.href="tel:"+phoneNumer,scope.elementData.ariaLabel=getPhoneAreaLabel(phoneNumer)}isEmpty(ngModelAsString)?scope.model="-":scope.model=ngModelAsString},!0)},templateUrl:"app/common/directives/views/viewFieldDirective.html"}})}(),function(){angular.module("Plania").directive("wysiwyg",[function(){return{restrict:"E",replace:!0,scope:{model:"="},link:function(scope,element,attrs){var isInitialized=!1;scope.$watch("model",function(newValue,oldValue){newValue!==oldValue&&isInitialized&&tinymce.activeEditor.setContent(newValue)}),tinymce.init({selector:"#wysiwyg",height:300,theme:"modern",language:"nb_NO",branding:!1,plugins:["advlist autolink lists link image charmap print preview hr anchor pagebreak","searchreplace visualblocks visualchars code codesample","insertdatetime media nonbreaking save table contextmenu directionality","emoticons template paste textcolor colorpicker textpattern imagetools toc help"],toolbar1:"undo redo | styleselect fontselect fontsizeselect | bold italic forecolor backcolor | alignleft aligncenter alignright | bullist numlist outdent indent | preview",image_advtab:!0,paste_data_images:!0,templates:[{title:"Test template 1",content:"Test 1"},{title:"Test template 2",content:"Test 2"}],content_css:["//fonts.googleapis.com/css?family=Lato:300,300i,400,400i","//www.tinymce.com/css/codepen.min.css"],init_instance_callback:function(editor){isInitialized=!0,scope.model&&editor.setContent(scope.model)}}),scope.$on("$destroy",function(){tinymce.activeEditor.destroy()})},templateUrl:"/app/common/directives/views/wysiwyg.html"}}])}(),function(){function controller($scope,$modalInstance,$modal,params,translationService,documentService,repository,$q,$sce,$filter,$localStorage,$window,$timeout){function setEmailBody(tmpString,properties,mappedProperties,userProperties,customProperties){for(var i=0;i0)for(var mappedUserProperties=userProperties.map(function(x){return x.match(/[\@\w\.]+/)[0]}),j=0;j0)for(var mappedCustomProperties=customProperties.map(function(x){return x.match(/[\#\w\.]+/)[0]}),k=0;k")),propertyValue||""}function hasValue(testModel,prop,isLastProperty){if(!testModel||!testModel.hasOwnProperty(prop))return!1;if(isLastProperty&&"object"==typeof testModel){var value=testModel[prop];if(0===value)return!1;if("Default"===value)return!1;if(""===value)return!1}return!0}function checkNestedProperties(dottedColumns){try{for(var i=0;i")?$scope.email.from=fromEmail:$scope.email.from=$localStorage.userData.realName+" <"+$localStorage.userData.email+">"}var camelCasePrefix=_.camelCase(entity),url=repository.apiData[camelCasePrefix].url,fetchAttachments=function(){return repository.getWithUrlParameter(repository.apiData.email.url+"getAvailableAttachmentsForEntity/"+$scope.model.Guid).then(function(response){return availableAttachments=response.Attachments,$scope.isInitiallyLoadingAttachments=!1,availableAttachments},function(error){repository.showError(error),$scope.isInitiallyLoadingAttachments=!1})};fetchAttachments(!0).then(function(){availableAttachments.forEach(function(attachment){attachment.IsDefaultAttached&&$scope.attachments.push(attachment)})}),function(){repository.GetPaginated(repository.apiData.emailTemplate.url,0,50,{Id:"asc"},{PropertyFilter:[{Property:"EntityType",Operator:"=",Value:entity}]}).then(function(result){$scope.emailTemplates=result.List,$scope.emailTemplates.length>0&&($scope.selectedEmailTemplate=getDefaultTemplate(),$scope.selectedTemplateChanged($scope.selectedEmailTemplate))})}();var getDefaultTemplate=function(){var defaultTemplate=_.find($scope.emailTemplates,{IsDefault:!0});return defaultTemplate||(defaultTemplate=_.find($scope.emailTemplates,function(o){return"Plania Standard"===o.Id})),defaultTemplate};$scope.selectedTemplateChanged=function(newValue){$scope.setEmailBodyWithValues(newValue.TemplateBody)},$scope.loadTags=function(query){var deferred=$q.defer();return repository.GetPaginated(repository.apiData.emailContact.url,0,20,{Email:"asc"},{searchString:query,PropertyFilter:[{Property:"Email",Operator:"<>",Value:""}]}).then(function(result){deferred.resolve(result)}),deferred.promise},$scope.tinymceOptions={height:350,language:"nb_NO",branding:!1,plugins:["advlist autolink lists link image charmap print preview hr anchor pagebreak","searchreplace visualblocks visualchars code codesample","insertdatetime media nonbreaking save table contextmenu directionality","emoticons template paste textcolor colorpicker textpattern imagetools toc help"],toolbar:"undo redo | styleselect fontselect fontsizeselect | bold italic forecolor backcolor | alignleft aligncenter alignright | bullist numlist outdent indent",image_advtab:!0,paste_data_images:!0,relative_urls:!1,convert_urls:!1,templates:[{title:"Test template 1",content:"Test 1"},{title:"Test template 2",content:"Test 2"}],inline_styles:!0,font_formats:"Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Calibri=calibri;Comic Sans MS=comic sans ms,sans-serif;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;",setup:function(editor){}},$scope.setEmailBodyWithValues=function(string){if(!string)return void($scope.email.body="");var properties=string.match(/{{\s*[\w\.]+\s*}}/g),userProperties=string.match(/{{\@\s*[\w\.]+\s*}}/g),customProperties=string.match(/{{\#\s*[\w\.]+\s*}}/g);properties||(properties=[]);var mappedProperties=properties.map(function(x){return x.match(/[\w\.]+/)[0]}),dottedColumns=_.filter(mappedProperties,function(o){return-1!==o.indexOf(".")}),tmpString=string;checkNestedProperties(dottedColumns)?setEmailBody(tmpString,properties,mappedProperties,userProperties,customProperties):repository.getSingle(url,$scope.model.Guid,JSON.stringify(dottedColumns)).then(function(response){$scope.emailModel=response.Data,setEmailBody(tmpString,properties,mappedProperties,userProperties,customProperties)})};var customPropertyFunctions=[{property:"#web_base_url",getValue:function(){return window.location.protocol+"//"+window.location.host}}];$scope.send=function(){if($scope.email.to.length<1)return swal("Manglende mottaker!","Minst 1 mottaker må velges","info"),void($scope.showToErrorMessage=!0);$scope.showToErrorMessage=!1;var attachments=$scope.attachments.map(function(a){return a.Guid}).join(",");$scope.email.subject||($scope.email.subject=$scope.getEntityCaption($scope.model)),"object"==typeof $scope.email.body&&($scope.email.body=$scope.email.body.toString());var postEmail={GuidEntity:$scope.model.Guid,EmailTo:_.map($scope.email.to,"Email").join(";"),EmailCopyTo:_.map($scope.email.copy,"Email").join(";"),EmailSubject:$scope.email.subject,EmailBody:$scope.email.body,EmailFrom:$scope.email.from,Attachments:attachments,Status:"Outbox"};params.returnEmailObject?$modalInstance.close(postEmail):repository.createSingle(repository.apiData.alarmLog.url,postEmail).then(function(result){swal("Suksess!","E-posten ble lagt til i utboksen","success"),$modalInstance.close(result)},function(error){swal("Feil!",error,"error")})},$scope.isEmptyGuid=function(guid){return"00000000-0000-0000-0000-000000000000"===guid},$scope.onTagAdded=function(tag){tag.Email||(tag.Email=tag.Name),tag.DisplayProperty||(tag.DisplayProperty=tag.Name+(new Date).valueOf())},$scope.$watch("email.to",function(newValue,oldValue){$scope.showToErrorMessage=!1}),$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.addAttachments=function(){$modal.open({templateUrl:"app/common/modal/views/selectAttachmentModal.html",controller:"SelectAttachmentModalController",size:"lg",resolve:{params:function(){return{entityType:entity,guid:$scope.model.Guid,availableAttachments:availableAttachments,selectedAttachmentGuids:_.map($scope.attachments,function(o){return o.Guid}),onNewAttachment:fetchAttachments,onNewDocument:onNewDocument,onNewImage:onNewImage}}}}).result.then(function(selectedAttachments){selectedAttachments.forEach(function(attachment){_.find($scope.attachments,{Guid:attachment.Guid})||$scope.attachments.push(attachment)})})},$scope.openDocument=function(attachment){"Document"===attachment.Type&&documentService.openDocument({Guid:attachment.Guid,FilePath:attachment.FilePath})},$scope.previewReport=function(reportId){$localStorage.reportParams=JSON.stringify({Guid:$scope.model.Guid,DisableAutomaticPrint:!0});var url=$scope.navigation.href("report.print",{reportName:reportId});$timeout(function(){$window.open(url,"_blank")},100)}}angular.module("Plania").controller("EmailModalController",["$scope","$modalInstance","$modal","params","TranslationService","DocumentService","Repository","$q","$sce","$filter","$localStorage","$window","$timeout",controller])}(),function(){function translationFilter(translationService){return function(defaultValue,systemName,model){var value=translationService.translate(systemName,defaultValue,model),matches=value.match(/%[a-zA-Z0-9\.]*%/g);return matches&&matches.forEach(function(match){var property=match.replace(new RegExp("%","g"),"");value=model[property],property.split(".").forEach(function(prop){value=model[prop]})}),value}}angular.module("Plania").filter("translate",["TranslationService",translationFilter])}(),function(){function filter($parse,filterWatcher){return function(collection,property){function _groupBy(collection,getter){var prop,result={};return _.forEach(collection,function(elm){prop=getter(elm),result[prop]||(result[prop]=[]),result[prop].push(elm)}),result}var isObject=function(value){return null!==value&&"object"==typeof value},isUndefined=function(value){return void 0===value};return!isObject(collection)||isUndefined(property)?collection:filterWatcher.isMemoized("groupBy",arguments)||filterWatcher.memoize("groupBy",arguments,this,_groupBy(collection,$parse(property)))}}angular.module("Plania").filter("groupBy",["$parse","filterWatcher",filter])}(),function(){function filter($filter){return function(value){return $filter("number")(value,2)}}angular.module("Plania").filter("plCurrency",["$filter",filter])}(),function(){function filter(){return function(text,textLimit,rowLimit){if(!text||0===text.length)return text;newText=text.substring(0,textLimit);var lines=newText.split(/\r\n|\r|\n|
    /);return rowLimit&&rowLimit>0&&(newText=lines.splice(0,rowLimit).join("\r\n")),newText}}angular.module("Plania").filter("plLimitTo",[filter])}(),function(){function filter($filter,$rootScope,translationService){return function(recurrenceRule){var day={Monday:"Mandag",Tuesday:"Tirsdag",Wednesday:"Onsdag",Thursday:"Torsdag",Friday:"Fredag",Saturday:"Lørdag",Sunday:"Søndag"},month={1:"Januar",2:"Februar",3:"Mars",4:"April",5:"Mai",6:"Juni",7:"Juli",8:"August",9:"September",10:"Oktober",11:"November",12:"Desember"};if(!recurrenceRule.Unit||"Undefined"===recurrenceRule.Unit)return"Engangsoppgave";if("Once"===recurrenceRule.Unit&&recurrenceRule.PeriodNumber)return text="Aktiv",recurrenceRule.StartDate&&(text+=" fra "+$filter("date")(recurrenceRule.StartDate,"dd.MM.yyyy"),recurrenceRule.EndDate&&(text+=" til "+$filter("date")(recurrenceRule.EndDate,"dd.MM.yyyy"))),text;var text;if(text="Year"===recurrenceRule.Unit?["Hvert"]:["Hver"],recurrenceRule.Interval>2)text.push(recurrenceRule.Interval);else if(2===recurrenceRule.Interval){var ending="Year"===recurrenceRule.Unit?"t":"n";text[0]="Anne"+ending+text[0].toLowerCase()}if(text.push(translationService.getEnumTranslation("TimeUnit",recurrenceRule.Unit).toLowerCase()),recurrenceRule.ByDay&&recurrenceRule.ByDay.length){"Week"===recurrenceRule.Unit&&text.push("på"),"Day"===recurrenceRule.Unit&&text.splice(text.length-1,1);var tmpDayArray=[];recurrenceRule.ByDay.forEach(function(byDay,index){tmpDayArray.push(day[byDay])}),text.push(tmpDayArray.join(", "))}return recurrenceRule.ByMonthDay&&recurrenceRule.ByMonth&&recurrenceRule.ByMonthDay.length&&!recurrenceRule.ByMonth.length&&(text[0]=text[0].toLowerCase(),text.unshift("Dag "+recurrenceRule.ByMonthDay[0])),recurrenceRule.ByMonthDay&&recurrenceRule.ByMonth&&recurrenceRule.ByMonthDay.length&&recurrenceRule.ByMonth.length&&(text[0]=text[0].toLowerCase(),text.unshift(recurrenceRule.ByMonthDay[0]+"."+month[recurrenceRule.ByMonth[0]])),recurrenceRule.Until?(text.push("til"),text.push($filter("date")(recurrenceRule.Until,"dd.MM.yyyy"))):recurrenceRule.Count&&(text.push(recurrenceRule.Count),text.push("gang"+recurrenceRule.Count>1?"er":"")),recurrenceRule.PeriodNumber&&(text.push("og varer i "+recurrenceRule.PeriodNumber),"Day"===recurrenceRule.PeriodUnit?text.push(recurrenceRule.PeriodNumber>1?" dager":" dag"):"Week"===recurrenceRule.PeriodUnit?text.push(recurrenceRule.PeriodNumber>1?" uker":" uke"):"Month"===recurrenceRule.PeriodUnit&&text.push(recurrenceRule.PeriodNumber>1?" måneder":" måned")),text.join(" ")}}angular.module("Plania").filter("plRecurrenceRuleFilter",["$filter","$rootScope","TranslationService",filter])}(),function(){angular.module("Plania").filter("round",function(){return function(value,mult,dir){return dir=dir||"nearest",mult=mult||1,value=value?Number(value):0,"up"===dir?Math.ceil(value/mult)*mult:"down"===dir?Math.floor(value/mult)*mult:Math.round(value/mult)*mult}})}(),function(){angular.module("Plania").filter("time",function(){var conversions={ss:angular.identity,mm:function(value){return 60*value},hh:function(value){return 3600*value}},padding=function(value,length){for(var zeroes=length-(""+value).length,pad="";zeroes-- >0;)pad+="0";return pad+value};return function(value,unit,format,isPadded){var totalSeconds=conversions[unit||"ss"](value),hh=Math.floor(totalSeconds/3600),mm=Math.floor(totalSeconds%3600/60),ss=totalSeconds%60;return format=format||"hh:mm:ss",isPadded=!angular.isDefined(isPadded)||isPadded,hh=isPadded?padding(hh,2):hh,mm=isPadded?padding(mm,2):mm,ss=isPadded?padding(ss,2):ss,format.replace(/hh/,hh).replace(/mm/,mm).replace(/ss/,ss)}})}(),function(){function controller($scope,$rootScope,repository,commonService,$localStorage,$q,$state,translationService){$scope.dataOwnerInfo=new function(){function setInternal(selected){commonService.setDataOwner(selected),me.selected=commonService.getFilterData().selectedDataOwner||{}}var me=this;this.columns=["Id","Description","Dimension1","DefaultDocumentType.Id","WoXEqDocumentCategory.Description","Country","CountryCode"],this.count=10,this.totalCount=0,this.filter={},this.selected=commonService.getFilterData().selectedDataOwner||{},this.entities=[],this.loadList=function(){me.filter.includeAllDataOwners=!1;var deferred=$q.defer();return repository.GetPaginated(repository.apiData.dataOwner.url,0,me.count,{id:"asc"},me.filter,me.selected.Guid,JSON.stringify(me.columns)).then(function(result){result&&result.List&&(me.totalCount=result.TotalCount,me.entities=result.List),deferred.resolve()},function(error){repository.showError(error),deferred.reject()}),deferred.promise},this.init=function(){me.loadList().then(function(){if(me.selected.Guid){var selected=_.find(me.entities,function(o){return o.Guid===me.selected.Guid});selected&&setInternal(selected)}})},this.loadMore=function(){me.count",Value:"-1"}),$scope.filters.PropertyFilter.push({Property:"Type",Operator:"<>",Value:"0"}),$scope.filters.PropertyFilter.push({Property:"Type",Operator:"<>",Value:"3"})),"WorkOrderXResourceGroup"===$state.params.entityData.prefix&&$scope.filters.PropertyFilter.push({Property:"GuidPerson",Operator:"=",Value:repository.authService.getUserData().guidPerson}),"Project"===$state.params.entityData.prefix&&($scope.filters.IsTemplate="projectTemplate.list"===$state.current.name),"PeriodicTask"===$state.params.entityData.prefix&&("periodicTaskTemplate.list"===$state.current.name?$scope.filters.PropertyFilter.push({Property:"TemplateType",Operator:"=",Value:"PeriodicTemplate"}):"workOrderTemplate.list"===$state.current.name?$scope.filters.PropertyFilter.push({Property:"TemplateType",Operator:"=",Value:"WorkOrderTemplate"}):$scope.filters.PropertyFilter.push({Property:"TemplateType",Operator:"=",Value:"Periodic"})),"UserXExternalLogin"!==$state.params.entityData.prefix&&"UserXUserNotification"!==$state.params.entityData.prefix||($scope.clickable=!1),"WorkOrder"===$state.params.entityData.prefix&&($scope.showProjectLinkButton=!1,$scope.hasModule("ProjectManagement")&&$scope.hasEditAccess("Project")))if($scope.userInfo.isSystemAdministrator||$scope.userInfo.isProjectAdministrator)$scope.showProjectLinkButton=!0;else{var filterModel={Condition:"and",Rules:[{Property:"ClosedDate",Operator:"=",value:null},{Property:"IsTemplate",Operator:"=",value:!1},{Condition:"or",Rules:[{Property:"GuidOwnerPerson",Operator:"=",value:$scope.userInfo.guidPerson},{Property:"GuidManagerPerson",Operator:"=",value:$scope.userInfo.guidPerson}]}]},anyActiveProjects={Prefix:"Project",FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,FilterModel:filterModel,Properties:[{Property:"Id",Function:"count"}]};repository.createSingle(repository.apiData.kpi.url,anyActiveProjects).then(function(result){isViewDestroyed||result&&result[0].Result&&result[0].Result[0].Value>0&&($scope.showProjectLinkButton=!0)})}$scope.datePickers={startFromDate:!1,startToDate:!1,endFromDate:!1,endToDate:!1},$scope.open=function($event,calendar){$scope.datePickers[calendar]=!$scope.datePickers[calendar],$event.preventDefault(),$event.stopPropagation()},function(){var prefix=$state.params.entityData.prefix;$state.params.entityData.prefix===repository.apiData.userGroup.prefix&&(prefix=repository.apiData.user.prefix),$scope.restrictEdit=!repository.authService.hasEditAccess(prefix),$scope.restrictCreate=!repository.authService.hasCreateAccess(prefix)}();var showPostOnTop=!1;$scope.$on("$stateChangeSuccess",function(event,toState,toParams,fromState,fromParams){var prefix=$state.params.entityData.prefix;$scope.fromState=fromState.name,fromState.name===prefix.charAt(0).toLowerCase()+prefix.slice(1)+".edit"?("WorkOrder"===prefix&&($scope.filters.ActivityStatus=$localStorage.workOrderActivityStatus),"Project"===prefix&&"projectTemplate.list"!==$state.current.name&&($scope.filters.ActivityStatus=$localStorage.projectActivityStatus)):($localStorage.workOrderActivityStatus="Active",$localStorage.projectActivityStatus="Active"),(fromState.name===prefix.charAt(0).toLowerCase()+prefix.slice(1)+".create"||"Customer"===prefix&&"housingCustomer.create"===fromState.name)&&(showPostOnTop=!0)}),$scope.preSelected=repository.commonService.getLastRegisterGuid($scope.navigation.current.name);var getItems=function(){$scope.items=listService.getNgTableParams($scope.selectedListSetup,$scope.navigation,$state.params.entityData,showPostOnTop?$scope.preSelected:null,$scope.filters)},getSelectedItems=function(){var tableItems=[];return $scope.items&&$scope.selectedList.length?($scope.selectedListSetup&&$scope.selectedListSetup.GroupBy?$scope.items.data.forEach(function(group){group.data&&group.data.forEach(function(item){tableItems.push(item)})}):tableItems=$scope.items.data,tableItems=_.filter(tableItems,function(item){return $scope.selectedList.includes(item.Guid)})):tableItems};$scope.getWebListViews=function(selectedSetup,overwriteSelected){$scope.navigation.params.menuGuid&&(menuParams=repository.getMenuParameters($scope.navigation.params.menuGuid),menuParams.selectedWebListView&&menuParams.selectedWebListView.Guid&&(selectedSetup=menuParams.selectedWebListView));var filterString=repository.location.search().filter;if(filterString)try{urlFilter=listCompressionService.decodeListUri(filterString)}catch(e){repository.growl(e,"danger")}urlFilter&&!overwriteSelected&&(selectedSetup=urlFilter.selectedListSetup,urlFilter.filter?$scope.filters=urlFilter.filter:$scope.selectedListSetup.Filter&&($scope.filters=$scope.selectedListSetup.Filter));var ignoredFilterPropertiesForShowFilter=["PropertyFilter","searchString","ActivityStatus","CleaningStatus","isBuildingDependent","isCorrectiveAction","active","IsTemplate","GetAll"];if($scope.filters)for(var filter in $scope.filters)-1===ignoredFilterPropertiesForShowFilter.indexOf(filter)&&$scope.filters[filter]&&($scope.showFilter=!0);listService.getWebListViews(selectedSetup,$state.params.entityData.prefix,!1,$scope.contextId,$scope.filters).then(function(result){if(!isViewDestroyed){$scope.listOptions=result.listOptions,$scope.selectedListSetup=result.selectedListSetup;var planiaStandard=$scope.listOptions.find(function(option){return option.IsPlaniaStandard});urlFilter&&(selectedSetup&&(selectedSetup.Guid||selectedSetup.inMemory)||($scope.selectedListSetup=planiaStandard)),menuParams&&(selectedSetup||menuParams.selectedWebListView&&menuParams.selectedWebListView.Guid||($scope.selectedListSetup=planiaStandard)),"AreaXCleaningTask"===$state.params.entityData.prefix&&repository.authService.getUserData().guidPerson&&repository.getSingle(repository.apiData.person.url,repository.authService.getUserData().guidPerson,JSON.stringify(["ResourceGroup.Id"])).then(function(result){if(!isViewDestroyed){var person=result.Data;person.GuidResourceGroup&&person.DoesCleaningTasks&&($scope.selectedResourceGroup=person.ResourceGroup.Id,menuParams||(menuParams={}),menuParams.guidResourceGroup=person.GuidResourceGroup)}}),$scope.selectedListSetup.Filter&&($scope.filters=$scope.selectedListSetup.Filter),$scope.items||getItems()}})},$scope.resetFilter=function(){if($scope.filters)for(var filter in $scope.filters)"PropertyFilter"!==filter&&"searchString"!==filter&&"ActivityStatus"!==filter&&"CleaningStatus"!==filter&&"GetAll"!==filter&&($scope.filters[filter]=null)},$scope.getWebListViews(),$scope.$watch("selectedListSetup",function(newValue,oldValue){oldValue!==newValue&&($scope.selectedListSetup.VisibleColumns=_.filter($scope.selectedListSetup.Columns,function(c){return!c.Filter||!c.Filter.some(function(f){return f.Hidden})}),$scope.items&&($scope.items.$params.sorting=$scope.selectedListSetup.Sorting,listService.updateSelectedListSetup($state.params.entityData.prefix,$scope.selectedListSetup),$scope.selectedListSetup.GroupBy?$scope.items.settings().groupBy=function(obj){return listService.getGroupName($state.params.entityData.prefix,obj)}:$scope.items.settings().groupBy=null,$scope.items.reload()))}),$scope.$on($scope.events.newSelection,function(){$scope.getWebListViews()}),$scope.$on("$destroy",function(){isViewDestroyed=!0}),$scope.toggleTreeView=function(){$scope.showTreeView=!$scope.showTreeView,$localStorage["showTreeView"+$state.params.entityData.prefix]=$scope.showTreeView},$scope.selectedList=[],$scope.preSelected&&$scope.selectedList.push($scope.preSelected),$scope.addSelected=function(guid){if(_.contains($scope.selectedList,guid))for(var i=0;i<$scope.selectedList.length;i++){var p=$scope.selectedList[i];if(p===guid)return void $scope.selectedList.splice(i,1)}else $scope.selectedList.push(guid)},$scope.isSelected=function(guid){return _.contains($scope.selectedList,guid)},$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.getGroupedByHeaderValue=function(groupByColumnValue){if($scope.selectedListSetup.GroupBy){var column=_.find($scope.selectedListSetup.Columns,function(c){return c.Property===$scope.selectedListSetup.GroupBy});if(column&&column.PropertyType&&column.PropertyType.startsWith("enum.")){var enumType=column.PropertyType.split(".")[1];if(enumType)return translationService.translate("web-enum-"+enumType+"-"+groupByColumnValue)}}return groupByColumnValue},$scope.markRow=function(item){return!!$localStorage.generalOptions&&item.HasUnreadComments};var openEquipmentOperatingHoursModal=function(item){$scope.hasEditAccess("EquipmentOperatingHours")&&$modal.open({templateUrl:"app/equipment/views/equipmentOperatingHoursModal.html",controller:"EquipmentOperatingHoursController",size:"sm",resolve:{params:function(){return item}}}).result.then(function(result){$scope.items.reload()},function(){})},openImageModal=function(item){$modal.open({templateUrl:"app/document/views/editImageModal.html",controller:"EditImageController",size:"lg",resolve:{params:function(){return{image:item,viewOnly:!0}}}}).result.then(function(result){},function(){})},openImageXEntityModal=function(item){var imageXEntity=angular.copy(item);imageXEntity.image=imageXEntity.Image,imageXEntity.deleteAccess=$scope.hasDeleteAccess("ImageXEntity"),imageXEntity.guidEntity=imageXEntity["Guid"+imageXEntity.LinkedEntityType],$modal.open({templateUrl:"app/document/views/editImageModal.html",controller:"EditImageController",size:"lg",resolve:{params:function(){return imageXEntity}}}).result.then(function(result){result&&$scope.items.reload()},function(){})};$scope.goToEdit=function(item,event){var itemPrefix=$state.params.entityData.prefix;if("ControlListXEntity"===itemPrefix||"ControlListItemAnswer"===itemPrefix){var params={restrictEdit:!0};return params.workOrderCaption="ControlListXEntity"===itemPrefix?item.WorkOrder.Caption:item.ControlListXEntity.WorkOrder.Caption,params.controlList="ControlListXEntity"===itemPrefix?item.ControlList:item.ControlListXEntity.ControlList,params.controlListXEntity="ControlListXEntity"===itemPrefix?item:{Guid:item.GuidControlListXEntity},void $modal.open({templateUrl:"app/controlList/views/controlListCompletionModal.html",size:"xl",controller:"ControlListCompletionModalController",resolve:{params:function(){return params}}})}if("AreaXCleaningTask"===itemPrefix){var tabs={cleaningCompletion:{visible:repository.authService.hasCreateAccess(repository.apiData.cleaningCompletion.prefix),active:!0},cleaningInfo:{visible:repository.authService.hasReadAccess(repository.apiData.areaXCleaningTask.prefix),active:!1},cleaningRequest:{visible:repository.authService.hasCreateAccess(repository.apiData.areaXCleaningTask.prefix),active:!1},technicalRequest:{visible:repository.authService.hasCreateAccess(repository.apiData.request.prefix),active:!1}};return void $modal.open({templateUrl:"app/dwg/views/dwgSelectionModal.html",size:"lg",controller:"DwgSelectionModalController",resolve:{params:function(){return{guid:item.GuidArea,tabInfo:tabs,task:item}}}})}if("PurchaseOrderItem"===itemPrefix){if(!$scope.hasEditAccess("PurchaseOrderItem"))return;return void $modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"xl",resolve:{params:function(){return{Guid:item.Guid}}}}).result.then(function(result){$scope.items.reload()},function(){})}if("EquipmentOperatingHours"===itemPrefix)return void openEquipmentOperatingHoursModal(item);if("Image"===itemPrefix)return void openImageModal(item);if("ImageXEntity"===itemPrefix)return void openImageXEntityModal(item);if("WorkOrderXResourceGroup"===itemPrefix)return void($scope.hasReadAccess("WorkOrder")&&$rootScope.go("workOrder.edit",{guid:item.GuidWorkOrder,menuGuid:$scope.navigation.params.menuGuid},event));if("Drawing"===$state.params.entityData.prefix&&"cleaning.dwg.list"===$state.current.name){var guid="DocumentXEntity"===itemPrefix?item.GuidDocument:item.Guid;return void($scope.userInfo.guidPerson&&$scope.hasReadAccess("Person")?repository.getSingle(repository.apiData.person.url,$scope.userInfo.guidPerson).then(function(result){result.Data.DoesCleaningTasks?$rootScope.go($state.params.entityData.navigationState,{guid:guid,menuGuid:$scope.navigation.params.menuGuid,selectedTheme:"cleaning"},event):$rootScope.go($state.params.entityData.navigationState,{guid:guid,menuGuid:$scope.navigation.params.menuGuid,theme:"cleaningMaintenance"},event)},function(error){$rootScope.go($state.params.entityData.navigationState,{guid:guid,menuGuid:$scope.navigation.params.menuGuid,theme:"cleaningMaintenance"},event)}):$rootScope.go($state.params.entityData.navigationState,{guid:guid,menuGuid:$scope.navigation.params.menuGuid,theme:"cleaningMaintenance"},event))}if("CleaningCompletion"===itemPrefix)return void $modal.open({templateUrl:"app/cleaningCompletion/views/cleaningCompletionModal.html",size:"lg",controller:"CleaningCompletionModalController",resolve:{params:function(){return{guid:item.Guid}}}});if("DataImport"===itemPrefix)return item.InputConfig&&"Bim"===item.InputConfig.Type&&$rootScope.go("dataImport.bim",{guid:item.Guid,menuGuid:$scope.navigation.params.menuGuid},event),void(item.InputConfig&&"Excel"===item.InputConfig.Type&&$rootScope.go("dataImport.edit",{guid:item.Guid,menuGuid:$scope.navigation.params.menuGuid},event));if($scope.clickable)if($state.params.modal)$modal.open({templateUrl:$state.params.modal.templateUrl,controller:$state.params.modal.controller,resolve:{params:function(){return{guid:item.Guid,menuGuid:$scope.navigation.params.menuGuid,modalParam:$state.params.modal.modalParam}}}}).result.then(function(result){$scope.items.reload()});else{var itemGuid="DocumentXEntity"===itemPrefix?item.GuidDocument:item.Guid;$rootScope.go($state.params.entityData.navigationState,{guid:itemGuid,menuGuid:$scope.navigation.params.menuGuid},event)}},$scope.massEditEnabled=function(){return $scope.generalOptions.EnableMassEdit||$scope.hasModule("DataAcquisition")},$scope.massEdit=function(){0===$scope.selectedList.length?swal("Ingen valg",translationService.translate("list-mass-edit-missingSelect","Ingen valg. Velg en eller flere rader fra listen for å masseredigere"),"error"):$modal.open({templateUrl:"app/common/views/massEditModal.html",controller:"MassEditModalController",resolve:{params:function(){return{columns:$scope.selectedListSetup.Columns,selectedRows:$scope.selectedList,selectedRowsObjects:_.filter($scope.items.data,function(o){return _.contains($scope.selectedList,o.Guid)}),prefix:$state.params.entityData.prefix}}}}).result.then(function(editedRows){$scope.items.reload()},function(){})},$scope.bulkDelete=function(){0===$scope.selectedList.length?swal("Ingen valg",translationService.translate("list-mass-delete-missingSelect","Ingen valg. Velg en eller flere rader fra listen for å masseslette"),"error"):swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-listService-delete-message","Valgte objekter vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-listService-button-confirm","Ja, fjern objektene!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null;var promises=[];$scope.selectedList.forEach(function(row){var guid=row.Guid;void 0===guid&&(guid=row),promises.push(repository.deleteSingle($state.params.entityData.url,guid))}),$q.all(promises).then(function(result){swal(translationService.translate("web-swal-listService-success","Objektene ble fjernet!"),"","success"),$scope.items.reload(),$scope.selectedList=[]})})},$scope.copy=function(guid){var selectedList=guid?[guid]:$scope.selectedList;if(selectedList.length<1)swal("Ingen valg",translationService.translate("list-copy-missingSelect","Velg en rader fra listen for å kopiere."),"error");else if(selectedList.length>1)swal("Ingen valg",translationService.translate("list-copy-toomanyselected","Du kan kun kopiere én rad om gangen."),"error");else{var prefix=$state.params.entityData.prefix,selectedGuid=selectedList[0];switch(prefix){case"PeriodicTask":repository.getSingle(repository.apiData.periodicTask.url,selectedGuid).then(function(result){var periodicTask=result.Data;periodicTask.IsTemplate||periodicTask.GuidTemplate?swal({title:translationService.translate("web-swal-create-copy-without-reference-to-template","Opprett en redigerbar kopi uten koblinger mot malbygg?"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-button-confirm","Ja"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.navigation.go(prefix.charAt(0).toLowerCase()+prefix.slice(1)+".create",{guidEntityToCopy:selectedGuid})}):$scope.navigation.go(prefix.charAt(0).toLowerCase()+prefix.slice(1)+".create",{guidEntityToCopy:selectedGuid})});break;case"Area":"housing.edit"===$state.params.entityData.navigationState?$scope.navigation.go("housing.create",{guidEntityToCopy:selectedGuid}):$scope.navigation.go(prefix.charAt(0).toLowerCase()+prefix.slice(1)+".create",{guidEntityToCopy:selectedGuid});break;case"WebDashboard":if($scope.loadingStates.isCreatingWebDashboardCopy)return;$scope.loadingStates.isCreatingWebDashboardCopy=!0,registeredFieldService.getRegisteredField(repository.commonService.prefix.WebDashboard).then(function(registeredFields){var idRule=_.filter(registeredFields,{DomainFieldName:"Id"})[0],maxLength=30;idRule&&idRule.MaxLength&&idRule.MaxLength>0&&(maxLength=idRule.MaxLength),repository.getSingle(repository.apiData.webDashboard.url,"00000000-0000-0000-0000-000000000000","&GuidCopyFrom="+selectedGuid).then(function(result){var webDashboardToCreate=result.Data,newId=webDashboardToCreate.Id+" "+translationService.translate("web-listController-webDashboard-copy-defaultIdSuffix","(kopi)");newId=newId.substring(0,maxLength),swal({title:translationService.translate("web-listController-webDashboard-copy-swalTitle","Nytt navn for kopi"),type:"input",showCancelButton:!0,closeOnConfirm:!1,inputValue:newId},function(text){return window.onkeydown=null,window.onfocus=null,!1===text?($scope.loadingStates.isCreatingWebDashboardCopy=!1,!1):""===text?(swal.showInputError(translationService.translate("web-listController-webDashboard-copy-id-mandatory","Id er obligatorisk for dashbord")),!1):text.length>maxLength?(swal.showInputError(translationService.translate("web-listController-webDashboard-copy-id-tooLong","Id overskrider maks antall tegn -")+" "+maxLength),!1):(swal.close(),webDashboardToCreate.Id=text,void repository.createSingle(repository.apiData.webDashboard.url,webDashboardToCreate).then(function(response){$scope.navigation.go("dashboard.view",{guid:response.Guid}),$scope.loadingStates.isCreatingWebDashboardCopy=!1},function(error){repository.showError(error),$scope.loadingStates.isCreatingWebDashboardCopy=!1}))})},function(error){repository.showError(error),$scope.loadingStates.isCreatingWebDashboardCopy=!1})},function(){$scope.loadingStates.isCreatingWebDashboardCopy=!0});break;default:$scope.navigation.go(prefix.charAt(0).toLowerCase()+prefix.slice(1)+".create",{guidEntityToCopy:selectedGuid})}}},$scope.documentExport=function(){if(!$scope.selectedList||0===$scope.selectedList.length)return void swal(translationService.translate("web-swal-document-exportDocument-title","Dokumenteksport"),translationService.translate("web-swal-document-exportDocument-noItems","Ingen rader markert. Marker en eller flere rader for eksport"),"error");repository.createSingle(repository.apiData.document.endpoint.exportSizeEstimate,$scope.selectedList,"preFix="+$scope.prefix).then(function(result){swal({title:translationService.translate("web-swal-document-exportDocument-title","Dokumenteksport"),text:translationService.translate("web-swal-document-exportDocument-message","Eksport av dokument kan ta tid, ønsker du å fortsette?\r\n Estimert total størrelse:")+" "+result.TotalSize,type:"info",showCancelButton:!0,confirmButtonColor:"#337ab7",confirmButtonText:translationService.translate("web-button-yes-continue","Ja, fortsett"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.createSingle(repository.apiData.document.endpoint.exportToken,$scope.selectedList,"preFix="+$scope.prefix).then(function(result){if(result.Token){var url=config.baseUrlApi+repository.apiData.document.endpoint.exportDownload+"?token="+result.Token;window.open(url,"_self"),swal(translationService.translate("web-swal-document-exportDocument-title","Dokumenteksport"),translationService.translate("web-swal-document-exportDocument-successMessage","Nedlasting starter innen kort tid"),"success")}},function(error){swal.close(),repository.showError(error)})})},function(error){repository.showError(error)})},$scope.updateReports=function(){$modal.open({templateUrl:"app/report/views/updateReport.html",controller:"UpdateReportController",size:"lg"}).result.then(function(){repository.growl("Rapporter har blitt oppdatert","info"),$scope.items.reload()},function(){})},$scope.openDocument=function(document){documentService.openDocument(document)},$scope.addNewDocument=function(){$modal.open({templateUrl:"app/document/views/createDocumentModal.html",controller:"CreateDocumentController",size:"lg"}).result.then(function(guids){1===guids.length||"string"==typeof guids?(guid=1===guids.length?guids[0]:guids,$scope.navigation.go("document.edit",{guid:guid},{reload:!0})):($scope.preSelected=guids,guids.forEach(function(r){$scope.selectedList.push(r)}),$scope.items.reload())},function(){$scope.items.reload()})},$scope.addOperationalMessage=function(){$modal.open({templateUrl:"app/operationalMessage/views/operationalMessageModal.html",controller:"OperationalMessageModalController",resolve:{params:function(){return{}}}}).result.then(function(){$scope.items.reload()})},$scope.addEntityCounter=function(){$modal.open({templateUrl:"app/entityCounter/views/entityCounterModal.html",controller:"EntityCounterModalController",resolve:{params:function(){return{}}}}).result.then(function(){$scope.items.reload()})},$scope.editDrawing=function(drawing){$scope.navigation.go("dwg.edit",{guid:drawing.Guid},{reload:!0})},$scope.addNewDrawing=function(){$scope.navigation.go("dwg.create",{},{reload:!0})},$scope.addNewBimFile=function(){$modal.open({templateUrl:"app/bimFile/views/createBimFileModal.html",controller:"CreateBimFileModalController",resolve:{modalParams:function(){return{}}}}).result.then(function(guids){1===guids.length||"string"==typeof guids?(guid=1===guids.length?guids[0]:guids,$scope.navigation.go("bimFile.edit",{guid:guid},{reload:!0})):($scope.preSelected=guids,guids.forEach(function(r){$scope.selectedList.push(r)}),$scope.items.reload())},function(){$scope.items.reload()})},$scope.createSparePart=function(){$modal.open({templateUrl:"app/sparePart/views/createSparePartModal.html",controller:"CreateSparePartModalController"}).result.then(function(sparePart){$scope.navigation.go("sparePart.edit",{guid:sparePart.Guid},{reload:!0})},function(){$scope.items.reload()})},$scope.createScheduledJob=function(){$modal.open({templateUrl:"app/scheduledJob/views/createScheduledJobModal.html",controller:"CreateScheduledJobModalController"}).result.then(function(result){$scope.navigation.go("scheduledJob.create",{scheduledJobModel:result})},function(){})},$scope.flushLogPerformance=function(){repository.createSingle("LogPerformance",{}).then(function(result){swal("Log performance har blitt lagret","Log performance har blitt lagret til database","success")})},$scope.createWorkOrdersFromCondition=function(){$modal.open({templateUrl:"app/workOrder/views/createWoFromConditionModal.html",controller:"CreateWoFromConditionModalController",size:"xl",resolve:{params:function(){return{SelectedListSetup:$scope.selectedListSetup}}}}).result.then(function(result){$scope.items.reload()},function(){})},$scope.closeDeviationDirectly=function(selectedGuid){$modal.open({templateUrl:"app/deviation/views/closeDeviationDirectlyModal.html",controller:"CloseDeviationDirectlyModalController",resolve:{params:function(){return{guid:selectedGuid,close:!0}}}}).result.then(function(result){$scope.items.reload()})},$scope.createWorkOrder=function(isCondition,selectedGuid){var workOrder={fromDeviation:!isCondition,fromCondition:isCondition},exitFunction=!1,errorMessage1="",errorMessage2="";if(!selectedGuid&&0===$scope.selectedList.length){var message="";return message=isCondition?translationService.translate("correctiveAction-list-createworkorder-missingSelect","Ingen tiltak valgt. Velg en eller flere fra listen for å lage arbeidsordre."):translationService.translate("deviation-list-createworkorder-missingSelect","Ingen avvik valgt. Velg en eller flere fra listen for å lage arbeidsordre."),void swal("Ingen valg",message,"error")}var guidList=[];if(guidList=selectedGuid?[selectedGuid]:$scope.selectedList,workOrder.guidSelections=guidList,guidList.forEach(function(guid){var tableItems=[];$scope.selectedListSetup&&$scope.selectedListSetup.GroupBy?$scope.items.data.forEach(function(group){group.data&&group.data.forEach(function(item){tableItems.push(item)})}):tableItems=$scope.items.data,tableItems.forEach(function(item){item.Guid===guid&&(!workOrder.guidEstate&&item.GuidEstate&&(workOrder.guidEstate=item.GuidEstate,item.Estate&&(workOrder.estate=item.Estate.Caption)),!workOrder.guidBuilding&&item.GuidBuilding&&(workOrder.guidBuilding=item.GuidBuilding,item.Building&&(workOrder.building=item.Building.Caption)),!workOrder.guidEquipment&&item.GuidEquipment&&(workOrder.guidEquipment=item.GuidEquipment,item.Equipment&&(workOrder.equipment=item.Equipment.Caption)),!workOrder.guidArea&&item.GuidArea&&(workOrder.guidArea=item.GuidArea,item.Area&&(workOrder.area=item.Area.Caption)),item.Estate&&workOrder.guidEstate!==item.GuidEstate&&(errorMessage1=isCondition?translationService.translate("web-listview-createWorkOrder-condition-differentEstate","Det er bare mulig å opprette arbeidsordre fra tiltak på samme eiendom. "):translationService.translate("web-listview-createWorkOrder-deviation-differentEstate","Det er bare mulig å opprette arbeidsordre fra avvik på samme eiendom. "),exitFunction=!0), item.Building&&workOrder.guidBuilding!==item.GuidBuilding&&(errorMessage1=isCondition?translationService.translate("web-listview-createWorkOrder-condition-differentBuilding","Det er bare mulig å opprette arbeidsordre fra tiltak på samme bygg. "):translationService.translate("web-listview-createWorkOrder-deviation-differentBuilding","Det er bare mulig å opprette arbeidsordre fra avvik på samme bygg. "),exitFunction=!0),item.Status&&"New"!==item.Status&&(errorMessage2=isCondition?translationService.translate("web-listview-createWorkOrder-condition-statusIsNotNew","Du kan ikke generere arbeidsordre på et tiltak som ikke har status lik ny. "):translationService.translate("web-listview-createWorkOrder-deviation-statusIsNotNew","Du kan ikke generere arbeidsordre på et avvik som ikke har status lik ny. "),exitFunction=!0),item.GuidCorrectiveWorkOrder&&(errorMessage2=isCondition?translationService.translate("web-listview-createWorkOrder-condition-hasGuidCorrectiveWorkOrder","Bare nye tiltak kan generere arbeidsordre. "):translationService.translate("web-listview-createWorkOrder-deviation-hasGuidCorrectiveWorkOrder","Bare nye avvik kan generere arbeidsordre. "),exitFunction=!0),isCondition&&"CurrentConditionInfo"===item.Type&&(errorMessage2=translationService.translate("web-listview-createWorkOrder-condition-isCurrentConditionInfo","Kan ikke opprette arbeidsordre fra tilstandsinformasjon."),exitFunction=!0),workOrder.defaultDescription=isCondition?translationService.translate("correctiveAction-new-workOrder-defaultDescription","Gjennomføring av tiltak"):translationService.translate("deviation-new-workOrder-defaultDescription","Utbedring av avvik"),1===guidList.length&&(isCondition||(workOrder.defaultText=item.ActionComment,workOrder.defaultDescription=translationService.translate("deviation-new-workOrder-description","Utbedring av")+" "+item.Id,item.GuidDeviationType&&(item.DeviationType&&item.DeviationType.Id?workOrder.defaultDescription+=" - "+item.DeviationType.Id:workOrder.enumTypeGuid=item.GuidDeviationType))))})}),exitFunction)return void swal("Feilmelding",errorMessage1+errorMessage2,"error");repository.persistedData.setPersistedData("workOrder.create",workOrder),$scope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})},$scope.confirmCondition=function(guid){var selection=guid?[guid]:[];if($scope.selectedList.length>0&&(selection=[],$scope.selectedList.forEach(function(guid){selection.push(guid)})),!selection.length)return void swal("Ingen valg",translationService.translate("web-list-confirmCondition-missingSelect","Ingen valg. Velg en eller flere rader fra listen for å bekrefte tilstand/tiltak."),"error");$modal.open({templateUrl:"app/condition/views/conditionConfirmVersionModal.html",controller:"ConditionConfirmVersionModalController",size:"md",resolve:{modalParams:function(){return{guids:selection}}}}).result.then(function(){$scope.items.reload(),$scope.selectedList=[]})},$scope.createWorkOrderFromPeriodicTask=function(guid){if(($scope.userInfo.canRunSystemFunction||$scope.userInfo.canRunNewPeriod)&&$scope.hasEditAccess("WorkOrder")&&(guid||!("periodicTaskTemplate"===$scope.routeEntity||"workOrderTemplate"===$scope.routeEntity||$scope.selectedList.length<=0||$scope.selectedList.length>20)))return 0!==$scope.selectedList.length||guid?$scope.selectedList.length>20&&!guid?void swal("For mange valgt",translationService.translate("web-list-createWorkOrderFromPeriodicTask-tooManySelect","For mange periodiske rutiner er valgt. Maksgrensen er 20 periodiske rutiner."),"error"):void $modal.open({templateUrl:"app/periodicTask/views/periodicTaskGenerateOrdersConfirmationModal.html",controller:"PeriodicTaskGenerateOrdersConfirmationModalController",resolve:{params:function(){return{guids:guid?[guid]:$scope.selectedList}}},size:"lg"}).result.then(function(result){$scope.items.reload()},function(){}):void swal("Ingen valg",translationService.translate("web-list-createWorkOrderFromPeriodicTask-missingSelect","Ingen valg. Velg en eller flere rader fra listen for å opprette AO."),"error")},$scope.connectWorkOrdersToProject=function(guid){if(guid||0!==$scope.selectedList.length){var filter={FilterModel:{Condition:"and",Rules:[{Property:"ClosedDate",Operator:"=",value:null},{Property:"IsTemplate",Operator:"=",value:0}]}};$scope.userInfo.isSystemAdministrator||$scope.userInfo.isProjectAdministrator||filter.FilterModel.Rules.push({Condition:"or",Rules:[{Property:"GuidOwnerPerson",Operator:"=",value:$scope.userInfo.guidPerson},{Property:"GuidManagerPerson",Operator:"=",value:$scope.userInfo.guidPerson}]}),swal({title:translationService.translate("web-swal-project-modify-workOrder-warning","Dette kan påvirke prosjektets økonomi, ønsker du å fortsette?"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-button-yes-continue","Ja, fortsett"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal.close(),$modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:translationService.translate("web-workOrder-connect-project","Velg prosjekt å koble arbeidsordrene til"),url:repository.apiData.project.url,sorting:{CreationDate:"desc"},filter:filter,columns:[{title:translationService.translate("web-project-Id","Ao Nr"),property:"Id"},{title:translationService.translate("web-project-Description","Beskrivelse"),property:"Description",PropertyType:"String"},{title:translationService.translate("web-project-Building-Id","Bygg Id"),property:"Building.Id"},{title:translationService.translate("web-project-Building-Description","Byggbeskrivelse"),property:"Building.Description",PropertyType:"String"}]}}}}).result.then(function(selectedEntity){repository.updateMultipleWithGuid(repository.apiData.project.endpoint.addWorkOrders,selectedEntity.Guid,guid?[guid]:$scope.selectedList).then(function(result){guid?repository.growl(translationService.translate("web-project-connectSingle-workOrder-success","Arbeidsordren har blitt koblet til prosjektet"),"success"):repository.growl(translationService.translate("web-project-connect-workOrder-success","Arbeidsordrene har blitt koblet til prosjektet"),"success"),$scope.items.reload()},function(error){swal(translationService.translate("web-project-connectWorkOrders-error-title","En eller flere feiler oppstod under kobling til prosjekt"),error,"error"),$scope.items.reload()})})})}else swal("Ingen valg",translationService.translate("web-list-connectProject-edit-missingSelect","Ingen valg. Velg en eller flere rader fra listen for å koble til prosjekt"),"error")},$scope.closeWorkOrderReinvoicing=function(guid){$scope.generalOptions.UseReinvoicing&&$scope.hasModule("Invoice")&&$scope.userInfo.canRunSystemFunction&&$scope.hasEditAccess("WorkOrder")&&(guid||0!==$scope.selectedList.length?swal({title:translationService.translate("web-swal-workOrder-closeWorkOrderReinvoicing-title","Bekreft sluttfakturering"),text:translationService.translate("web-swal-workOrder-closeWorkOrderReinvoicing-message","Dette vil sette alle valgte arbeidsordre som har en faktureringsstatus til sluttfakturert.\n\n Hvis mange arbeidsordre er valgt, så kan operasjonen ta lang tid."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-button-yes-continue","Ja, fortsett"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.runAction(repository.apiData.workOrder.endpoint.closeReinvoicing,guid?[guid]:$scope.selectedList).then(function(result){swal(translationService.translate("web-workorder-close-reinvoicing-success","Arbeidsordrene er sluttfakturert"),result,"success"),$scope.items.reload()})}):swal("Ingen valg",translationService.translate("web-list-setInvoiced-edit-missingSelect","Ingen valg. Velg en eller flere rader fra listen for sluttfakturering"),"error"))},$scope.sendWorkOrdersToHistory=function(){($scope.userInfo.canRunSystemFunction||$scope.userInfo.canRunNewPeriod)&&$scope.hasEditAccess("WorkOrder")&&$modal.open({templateUrl:"app/workOrder/views/sendWorkOrderToHistoryModal.html",controller:"SendWorkOrderToHistoryModalController",size:"xl",resolve:{params:function(){return{SelectedListSetup:$scope.selectedListSetup}}}}).result.then(function(result){$scope.items.reload()},function(){})},$scope.forceLogout=function(){0===$scope.selectedList.length?swal("Ingen valg",translationService.translate("web-webUserToken-selectedList-missing","Ingen valg. Velg en eller flere brukere for kaste dem ut av systemet"),"error"):swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-webUserToken-selectedList-logout-confirmationMessage","Valgte brukere vil bli kastet ut av Plania, men dette vil ikke sperre dem fra å logge inn på nytt"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-webUserToken-selectedList-logout-confirm","Ja, kast ut brukere!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,repository.updateMultiple($state.params.entityData.url+"forceLogout/",$scope.selectedList).then(function(result){swal(translationService.translate("web-webUserToken-delete-success","Brukerene har blitt kastet ut"),"","success"),$scope.items.reload(),$scope.selectedList=[]})})},$scope.generateCalendarEvent=function(guid){if(!guid&&$scope.selectedList.length<1)return void swal("Ingen valg",translationService.translate("web-list-missingSelect","Velg minst en rad i listen"),"error");var filter={};filter.PropertyFilter=guid?[{Property:"Guid",Operator:"=",value:guid}]:[{Property:"Guid",Operator:"in",value:$scope.selectedList.join(",")}],repository.getWithUrlParameter(repository.apiData.workOrderCalendar.url,"calendar=true",filter).then(function(response){var blob=new Blob([response],{type:"text/calendar"});if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(blob,translationService.translate("web-workorder-calendar-filename","arbeidsordrer")+".ics");else{var element=document.createElement("a");element.style.display="none",element.href=window.URL.createObjectURL(blob),element.download=translationService.translate("web-workorder-calendar-filename","arbeidsordrer")+".ics",document.body.appendChild(element),element.click(),document.body.removeChild(element),window.URL.revokeObjectURL(element.href)}},function(error){repository.growl(error,"danger")})};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.contextMenu=new function(){var me=this;this.useDefaultParentObjectNavigation=!0,this.addDefaultParentObjectNavigation=function(item,options){if($rootScope.userInfo.enableWebNavigation&&this.useDefaultParentObjectNavigation){var navigationOptions=[];!item.GuidEstate||item.GuidBuilding||item.GuidEquipment||item.GuidArea||!$scope.hasReadAccess("Estate")||navigationOptions.push(getMenuLink($rootScope.navigation.href("estate.edit",{guid:item.GuidEstate}),translationService.translate("web-listview-contextMenu-common-viewEstate","Gå til eiendom"))),item.GuidBuilding&&!item.GuidEquipment&&!item.GuidArea&&$scope.hasReadAccess("Building")&&navigationOptions.push(getMenuLink($rootScope.navigation.href("building.edit",{guid:item.GuidBuilding}),translationService.translate("web-listview-contextMenu-common-viewBuilding","Gå til bygg"))),item.GuidEquipment&&$scope.hasReadAccess("Equipment")&&navigationOptions.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:item.GuidEquipment}),translationService.translate("web-listview-contextMenu-common-viewEquipment","Gå til anlegg"))),item.GuidArea&&$scope.hasReadAccess("Area")&&(item.Area&&item.Area.IsHousing?navigationOptions.push(getMenuLink($rootScope.navigation.href("housing.edit",{guid:item.GuidArea}),translationService.translate("web-listview-contextMenu-common-viewHousing","Gå til bolig"))):navigationOptions.push(getMenuLink($rootScope.navigation.href("area.edit",{guid:item.GuidArea}),translationService.translate("web-listview-contextMenu-common-viewArea","Gå til areal")))),navigationOptions.length>0&&(navigationOptions[0].hasTopDivider=!!options.length,navigationOptions.forEach(function(o){options.push(o)}))}},this.getOptions=function(item){var itemPrefix=$state.params.entityData.prefix,options=[],getOptions=me[itemPrefix];return getOptions?(getOptions(item,options),me.addDefaultParentObjectNavigation(item,options)):options.push({html:''}),options},this.hasOptions=function(){var itemPrefix=$state.params.entityData.prefix;return!!me[itemPrefix]},this.WorkOrderXResourceGroup=function(item,options){$scope.hasReadAccess("WorkOrder")&&item.GuidWorkOrder&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidWorkOrder}),translationService.translate("web-listview-contextMenu-workOrderXResourceGroup-viewWorkOrder","Gå til arbeidsordre")))},this.EquipmentOperatingHours=function(item,options){options.push({html:' '+translationService.translate("web-listview-contextMenu-equipmentOperatingHours-view","Åpne anleggstimer")+"",click:function($itemScope,$event,modelValue,text,$li){openEquipmentOperatingHoursModal(item)}}),$scope.hasReadAccess("Equipment")&&item.GuidEquipment&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:item.GuidEquipment}),translationService.translate("web-listview-contextMenu-equipment-view","Gå til anlegg")))},this.EntityCounter=function(item,options){options.push({html:' '+translationService.translate("web-listview-contextMenu-entityCounter-view","Åpne autonummerering")+"",click:function($itemScope,$event){$scope.goToEdit(item,$event)}}),$scope.hasDeleteAccess("EntityCounter")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-entityCounter-delete","Slett")+"",click:function($itemScope,$event,modelValue,text,$li){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-entityCounter-message","Autonummereringen vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-entityCounter-button-confirm","Ja, fjern autonummereringen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.deleteSingle(repository.apiData.entityCounter.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-entityCounter-success","Autonummereringen ble fjernet!"),result,"success"),$scope.items.reload()},function(error){swal("Error",error,"error")})})}})},this.Contract=function(item,options){"reinvoicingContract.list"===$state.current.name?options.push(getMenuLink($rootScope.navigation.href("reinvoicingContract.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-reinvoicingContract-view","Åpne avtale"))):options.push(getMenuLink($rootScope.navigation.href("contract.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-contract-view","Åpne kontrakt"))),$scope.hasReadAccess("Customer")&&item.GuidCustomer&&$rootScope.userInfo.enableWebNavigation&&("reinvoicingContract.list"===$state.current.name?options.push(getMenuLink($rootScope.navigation.href("housingCustomer.edit",{guid:item.GuidCustomer}),translationService.translate("web-listview-contextMenu-reinvoicingContract-viewHousingCustomer","Gå leietaker"))):options.push(getMenuLink($rootScope.navigation.href("customer.edit",{guid:item.GuidCustomer}),translationService.translate("web-listview-contextMenu-contract-viewCustomer","Gå til kunde"))))},this.Estate=function(item,options){options.push(getMenuLink($rootScope.navigation.href("estate.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-estate-view","Åpne eiendom")))},this.Building=function(item,options){options.push(getMenuLink($rootScope.navigation.href("building.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-building-view","Åpne bygg")))},this.Equipment=function(item,options){options.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-equipment-view","Åpne anlegg")))},this.Area=function(item,options){item.IsHousing?options.push(getMenuLink($rootScope.navigation.href("housing.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-housing-view","Åpne bolig"))):options.push(getMenuLink($rootScope.navigation.href("area.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-area-view","Åpne areal"))),$scope.hasReadAccess("Drawing")&&item.GuidDrawing&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("dwg.view",{guid:item.GuidDrawing}),translationService.translate("web-listview-contextMenu-area-viewDrawing","Gå til SVG-visningen"))),item.GuidIfc&&options.push(getMenuLink($rootScope.navigation.href("bimFile.viewBim",{guidArea:item.Guid}),translationService.translate("web-listview-contextMenu-area-viewBimsyncModel","Gå til bim modell")))},this.Drawing=function(item,options){if("cleaning.dwg.list"===$state.current.name)return[];options.push(getMenuLink($rootScope.navigation.href("dwg.view",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-drawing-view","Åpne SVG-visningen"))),options.push(getMenuLink($rootScope.navigation.href("dwg.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-drawing-editPage","Åpne tegningssiden")))},this.Article=function(item,options){options.push(getMenuLink($rootScope.navigation.href("article.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-article-view","Åpne artikkel")))},this.Document=function(item,options){options.push(getMenuLink($rootScope.navigation.href("document.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-document-view","Åpne dokument siden"))),options.push({html:' '+translationService.translate("web-listview-contextMenu-document-openDocument","Åpne dokument fil")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.openDocument(item)}})},this.DocumentXEntity=function(item,options){me.useDefaultParentObjectNavigation=!1,options.push(getMenuLink($rootScope.navigation.href("document.edit",{guid:item.Document.Guid}),translationService.translate("web-listview-contextMenu-document-view","Åpne dokument siden"))),options.push({html:' '+translationService.translate("web-listview-contextMenu-document-openDocument","Åpne dokument fil")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.openDocument(item.Document)}});var prefix=item.EntityType,entityRoute=prefix.charAt(0).toLowerCase()+prefix.slice(1),entityGuid=item["Guid"+prefix],routeExists=repository.apiData[entityRoute];if(routeExists){var title=translationService.translate("web-listview-contextMenu-documentXEntity-openEntity","Gå til")+" "+translationService.translate("web-"+prefix).toLowerCase();options.push(getMenuLink($rootScope.navigation.href(routeExists.navigationState,{guid:entityGuid}),title))}},this.Component=function(item,options){options.push(getMenuLink($rootScope.navigation.href("component.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-component-view","Åpne komponent")))},this.Customer=function(item,options){"List-HousingCustomer"===$scope.contextId?options.push(getMenuLink($rootScope.navigation.href("housingCustomer.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-housingCustomer-view","Åpne leietaker"))):options.push(getMenuLink($rootScope.navigation.href("customer.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-customer-view","Åpne kunde")))},this.Supplier=function(item,options){options.push(getMenuLink($rootScope.navigation.href("supplier.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-supplier-view","Åpne leverandør")))},this.Person=function(item,options){options.push(getMenuLink($rootScope.navigation.href("person.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-person-view","Åpne person")))},this.Budget=function(item,options){options.push(getMenuLink($rootScope.navigation.href("budget.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-budget-view","Åpne budsjett")))},this.Condition=function(item,options){if("CorrectiveAction"===item.Type?options.push(getMenuLink($rootScope.navigation.href("condition.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-condition-viewCorrectiveAction","Åpne tiltak"))):"CurrentConditionInfo"===item.Type?options.push(getMenuLink($rootScope.navigation.href("condition.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-condition-viewCurrentConditionInfo","Åpne gjeldende tiltak"))):options.push(getMenuLink($rootScope.navigation.href("condition.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-condition-view","Åpne tilstand"))),$scope.hasCreateAccess("Condition")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-condition-copy","Kopier valgt tilstand/tiltak")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.copy(item.Guid)}}),"CurrentConditionInfo"!==item.Type&&$scope.hasCreateAccess("WorkOrder")&&(!item.GuidCorrectiveWorkOrder&&"New"===item.Status||$scope.selectedList.length>0)){var htmlText=translationService.translate("web-listview-contextMenu-condition-createWorkOrder","Opprett arbeidsordre fra dette tiltaket");$scope.selectedList.length>0&&(htmlText=translationService.translate("web-listview-contextMenu-condition-createWorkOrderFromSelected","Opprett arbeidsordre fra valgte tiltak")+" ("+$scope.selectedList.length+")"),options.push({html:' '+htmlText+"",click:function($itemScope,$event,modelValue,text,$li){$scope.selectedList.length>0?$scope.createWorkOrder(!0):$scope.createWorkOrder(!0,item.Guid)}})}if($localStorage.generalOptions.UseNewCorrectiveAction){var confirmHtmlText=translationService.translate("web-listview-contextMenu-condition-confirmVersion","Bekreft");$scope.selectedList.length>0&&(confirmHtmlText=translationService.translate("web-listview-contextMenu-condition-confirmVersionFromSelected","Bekreft valgte")+" ("+$scope.selectedList.length+")"),options.push({html:' '+confirmHtmlText+"",click:function($itemScope,$event,modelValue,text,$li){$scope.confirmCondition(item.Guid)}})}"CurrentConditionInfo"!==item.Type&&$scope.hasReadAccess("WorkOrder")&&$rootScope.userInfo.enableWebNavigation&&(item.GuidInspectionWorkOrder&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidInspectionWorkOrder}),translationService.translate("web-listview-contextMenu-condition-viewInspectionWorkOrder","Gå til arbeidsordre som opprettet tiltaket"))),item.GuidCorrectiveWorkOrder&&("Closed"===item.Status?options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidCorrectiveWorkOrder}),translationService.translate("web-listview-contextMenu-condition-viewCorrectiveWorkOrderClosed","Gå til arbeidsordre som lukket tiltaket"))):options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidCorrectiveWorkOrder}),translationService.translate("web-listview-contextMenu-condition-viewCorrectiveWorkOrder","Gå til arbeidsordre som jobber med tiltaket")))))},this.ControlList=function(item,options){options.push({html:' '+translationService.translate("web-listview-contextMenu-controlList-view","Åpne kontrolliste")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.goToEdit(item)}}),$scope.hasCreateAccess("ControlList")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-controlList-copy","Kopier valgt kontrolliste")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.copy(item.Guid)}})},this.ControlListItemAnswer=function(item,options){options.push({html:' '+translationService.translate("web-listview-contextMenu-controlListItemAnswer-view","Åpne kontrollistesvar")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.goToEdit(item)}})},this.ControlListXEntity=function(item,options){options.push({html:' '+translationService.translate("web-listview-contextMenu-controlListXEntity-view","Åpne utfylt kontrolliste")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.goToEdit(item)}}),$scope.hasReadAccess("WorkOrder")&&item.GuidWorkOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidWorkOrder}),translationService.translate("web-listview-contextMenu-controlListXEntity-viewWorkOrder","Gå til arbeidsordre")))},this.Cost=function(item,options){options.push(getMenuLink($rootScope.navigation.href("cost.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-cost-view","Åpne kostnad"))),$scope.hasReadAccess("WorkOrder")&&item.GuidWorkOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidWorkOrder}),translationService.translate("web-listview-contextMenu-cost-viewWorkOrder","Gå til arbeidsordre"))),$scope.hasReadAccess("PurchaseOrder")&&item.GuidPurchaseOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:item.GuidPurchaseOrder}),translationService.translate("web-listview-contextMenu-cost-viewPurchaseOrder","Gå til bestilling"))),$scope.hasReadAccess("PurchaseOrderItem")&&item.GuidPurchaseOrderItem&&$rootScope.userInfo.enableWebNavigation&&options.push({html:' '+translationService.translate("web-listview-contextMenu-cost-viewPurchaseOrderItem","Åpne konteringsobjekt")+"",click:function($itemScope,$event,modelValue,text,$li){$modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"xl",resolve:{params:function(){return{Guid:item.GuidPurchaseOrderItem}}}})}})},this.Deviation=function(item,options){if(options.push(getMenuLink($rootScope.navigation.href("deviation.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-deviation-view","Åpne avvik"))),$scope.hasCreateAccess("WorkOrder")&&(!item.GuidCorrectiveWorkOrder&&"New"===item.Status||$scope.selectedList.length>0)){var htmlText=translationService.translate("web-listview-contextMenu-deviation-createWorkOrder","Opprett arbeidsordre fra dette avviket");$scope.selectedList.length>0&&(htmlText=translationService.translate("web-listview-contextMenu-deviation-createWorkOrderFromSelected","Opprett arbeidsordre fra valgte avvik")+" ("+$scope.selectedList.length+")"),options.push({html:' '+htmlText+"",click:function($itemScope,$event,modelValue,text,$li){$scope.selectedList.length>0?$scope.createWorkOrder(!1):$scope.createWorkOrder(!1,item.Guid)}})}$scope.hasReadAccess("WorkOrder")&&$rootScope.userInfo.enableWebNavigation&&(item.GuidInspectionWorkOrder&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidInspectionWorkOrder}),translationService.translate("web-listview-contextMenu-deviation-viewInspectionWorkOrder","Gå til arbeidsordre som opprettet avviket"))),item.GuidCorrectiveWorkOrder&&("Closed"===item.Status?options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidCorrectiveWorkOrder}),translationService.translate("web-listview-contextMenu-deviation-viewCorrectiveWorkOrderClosed","Gå til arbeidsordre som lukket avviket"))):options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidCorrectiveWorkOrder}),translationService.translate("web-listview-contextMenu-deviation-viewCorrectiveWorkOrder","Gå til arbeidsordre som jobber med avviket"))))),$scope.selectedList.length<=1&&"Closed"!==item.Status&&$scope.hasEditAccess("Deviation")&&!item.GuidCorrectiveWorkOrder&&options.push({html:' '+translationService.translate("web-deviation-followUpContextMenu-closeDeviationDirectly","Lukk avvik direkte")+"",click:function(){$scope.closeDeviationDirectly(item.Guid)}})},this.OperationalMessage=function(item,options){options.push({html:' '+translationService.translate("web-listview-contextMenu-operationalMessage-view","Åpne driftsmelding")+"",click:function($itemScope,$event){$scope.goToEdit(item,$event)}}),item.GuidWorkOrder&&$scope.hasEditAccess("OperationalMessage")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-operationalMessage-removeWorkOrder","Fjern fra arbeidsordren")+"",click:function(){repository.patch(repository.apiData.operationalMessage.url,item.Guid,{GuidWorkOrder:null}).then(function(response){repository.growl(translationService.translate("web-operationalMessage-removeWorkOrder-success","Driftsmeldingen ble fjernet fra arbeidsordren"),"success"),$scope.items.reload()},function(error){repository.showError(error)})}}), item.GuidWorkOrder?options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidWorkOrder}),translationService.translate("web-listview-contextMenu-operationalMessage-viewWorkOrder","Gå til arbeidsordre"))):$scope.hasCreateAccess("WorkOrder")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-operationalMessage-createWorkOrder","Opprett arbeidsordre")+"",click:function(){operationalMessageService.createWorkOrder(item)}}),$scope.hasDeleteAccess("OperationalMessage")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-operationalMessage-delete","Slett")+"",click:function($itemScope,$event,modelValue,text,$li){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-operationalMessage-message","Driftsmeldingen vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-operationalMessage-button-confirm","Ja, fjern driftsmeldingen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.deleteSingle(repository.apiData.operationalMessage.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-operationalMessage-success","Driftsmeldingen ble fjernet!"),result,"success"),$scope.items.reload()},function(error){swal("Error",error,"error")})})}})},this.Project=function(item,options){me.useDefaultParentObjectNavigation=!item.IsTemplate,item.IsTemplate?options.push(getMenuLink($rootScope.navigation.href("projectTemplate.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-projectTemplate-view","Åpne prosjektmal"))):options.push(getMenuLink($rootScope.navigation.href("project.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-project-view","Åpne prosjekt")))},this.PeriodicTask=function(item,options){me.useDefaultParentObjectNavigation=!item.IsTemplate,"PeriodicTemplate"===item.TemplateType?options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-periodicTemplate-view","Åpne malrutine"))):"WorkOrderTemplate"===item.TemplateType?options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-workOrderTemplate-view","Åpne aktivitetsmal"))):options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-periodicTask-view","Åpne periodisk"))),($scope.userInfo.canRunSystemFunction||$scope.userInfo.canRunNewPeriod)&&$scope.hasEditAccess("WorkOrder")&&(options.push({html:' '+translationService.translate("web-listview-contextMenu-periodicTask-createWorkOrderFromPeriodicTask","Opprett arbeidsordre fra denne rutinen")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.createWorkOrderFromPeriodicTask(item.Guid)},enabled:"periodicTaskTemplate"!==$scope.routeEntity&&"workOrderTemplate"!==$scope.routeEntity}),options.push({html:' '+translationService.translate("web-listview-contextMenu-periodicTask-createWorkOrderFromSelectedPeriodicTasks","Opprett arbeidsordre fra valgte rutiner ("+$scope.selectedList.length+"/20)")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.createWorkOrderFromPeriodicTask()},enabled:"periodicTaskTemplate"!==$scope.routeEntity&&"workOrderTemplate"!==$scope.routeEntity&&$scope.selectedList.length>0&&$scope.selectedList.length<=20}))},this.PurchaseOrder=function(item,options){options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-purchaseOrder-view","Åpne bestilling")))},this.PurchaseOrderItem=function(item,options){$scope.hasEditAccess("PurchaseOrderItem")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-purchaseOrderItem-view","Åpne konteringsobjekt")+"",click:function($itemScope,$event,modelValue,text,$li){$modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"xl",resolve:{params:function(){return{Guid:item.Guid}}}}).result.then(function(result){$scope.items.reload()},function(){})}}),$scope.hasCreateAccess("Cost")&&"Proposal"!==item.Status&&"Closed"!==item.Status&&options.push({html:' '+translationService.translate("web-listview-contextMenu-purchaseOrderItem-createCost","Legg til kostnad")+"",click:function($itemScope,$event,modelValue,text,$li){var persistedData={};persistedData.GuidPurchaseOrderItem=item.Guid,repository.persistedData.setPersistedData("cost.create",persistedData),$scope.$parent.navigation.go("cost.create",{showPersistantData:!0},{reload:!0})}}),$scope.hasReadAccess("PurchaseOrder")&&item.GuidPurchaseOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:item.GuidPurchaseOrder}),translationService.translate("web-listview-contextMenu-purchaseOrderItem-viewPurchaseOrder","Gå til bestilling"))),$scope.hasReadAccess("WorkOrder")&&item.GuidWorkOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidWorkOrder}),translationService.translate("web-listview-contextMenu-purchaseOrderItem-viewWorkOrder","Gå til arbeidsordre")))},this.Request=function(item,options){options.push(getMenuLink($rootScope.navigation.href("request.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-request-view","Åpne melding")))},this.SparePart=function(item,options){options.push(getMenuLink($rootScope.navigation.href("sparePart.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-sparePart-view","Åpne reservedel"))),$scope.hasReadAccess("Component")&&item.GuidComponent&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("component.edit",{guid:item.GuidComponent}),translationService.translate("web-listview-contextMenu-sparePart-viewComponent","Gå til komponent")))},this.SparePartCounting=function(item,options){options.push(getMenuLink($rootScope.navigation.href("sparePartCounting.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-sparePartCounting-view","Åpne varetelling")))},this.SparePartWithdrawal=function(item,options){options.push(getMenuLink($rootScope.navigation.href("sparePartWithdrawal.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-sparePartWithdrawal-view","Åpne uttakshistorikk"))),$scope.hasReadAccess("SparePart")&&item.GuidSparePart&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("sparePart.edit",{guid:item.GuidSparePart}),translationService.translate("web-listview-contextMenu-sparePartWithdrawal-viewSparePart","Gå til reservedel")))},this.WorkOrder=function(item,options){options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-workOrder-view","Åpne arbeidsordre"))),options.push({html:' '+translationService.translate("web-listview-contextMenu-workOrder-generateCalendarEvent","Last ned arbeidsordre for kalender")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.generateCalendarEvent(item.Guid)}}),"Active"===$scope.items.filter().ActivityStatus&&$scope.showProjectLinkButton&&$scope.hasModule("ProjectManagement")&&$scope.hasReadAccess("Project")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-workOrder-connectWorkOrdersToProject","Koble til prosjekt")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.connectWorkOrdersToProject(item.Guid)}}),$scope.generalOptions.UseReinvoicing&&$scope.hasModule("Invoice")&&$scope.userInfo.canRunSystemFunction&&$scope.hasEditAccess("WorkOrder")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-workOrder-closeWorkOrderReinvoicing","Sett som sluttfakturert")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.closeWorkOrderReinvoicing(item.Guid)}}),$rootScope.hasCreateAccess("WorkOrder")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-workOrder-copy","Kopier arbeidsordre")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.copy(item.Guid)}})},this.AreaXCleaningTask=function(item,options){options.push({html:' '+translationService.translate("web-listview-contextMenu-areaXCleaningTask-view","Åpne renholdsoppgave")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.goToEdit(item)}}),$scope.hasReadAccess("CleaningTask")&&item.GuidCleaningTask&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("cleaningTask.edit",{guid:item.GuidCleaningTask}),translationService.translate("web-listview-contextMenu-areaXCleaningTask-viewCleaningTask","Gå til renholdsoppgave definisjon")))},this.CleaningCompletion=function(item,options){options.push({html:' '+translationService.translate("web-listview-contextMenu-cleaningCompletion-view","Åpne renholdsaktivitet")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.goToEdit(item)}}),$scope.hasReadAccess("CleaningTask")&&item.GuidCleaningTask&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("cleaningTask.edit",{guid:item.GuidCleaningTask}),translationService.translate("web-listview-contextMenu-areaXCleaningTask-viewCleaningTask","Gå til renholdsoppgave definisjon")))},this.CleaningQualityControl=function(item,options){options.push(getMenuLink($rootScope.navigation.href("cleaningQualityControl.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-cleaningQualityControl-view","Åpne INSTA kontroll")))},this.CleaningTask=function(item,options){options.push(getMenuLink($rootScope.navigation.href("cleaningTask.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-cleaningTask-view","Åpne renholdsoppgave definisjon")))},this.BimFile=function(item,options){options.push(getMenuLink($rootScope.navigation.href("bimFile.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-bimFile-view","Åpne bim fil administrasjon")));var selectedItems=getSelectedItems();selectedItems.length?options.push({html:' '+translationService.translate("web-listview-contextMenu-bimFile-viewModels","Se modeller")+" ("+selectedItems.length+")",click:function($itemScope,$event,modelValue,text,$li){var validItems=_.filter(selectedItems,function(item){return item.GuidBimProject&&item.ExternalId&&item.ModelVersion});if(!validItems.length)return void swal(translationService.translate("web-listview-contextmenu-bimFile-viewModels-missingValidModels-title","Ingen gyldige modeller."),translationService.translate("web-listview-contextmenu-bimFile-viewModels-missingValidModels-message","Velg minst 1 modell som er ferdig prossessert."),"error");if(!_.every(selectedItems,{GuidBimProject:validItems[0].GuidBimProject}))return void swal(translationService.translate("web-listview-contextmenu-bimFile-viewModels-notSameBimProject-title","Modeller er på forskjellige prosjekter/eiendommer."),translationService.translate("web-listview-contextmenu-bimFile-viewModels-notSameBimProject-message","Alle valgte modeller må være under samme prosjekt/eiendom."),"error");var selectedGuids=selectedItems.map(function(item){return item.Guid}).join(",");$rootScope.navigation.go("bimFile.viewBim",{guidBimProject:validItems[0].GuidBimProject,guidBimFile:selectedGuids})}}):item.GuidBimProject&&item.ExternalId&&item.ModelVersion&&options.push(getMenuLink($rootScope.navigation.href("bimFile.viewBim",{guidBimProject:item.GuidBimProject,guidBimFile:item.Guid}),translationService.translate("web-listview-contextMenu-bimFile-viewBimsync","Se modell")))},this.DataImport=function(item,options){$scope.hasCreateAccess("DataImport")&&(options.push(getMenuLink($rootScope.navigation.href("dataImport.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-dataImport-view","Åpne dataimport"))),item.InputConfig&&item.InputConfig.Type&&options.push({html:' '+translationService.translate("web-listview-contextMenu-dataImport-copy","Opprett ny fra eksisterende")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.navigation.go("Bim"===item.InputConfig.Type?"dataImport.bim":"dataImport.edit",{guidEntityToCopy:item.Guid})}})),$scope.hasDeleteAccess("DataImport")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-dataImport-delete","Slett dataimport")+"",click:function($itemScope,$event,modelValue,text,$li){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-listview-contextMenu-dataImport-deleteMessage","Dataimport vil bli fjernet"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-button-confirm","Ja"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.dataImport.url,item.Guid).then(function(){repository.growl("Dataimport slettet","success"),$scope.items.reload(),swal.close()})})}})},this.WebDashboard=function(item,options){$scope.hasCreateAccess("WebDashboard")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-webDashboard-copy","Lag kopi")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.copy(item.Guid)},enabled:!$scope.loadingStates.isCreatingWebDashboardCopy})},this.ChangeSet=function(item,options){me.useDefaultParentObjectNavigation=!0,options.push({html:' '+translationService.translate("web-listview-contextMenu-changeSet-view","Åpne endringsett")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.goToEdit(item)}});var prefix=item.EntityType,entityRoute=prefix.charAt(0).toLowerCase()+prefix.slice(1),entityGuid=item.GuidEntity,routeExists=repository.apiData[entityRoute];if(routeExists){var title=translationService.translate("web-listview-contextMenu-changeSet-openEntity","Gå til")+" "+translationService.translate("web-"+prefix).toLowerCase();options.push(getMenuLink($rootScope.navigation.href(routeExists.navigationState,{guid:entityGuid}),title))}},this.ScheduledJobExecution=function(item,options){options.push(getMenuLink($rootScope.navigation.href("scheduledJobExecution.edit",{guid:item.Guid}),translationService.translate("web-listview-contextMenu-scheduledJobExecution-view","Åpne utført bakgrunnsjobb"))),$scope.hasReadAccess("ScheduledJob")&&item.GuidScheduledJob&&options.push(getMenuLink($rootScope.navigation.href("scheduledJob.edit",{guid:item.GuidScheduledJob}),translationService.translate("web-listview-contextMenu-scheduledJob-view","Åpne bakgrunnsjobb")))},this.ImageXEntity=function(item,options){me.useDefaultParentObjectNavigation=!1,options.push({html:' '+translationService.translate("web-listview-contextMenu-imageXEntity-view","Åpne bildereferanse")+"",click:function($itemScope,$event,modelValue,text,$li){openImageXEntityModal(item)}});var prefix=item.LinkedEntityType,entityRoute=prefix.charAt(0).toLowerCase()+prefix.slice(1),entityGuid=item["Guid"+prefix],routeExists=repository.apiData[entityRoute];if(routeExists&&routeExists.allowEntityNavigation){var title=translationService.translate("web-listview-contextMenu-imageXEntity-openEntity","Gå til")+" "+translationService.translate("web-"+prefix).toLowerCase();options.push(getMenuLink($rootScope.navigation.href(routeExists.navigationState,{guid:entityGuid}),title))}},this.UserXExternalLogin=function(item,options){options.push(getMenuLink($rootScope.navigation.href("user.edit",{guid:item.GuidUser}),translationService.translate("web-listview-contextMenu-user-view","Gå til bruker")))}},$scope.autoCompleteFilter=function(filterName){switch(filterName){case"resourceGroup":return{PropertyFilter:[{Property:"DoesCleaningTasks",Operator:"=",Value:!0}]}}}}])}(),function(){function controller($scope,$modalInstance,$modal,params,repository,translationService,$localStorage){$scope.model=params.listSetup,$scope.hideFilters=params.hideFilters,$scope.keywords=repository.filterKeyWords,$scope.user=repository.authService.getUserData();var updateStableColumns=function(){$scope.columns=angular.copy($scope.model.Columns)};updateStableColumns(),$scope.advancedWebListFiltering=$localStorage.generalOptions.AdvancedWebListFiltering;var originalColumnSetup=params.listSetup.Columns.slice(),originalObject=_.clone(params.listSetup);$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.WebListView,!1),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.WebListView,!1),$scope.sortingParams=[{name:"Stigende",value:"asc"},{name:"Synkende",value:"desc"}];for(var i in $scope.model.Sorting)$scope.sortingProperty=i,$scope.sortingParam=$scope.model.Sorting[i];$scope.addFilter=function(column){column.Filter?column.Filter.push({Operator:"=",Property:column.Property}):column.Filter=[{Operator:"=",Property:column.Property}]},$scope.addNewColumn=function(){$modal.open({templateUrl:"app/common/views/addNewListColumnModal.html",controller:"AddNewListColumnController",resolve:{params:function(){return{prefix:$scope.model.EntityName||$scope.model.EntityType,existingColumns:$scope.model.Columns,showAdvancedMode:$scope.advancedWebListFiltering}}}}).result.then(function(selectedColumns){selectedColumns.forEach(function(column){$scope.model.Columns.push(column),updateStableColumns()})})},$scope.filterSortingColumns=function(){return function(column){return"CleaningEstimateYear"!==column.Property&&"EstimatedTimeYear"!==column.Property&&"NextCleaning"!==column.Property}},$scope.removeColumn=function(index){var setNewSorting=!1;$scope.model.Columns[index].Property===$scope.sortingProperty&&(setNewSorting=!0),$scope.model.Columns.splice(index,1),setNewSorting&&($scope.sortingProperty=$scope.model.Columns[0].Property),updateStableColumns()};var handleDateFilter=function(filter){filter.Property.indexOf("Date")>=0&&filter.Value&&"[object Date]"===Object.prototype.toString.call(filter.Value)&&(filter.Value=new Date(filter.Value).toISOString())},handleEnumFilter=function(filter){Array.isArray($scope.model.Columns)&&$scope.model.Columns.forEach(function(col){col.Property&&col.PropertyType&&col.PropertyType.startsWith("enum.")&&col.Property===filter.Property&&("in"===filter.Operator||"notin"===filter.Operator?Array.isArray(filter.Value)||(filter.Value=[]):Array.isArray(filter.Value)&&(filter.Value=filter.Value[0]))})},setColumnPositionOnModel=function(model){for(var i=0;i=0&&(column.PropertyType="autocomplete",column.AutocompleteProperty="GuidCleaningQuality",column.AutocompleteService="cleaningQuality"),entityPrefix===repository.apiData.area.prefix&&column.Property.indexOf("ResourceGroup.")>=0&&(column.PropertyType="autocomplete",column.AutocompleteProperty="GuidCleaningTeam",column.AutocompleteService="resourceGroup"),"recurrence"!==column.PropertyType.toLowerCase()&&"recurrencerule"!==column.PropertyType.toLowerCase()||(column.RecurrenceRule={},column.StartDate=new Date,$scope.showPeriodicCleaningRecurrence?column.RecurrenceRule={StartDate:new Date,Unit:"Once",PeriodNumber:1,PeriodUnit:"Day"}:column.RecurrenceRule={StartDate:new Date,Unit:"Day"},$scope.model=column),$scope.columns.push(column)))})}),$scope.selectedRows=params.selectedRows,$scope.selectedColumns=[{}],$scope.getSelectedRowCaption=function(result){var object=_.find(params.selectedRowsObjects,{Guid:result.Guid});return object.Caption?object.Caption:object.Area.Caption?object.Area.Caption:object.Building.Caption?object.Building.Caption:void 0},$scope.save=function(){var editedRows=[];$scope.selectedRows.forEach(function(rowGuid){var editedRow={Guid:rowGuid};$scope.selectedColumns.forEach(function(column){column.model&&("recurrence"===column.model.PropertyType.toLowerCase()||"recurrencerule"===column.model.PropertyType.toLowerCase()?(column.model.RecurrenceRule&&(enumService.setTimeUnitOnRecurrence(column.model.RecurrenceRule),column.model.RecurrenceRule&&column.model.RecurrenceRule.StartDate&&(column.model.RecurrenceRule.StartDate=new Date(column.model.RecurrenceRule.StartDate).toISOString()),column.model.RecurrenceRule&&column.model.RecurrenceRule.EndDate&&(column.model.RecurrenceRule.EndDate=new Date(column.model.RecurrenceRule.EndDate).toISOString()),column.model.RecurrenceRule&&column.model.RecurrenceRule.Until&&(column.model.RecurrenceRule.Until=new Date(column.model.RecurrenceRule.Until).toISOString()),editedRow.RecurrenceRule=column.model.RecurrenceRule),column.model.StartDate&&(editedRow.StartDate=new Date(column.model.StartDate).toISOString()),column.model.UntilDate&&(editedRow.UntilDate=new Date(column.model.UntilDate).toISOString())):(column.model.NewValue||0===column.model.NewValue)&&("string"===column.model.PropertyType||"number"===column.model.PropertyType?editedRow[column.model.Property]=column.model.NewValue:"autocomplete"===column.model.PropertyType?editedRow[column.model.AutocompleteProperty]=column.model.newPropertyValue:"date"===column.model.PropertyType&&(editedRow[column.model.Property]=new Date(column.model.NewValue).toISOString())))}),editedRows.push(editedRow)}),repository.patch(entityApiData.url,null,editedRows).then(function(response){$scope.updateResult=response,_.every(response,function(response){return response.IsSuccess})&&$modalInstance.close()},function(error){repository.showError(error)})},$scope.columnWasSelected=function(column){var index=$scope.columns.indexOf(column);$scope.columns.splice(index,1),$scope.columns.length>0&&$scope.selectedColumns.push({})},$scope.removeSelectedColumn=function(column,index){$scope.selectedColumns.splice(index,1),0===$scope.columns.length&&$scope.selectedColumns.push({}),$scope.columns.push(column)},$scope.autocompleteFilter=function(filterName){var filter={};switch(filterName){case"resourceGroup":return entityPrefix===repository.commonService.prefix.AreaXCleaningTask&&(filter.FilterModel={Condition:"and",Rules:[{Property:"DoesCleaningTasks",Value:1,Operator:"="}]}),filter}},$scope.cancel=function(){$scope.updateResult?$modalInstance.close():$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("MassEditModalController",["$scope","$modalInstance","params","Repository","TranslationService","EnumService",controller])}(),function(){function controller($scope,$modalInstance,content){$scope.header=content.header,$scope.message=content.message,$scope.timestamp=content.timestamp,$scope.close=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("MessageModalController",["$scope","$modalInstance","content",controller])}(),function(){function controller($scope,$modalInstance,repository,documentService,$state,authService,translationService){$scope.model={isLoadingDocument:!0,isUpdatingUser:!1,document:null,hasConfirmed:!1,hasOpenedDocument:!1},repository.getSingleWithNoParameter(repository.apiData.generalOptions.endpoint.getTermsOfUseDocument).then(function(result){$scope.model.document=result.Data,$scope.model.isLoadingDocument=!1},function(error){repository.showError(error),$scope.model.isLoadingDocument=!1}),$scope.openDocument=function(document){$scope.model.hasOpenedDocument=!0,documentService.openDocument(document)},$scope.ok=function(){if($scope.model.document&&!$scope.model.hasOpenedDocument)return void swal(translationService.translate("web-acceptTermsOfUseModal-cannotConfirm-hasNotReadDocument-title","Du må åpne dokumentet før du kan trykke Godkjenn."),"","info");$scope.model.isUpdatingUser=!0,repository.runAction(repository.apiData.user.endpoint.acceptTermsOfUse).then(function(){$scope.model.isUpdatingUser=!1,authService.hasAcceptedTermsOfUse(),$modalInstance.close()},function(error){ $scope.model.isUpdatingUser=!1,repository.showError(error)})},$scope.cancel=function(){$modalInstance.dismiss(),$state.go("logout")}}angular.module("Plania").controller("AcceptTermsOfUseModalController",["$scope","$modalInstance","Repository","DocumentService","$state","authService","TranslationService",controller])}(),function(){function controller($scope,$modalInstance,params,ngTableParams,repository,translationService){$scope.model={GuidIfc:params.guidIfc},$scope.enableEditGlobalId=!1;var prefix=params.prefix,guid=params.guid,guidBuilding=params.guidBuilding,products=[];$scope.columns=[];var setColumns=function(){var columns=[];products.length&&products.every(function(product){return product.GuidIfc===products[0].GuidIfc})||columns.push({Position:1,Title:translationService.translate("web-bimProduct-modelName","Model"),Property:"ModelName",PropertyType:"string"}),columns.push({Position:2,Title:translationService.translate("web-bimProduct-storeyName","Etasje"),Property:"StoreyName",PropertyType:"string"}),columns.push({Position:3,Title:translationService.translate("web-bimProduct-productName","Navn"),Property:"ProductName",PropertyType:"string"}),$scope.columns=columns};setColumns(),function(){var url=repository.apiData.planiaBim.url;url+="building/"+guidBuilding,url+="/productConnections";var urlParms=["ifcType=IfcSpace"].join("&");repository.getWithUrlParameter(url,urlParms).then(function(result){products=result,setColumns(),$scope.productsTable.reload()},function(error){repository.growl(error,"danger")})}();var sortFunction=function(key){return function(a,b){var aVal=a[key],bVal=b[key];return aValbVal?1:0}},getFilteredData=function(filter){var filterText=filter.searchString.toLowerCase(),data=products;return filter.showConnected&&"0"!==filter.showConnected||(data=data.filter(function(product){return!product.GuidEntities||!product.GuidEntities.length||product.GuidEntities.includes(guid)})),data=data.filter(function(product){if(void 0===filterText||null===filterText||""===filterText.trim())return!0;var state=!1;return $scope.columns.forEach(function(column){(""+product[column.Property]).toLowerCase().includes(filterText)&&(state=!0)}),state})};$scope.productsTable=new ngTableParams({page:1,count:10,sorting:{StoreyName:"asc"},filter:{searchString:"",showConnected:"0"}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var data=getFilteredData(params.filter()),sortingKey=Object.keys(params.sorting())[0],direction=params.sorting()[sortingKey];data=data.sort(sortFunction(sortingKey)),"desc"===direction.toLowerCase()&&(data=data.reverse()),$scope.productsTable.settings().total=data.length,$scope.productsTable.settings().filterDelay=50,data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$defer.resolve(data)}}),$scope.selectProduct=function(product){$scope.model.GuidIfc=product.GlobalId};var getUrl=function(){switch(prefix){case"Area":return repository.apiData.area.url;default:return null}};$scope.toggleEditEnableGlobalId=function(){$scope.enableEditGlobalId=!$scope.enableEditGlobalId},$scope.save=function(){var url=getUrl();url&&guid||$scope.cancel(),repository.patch(url,guid,{GuidIfc:$scope.model.GuidIfc}).then(function(){repository.growl(translationService.translate("web-bimConnectionEdit-saved","Oppdatert referanse")),$modalInstance.close($scope.model.GuidIfc)},function(error){repository.growl(error,"danger")})},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("BimConnectionEditModalController",["$scope","$modalInstance","params","ngTableParams","Repository","TranslationService",controller])}(),function(){function controller($scope,$modalInstance,params){$scope.model={id:params.id},$scope.save=function(){$modalInstance.close($scope.model.id)},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("ChangeIdModalController",["$scope","$modalInstance","params",controller])}(),function(){function controller($scope,$modalInstance,params,$localStorage){$scope.viewModel={},$scope.user=params.user,$scope.mustChangePasswordProcess=params.mustChangePasswordProcess,$scope.passwordField={focus:!0};var generalOptions=$localStorage.generalOptions;$scope.passwordRules={PwdMinNumberChars:generalOptions.PwdMinNumberChars,PwdMustContainLetters:generalOptions.PwdMustContainLetters,PwdMustContainDigits:generalOptions.PwdMustContainDigits};var stringContainsANumber=function(text){return void 0!==text&&null!==text&&""!==text&&/\d/.test(text)},isCharacterALetter=function(char){return char.toLowerCase()!==char.toUpperCase()},stringContainsALetter=function(text){return void 0!==text&&null!==text&&""!==text&&_.some(text.split(""),function(char){return isCharacterALetter(char)})};$scope.isValid=function(){var newPassword=$scope.viewModel.NewPassword;return!!(newPassword&&$scope.viewModel.ConfirmPassword&&$scope.viewModel.OldPassword)&&(newPassword===$scope.viewModel.ConfirmPassword&&(!($scope.mustChangePasswordProcess&&newPassword.length<$scope.passwordRules.PwdMinNumberChars)&&(!($scope.mustChangePasswordProcess&&$scope.passwordRules.PwdMustContainLetters&&!stringContainsALetter(newPassword))&&!($scope.mustChangePasswordProcess&&$scope.passwordRules.PwdMustContainDigits&&!stringContainsANumber(newPassword)))))},$scope.getPwdMinNumberCharsIcon=function(){var newPassword=$scope.viewModel.NewPassword;return newPassword?newPassword.length<$scope.passwordRules.PwdMinNumberChars?"fa-circle-exclamation c-red":"fa-check-circle c-green":"fa-help"},$scope.getPwdMustContainLettersIcon=function(){var newPassword=$scope.viewModel.NewPassword;return newPassword?$scope.passwordRules.PwdMustContainLetters&&!stringContainsALetter(newPassword)?"fa-circle-exclamation c-red":"fa-check-circle c-green":"fa-help"},$scope.getPwdMustContainDigitsIcon=function(){var newPassword=$scope.viewModel.NewPassword;return newPassword?$scope.passwordRules.PwdMustContainDigits&&!stringContainsANumber(newPassword)?"fa-circle-exclamation c-red":"fa-check-circle c-green":"fa-help"},$scope.save=function(){params.saveOverride&&"function"==typeof params.saveOverride?params.saveOverride($scope.viewModel,$modalInstance):$modalInstance.close($scope.viewModel.NewPassword)},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("ChangePasswordModalController",["$scope","$modalInstance","params","$localStorage",controller])}(),function(){function controller($scope,$modalInstance,params,repository,translationService,$localStorage,$rootScope,$window){$scope.qrCode=angular.copy(params.qrCode),$scope.guidSparePart=params.guidSparePart,$scope.isUpdate=params.isUpdate,$scope.domainName=params.domainName,$scope.hidePrint=params.hidePrint,$scope.reloads={reload:!1,reloadQrCode:!1},repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix.Barcode).then(function(result){$scope.fieldRules=result,$scope.reload=!0}),$scope.generateBarcode=function(){repository.createSingle(repository.apiData.barcode.url,$scope.qrCode).then(function(result){repository.growl("QR-kode generert","success")},function(error){repository.growl(error,"danger")})},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-barcode-message","Qr-koden vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-barcode-button-confirm","Ja, fjern qr-koden"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){repository.deleteSingle(repository.apiData.barcode.url,$scope.qrCode.Guid).then(function(result){repository.growl("Qr-koden har blitt fjernet","success"),$modalInstance.close("deleted")})})},$scope.save=function(){$scope.isUpdate?repository.updateSingle(repository.apiData.barcode.url,$scope.qrCode).then(function(result){repository.growl("QR-kode oppdatert","success"),$modalInstance.close(result)}).catch(function(error){repository.growl(error,"danger")}):repository.createSingle(repository.apiData.barcode.url,$scope.qrCode).then(function(result){repository.growl("QR-kode opprettet","success"),$modalInstance.close("ok")},function(error){repository.growl(error,"danger")})},$scope.printLabel=function(){$scope.guidSparePart&&($scope.domainName="SparePart");var params={Guids:$scope.guidSparePart?JSON.stringify([$scope.guidSparePart]):JSON.stringify([$scope.qrCode["Guid"+$scope.domainName]]),GuidBarcode:$scope.qrCode.Guid};$localStorage.reportParams=JSON.stringify(params);var reportName="PrintLabel"+$scope.domainName,url=$rootScope.navigation.href("report.print",{reportName:reportName,reportParams:JSON.stringify(params)});$window.open(url,"_blank")},$scope.cancel=function(){$modalInstance.dismiss("cancelled")}}angular.module("Plania").controller("EditQrCodeModalController",["$scope","$modalInstance","params","Repository","TranslationService","$localStorage","$rootScope","$window",controller])}(),function(){function controller($scope,$modalInstance,$modal,params,repository,translationService){$scope.model=params.listSetup,$scope.user=repository.authService.getUserData();var originalColumnSetup=params.listSetup.Columns.slice();$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.WebListView,!1),$scope.addNewColumn=function(){$modal.open({templateUrl:"app/common/views/addNewListColumnModal.html",controller:"AddNewListColumnController",resolve:{params:function(){return{prefix:params.entity,existingColumns:$scope.model.Columns}}}}).result.then(function(selectedColumns){selectedColumns.forEach(function(column){$scope.model.Columns.push(column)})})},$scope.removeColumn=function(index){var setNewSorting=!1;$scope.model.Columns[index].Property===$scope.sortingProperty&&(setNewSorting=!0),$scope.model.Columns.splice(index,1),setNewSorting&&($scope.sortingProperty=$scope.model.Columns[0].Property)};var setColumnPositionOnModel=function(){for(var i=0;i<$scope.model.Columns.length;i++){var filter=$scope.model.Columns[i].Filter;filter&&(filter.forEach(handleDateFilter),$scope.model.Columns[i].Filter=JSON.stringify(filter)),$scope.model.Columns[i].Position=i+1}};$scope.cancel=function(){$scope.model.Columns=originalColumnSetup,$modalInstance.dismiss("canceled")},$scope.revertToDefault=function(){params.defaultListSetup&&($scope.model.Columns=params.defaultListSetup.Columns,$scope.save())},$scope.save=function(){setColumnPositionOnModel(),$scope.model.WebColumnsToSynchronize=$scope.model.Columns,repository.updateSingle(repository.apiData.webListView.url,$scope.model).then(function(result){repository.growl("Listeoppsettet har blitt lagret","success"),delete $scope.model.WebColumnsToSynchronize,$modalInstance.close("saved")})}}angular.module("Plania").controller("EditTableColumnsModalController",["$scope","$modalInstance","$modal","params","Repository","TranslationService",controller])}(),function(){function controller($scope,$modal,$modalInstance,repository,params,translationService,$rootScope){function getNonsReference(guidNonsReference){repository.getMainModel(repository.apiData.nonsReference.url,guidNonsReference).then(function(response){$scope.model=response.Data,$scope.directiveReady=!0,$scope.hasModel=!0},function(error){repository.growl(error,"danger"),$scope.directiveReady=!0,$scope.hasModel=!1})}if($scope.model={},$scope.directiveReady=!1,$scope.hasModel=!1,$scope.hasReadAccess=$rootScope.hasReadAccess("NonsReference"),$scope.hasDeleteAccess=$rootScope.hasDeleteAccess("NonsReference"),$scope.hasCreateAccess=$rootScope.hasCreateAccess("NonsReference"),$scope.hasEditAccess=$rootScope.hasEditAccess("NonsReference"),$scope.isDeleting=!1,$scope.entityModel=params.entityModel,params.entityModel.GuidNonsReference?getNonsReference(params.entityModel.GuidNonsReference):($scope.model.GuidEntity=params.entityModel.Guid,$scope.model.EntityType="Equipment"),$scope.isEdit=!params.entityModel.GuidNonsReference,!$scope.hasReadAccess)return void($scope.directiveReady=!0);$scope.edit=function(){$scope.isEdit=!0},$scope.save=function(){$scope.model.Guid?repository.updateSingle(repository.apiData.nonsReference.url,$scope.model).then(function(result){repository.growl(translationService.translate("web-nonsReference-updated","Nons reference oppdatert"),"success"),$scope.model=result,$scope.isEdit=!1}).catch(function(error){repository.growl(error,"danger")}):repository.createSingle(repository.apiData.nonsReference.url,$scope.model).then(function(result){repository.growl(translationService.translate("web-nonsReference-created","Nons reference ble lagt til"),"success"),$scope.model=result,$scope.isEdit=!1}).catch(function(error){repository.growl(error,"danger")})},$scope.cancel=function(){$scope.model.Guid?$scope.isEdit=!1:$modalInstance.close("dismissed")},$scope.close=function(){$modalInstance.close($scope.model)},$scope.deleteReference=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-nonsReference-message","Nons referanse vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-nonsReference-button-confirm","Ja, fjern referansen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){$scope.isDeleting=!0,repository.deleteSingle(repository.apiData.nonsReference.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-supplier-nonsReference-success","Referansen ble fjernet!"),result,"success"),$scope.hasModel=!1,$scope.entityModel.GuidNonsReference=void 0,$scope.model={},$scope.isDeleting=!1,$modalInstance.close("deleted")})})}}angular.module("Plania").controller("NonsReferenceModalController",["$scope","$modal","$modalInstance","Repository","params","TranslationService","$rootScope",controller])}(),function(){function controller($scope,$modalInstance,params,repository,$modal,translationService){$scope.selectedAttachments=[],$scope.entityType=params.entityType;var guidEntity=params.guid;$scope.canAddDocument=!0,$scope.canAddImage="WorkOrder"===$scope.entityType||"Request"===$scope.entityType,$scope.availableAttachments=_.map(params.availableAttachments,function(attachment){var copy=angular.copy(attachment);return copy.isAlreadySelected=_.contains(params.selectedAttachmentGuids,attachment.Guid),copy.translatedName=translationService.translate("web-"+copy.ParentEntityType,copy.ParentEntityType),copy}),$scope.selectAttachment=function(attachment){if(!attachment.isAlreadySelected)if(_.find($scope.selectedAttachments,{Guid:attachment.Guid})){for(var i=0;i<$scope.selectedAttachments.length;i++)if($scope.selectedAttachments[i].Guid===attachment.Guid)return void $scope.selectedAttachments.splice(i,1)}else $scope.selectedAttachments.push(attachment)},$scope.isSelected=function(attachment){return!!attachment.isAlreadySelected||_.find($scope.selectedAttachments,{Guid:attachment.Guid})};var onNewDocument=params.onNewDocument,onNewImage=params.onNewImage,resolveParams=function(){var params={};return params["guid"+$scope.entityType]=guidEntity,params},onNewAttachment=function(guids){var onNewAttachment=params.onNewAttachment;"function"==typeof onNewAttachment&&onNewAttachment().then(function(attachments){attachments.forEach(function(attachment){if(!_.find($scope.availableAttachments,{Guid:attachment.Guid})){var copy=angular.copy(attachment);copy.translatedName=translationService.translate("web-"+copy.ParentEntityType,copy.ParentEntityType),$scope.availableAttachments.push(copy),guids.includes(copy.Guid)&&$scope.selectAttachment(copy)}})})};$scope.addNewDocument=function(){$modal.open({templateUrl:"app/document/views/createDocumentModal.html",controller:"CreateDocumentXEntityController",size:"lg",resolve:{params:resolveParams}}).result.then(function(response){var guids=[];response&&response.savedFiles&&Array.isArray(response.savedFiles)&&response.savedFiles.forEach(function(obj){obj.guid&&guids.push(obj.guid)}),onNewAttachment(guids),onNewDocument&&"function"==typeof onNewDocument&&onNewDocument(guids)})},$scope.addNewImage=function(){$modal.open({templateUrl:"app/document/views/createImageModal.html",controller:"CreateDocumentXEntityController",size:"lg",resolve:{params:resolveParams}}).result.then(function(images){var guids=[];images&&Array.isArray(images)&&images.forEach(function(image){image.Guid&&guids.push(image.Guid)}),onNewAttachment(guids),onNewImage&&"function"==typeof onNewImage&&onNewImage(images)})},$scope.currentEntityTypeFirst=function(attachment){return attachment.ParentEntityType!==$scope.entityType},$scope.ok=function(){$modalInstance.close($scope.selectedAttachments)},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("SelectAttachmentModalController",["$scope","$modalInstance","params","Repository","$modal","TranslationService",controller])}(),function(){function controller($scope,$modalInstance,iconService){$scope.activeTab={objects:!0,symbols:!1,activities:!1},$scope.selectTab=function(action){for(var key in $scope.activeTab)$scope.activeTab.hasOwnProperty(key)&&($scope.activeTab[key]=!1);$scope.activeTab[action]=!0,$scope.availableIcons=iconService.GetTabContent(action)},$scope.allAvaliableIcons=iconService.GetAvailableIcons(),$scope.availableIcons=iconService.GetTabContent($scope.activeTab.objects?"objects":$scope.activeTab.symbols?"symbols":$scope.activeTab.activities?"activities":[]),$scope.iconMap=iconService.GetIconMap(),$scope.getIcon=iconService.getIcon,$scope.ok=function(selectedIcon){$modalInstance.close(selectedIcon)},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("SelectIconModalController",["$scope","$modalInstance","IconService",controller])}(),function(){function controller($scope,$modalInstance,translationService){$scope.userInfo;$scope.availableProperties=[{Name:translationService.translate("web-userinfo-realname","Fullt navn"),Property:"@CurrentUser.realName"},{Name:translationService.translate("web-userinfo-email","E-post"),Property:"@CurrentUser.email"},{Name:translationService.translate("web-userinfo-phone","Telefonnummer"),Property:"@CurrentUser.phone"}],$scope.ok=function(){$modalInstance.close(_.map(_.filter($scope.availableProperties,{isSelected:!0}),"Property"))},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("SelectUserInfoPropertyModal",["$scope","$modalInstance","TranslationService",controller])}(),function(){function controller($scope,$modalInstance,modalParams,repository,ngTableParams,translationService,listService){$scope.allRowsSelected=!1,$scope.modalParams=modalParams,$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.visibleColumns=_.filter($scope.modalParams.columns,function(c){return!c.Hidden}),modalParams.filter||(modalParams.filter={});var sorting=modalParams.sorting;!sorting&&modalParams.columns&&modalParams.columns[0]&&modalParams.columns[0].Property&&(sorting={},sorting[modalParams.columns[0].Property]="asc"),$scope.itemTable=new ngTableParams({page:1,count:10,sorting:sorting,filter:modalParams.filter},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){var filter=angular.copy(params.filter());_.remove(filter.PropertyFilter,function(prop){return prop.isDisabled});var columns=null;modalParams.columns&&(columns=_.map(modalParams.columns,"Property")),repository.GetPaginated(modalParams.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.selectedItems=[],$scope.save=function(){modalParams.useObjects?$modalInstance.close($scope.selectedItems):$modalInstance.close(_.map($scope.selectedItems,"Guid"))},$scope.addSelectedItem=function(object){if($scope.isItemSelected(object)){for(var i=0;i<$scope.selectedItems.length;i++)if($scope.selectedItems[i].Guid===object.Guid)return void $scope.selectedItems.splice(i,1)}else $scope.alreadySaved(object.Guid)||$scope.selectedItems.push(object)},$scope.isItemSelected=function(object){return _.find($scope.selectedItems,function(o){return o.Guid===object.Guid})},$scope.alreadySaved=function(guid){return _.includes(modalParams.alreadySavedGuids,guid)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("MultipleSelectModalController",["$scope","$modalInstance","modalParams","Repository","ngTableParams","TranslationService","ListService",controller])}(),function(){function provider(){this.$get=["$window","$rootScope",function($window,$rootScope){function getHashKey(fName,args){function replacerFactory(){var cache=[];return function(key,val){if(isObject(val)&&!_.isNull(val)){if(~cache.indexOf(val))return"[Circular]";cache.push(val)}return $window==val?"$WINDOW":$window.document==val?"$DOCUMENT":isScope(val)?"$SCOPE":val}}return[fName,JSON.stringify(args,replacerFactory())].join("#").replace(/"/g,"")}function removeCache(event){var id=event.targetScope.$id;_.forEach($$listeners[id],function(key){delete $$cache[key]}),delete $$listeners[id]}function cleanStateless(){$$timeout(function(){$rootScope.$$phase||($$cache={})},2e3)}function addListener(scope,hashKey){var id=scope.$id;return isUndefined($$listeners[id])&&(scope.$on("$destroy",removeCache),$$listeners[id]=[]),$$listeners[id].push(hashKey)}function $$isMemoized(filterName,args){var hashKey=getHashKey(filterName,args);return $$cache[hashKey]}function $$memoize(filterName,args,scope,result){var hashKey=getHashKey(filterName,args);return $$cache[hashKey]=result,isScope(scope)?addListener(scope,hashKey):cleanStateless(),result}var isObject=function(value){return null!==value&&"object"==typeof value},isUndefined=function(value){return void 0===value},isScope=function(obj){return obj&&obj.$evalAsync&&obj.$watch},$$cache={},$$listeners={},$$timeout=$window.setTimeout;return{isMemoized:$$isMemoized,memoize:$$memoize}}]}angular.module("Plania").provider("filterWatcher",[provider])}(),function(){function controller($scope,$modalInstance){$scope.loginUrl=document.location.protocol+"//"+document.location.host,$scope.ok=function(){$modalInstance.close("ok")}}angular.module("Plania").controller("QrCodeModalController",["$scope","$modalInstance",controller])}(),function(){function controller($scope,$modal){this.openQRCodeModal=function(){$modal.open({controller:"QrCodeModalController",templateUrl:"app/common/views/qrCodeModal.html"})}}angular.module("Plania").controller("QrCodeOpenModalController",["$scope","$modal",controller])}(),function(){angular.module("Plania").directive("reactBimViewer",["$rootScope",function($rootScope){return{restrict:"E",scope:{},link:function(scope,element,attrs){scope.props={reload:!0},scope.$on($rootScope.events.newSelection,function(){scope.props.reload=!scope.props.reload})},template:''}}])}(),function(){angular.module("Plania").directive("reactBuildingTable",["$rootScope",function($rootScope){return{restrict:"E",scope:{},link:function(scope,element,attrs){scope.props={reload:!0},scope.$on($rootScope.events.newSelection,function(){scope.props.reload=!scope.props.reload})},template:''}}])}(),function(){angular.module("Plania").controller("ReactCommonListController",["$scope","$state",function($scope,$state){$scope.apiData=$state.params.entityData}]),angular.module("Plania").directive("reactPlaniaMainTable",["$rootScope",function($rootScope){return{restrict:"E",scope:{entity:"@",apiData:"="},link:function(scope,element,attrs){scope.props={reload:!0,entity:scope.entity,apiData:scope.apiData},scope.$on($rootScope.events.newSelection,function(){scope.props.reload=!scope.props.reload})},template:'
    '}}])}(),function(){angular.module("Plania").directive("reactComponent",["ReactService",function(reactService){return{restrict:"E",scope:{componentName:"@",props:"=props"},link:function(scope){scope.id=reactService.generateId();var component=window.AngularMigration.Components[scope.componentName];if(!component)throw Error("COMPONENT NOT FOUND");var container,root;scope.$watch(function(scope){return{props:scope.props}},function(settings,oldSettings){var properties={};settings.props&&"object"==typeof settings.props&&Object.keys(settings.props).forEach(function(key){properties[key]=settings.props[key]}),container||(container=document.getElementById(scope.id)),root||(root=window.AngularMigration.createRoot(container)),root.render(window.AngularMigration.React.createElement(component,properties))},!0),scope.$on("$destroy",function(){reactService.removeId(scope.id),root&&root.unmount()})},template:'
    '}}])}(),function(){angular.module("Plania").directive("reactWorkOrderTable",["$rootScope",function($rootScope){return{restrict:"E",scope:{},link:function(scope,element,attrs){scope.props={reload:!0},$rootScope.$on($rootScope.events.newSelection,function(){scope.props.reload=!scope.props.reload})},template:''}}])}(),function(){angular.module("Plania").service("authInterceptorService",["$q","$injector","config",function($q,$injector,apiConfig){var $http,authInterceptorServiceFactory={},request=function(config){if(config.skipAuth)return config;if(-1===config.url.indexOf(apiConfig.baseUrl))return config;document.execCommand("ClearAuthenticationCache","false");var authService=$injector.get("authService");return config.headers=config.headers||{},config.headers.Authorization=authService.getPlaniaToken().access,config},retryHttpRequest=function(config,deferred){$http=$http||$injector.get("$http"),$http(config).then(function(response){deferred.resolve(response)},function(response){deferred.reject(response)})},responseError=function(rejection){if(rejection.config.skipAuth)return $q.reject(rejection);var deferred=$q.defer(),authService=$injector.get("authService"),accessToken=authService.getPlaniaToken().access;return rejection.config.headers.Authorization!==accessToken?(rejection.config.headers.Authorization=accessToken,retryHttpRequest(rejection.config,deferred)):deferred.reject(rejection),deferred.promise};return authInterceptorServiceFactory.request=request,authInterceptorServiceFactory.responseError=responseError,authInterceptorServiceFactory}])}(),function(){function service($http,$rootScope,config,commonService,moduleService,$localStorage,signalR,$q,$window){function resetUserData(){userData.isAuthenticated=!1,userData.username="",userData.accessToDesktop=!1,userData.canSeeWebMainMenu=!1,userData.canExportToExcel=!1,userData.isSystemAdministrator=!1,userData.isProjectAdministrator=!1,userData.canRunSystemFunction=!1,userData.canOverridePermissions=!1,userData.enableWebNavigation=!1,userData.isExternalUser=!1,userData.needToAcceptTermsOfUse=!1,userData.GuidWebMenu="",userData.guidImage="",userData.MenuContext="",userData.MenuParameters="",userData.phone="",userData.cellPhone="",userData.email="",userData.realName="",userData.guidUser="",userData.guidPerson="",userData.guidCustomer="",userData.personEmployeeNr="",userData.personFirstName="",userData.personLastName="",userData.personResourceGroup="",userData.guidPersonResourceGroup="",userData.defaultSelection="",userData.defaultSelectionDescription="",userData.defaultDataOwner="",userData.userResourceGroup="",userData.guidResourceGroup="",userData.userAccount="",userData.guidAccount="",userData.userDepartment="",userData.guidDepartment="",userData.userSupplier="",userData.guidSupplier="",userData.guidPersonDepartment="",userData.language="",userData.useTwoFactor="",userData.guidPersonOrganization="",userData.guidPersonOrganizationUnit="",userData.guidPersonOrganizationSection="",$rootScope.events&&$rootScope.$broadcast($rootScope.events.userInfoChangedEvent)}function stopSignalR(){signalR.setQs({}),signalR.stop()}var repository={},userData={};resetUserData();var authenticationSuccess=function(data){delete $localStorage.userData,delete $localStorage.planiaToken,$localStorage.planiaToken={access:"Bearer "+data.access_token,refresh:data.refresh_token,expiration:new Date(data[".expires"]),issued:new Date(data[".issued"])},userData.isAuthenticated=!0,userData.username=data.userName,userData.accessToDesktop="1"===data.AccessToDesktop,userData.isSystemAdministrator="1"===data.SystemAdministrator,userData.isUserAdministrator="1"===data.UserAdministrator,userData.isProjectAdministrator="1"===data.ProjectAdministrator,userData.canRunSystemFunction="1"===data.CanRunSystemFunction,userData.canChangeRequestStatus="1"===data.CanChangeRequestStatus,userData.canChangeDataAcquisitionStatus="1"===data.CanChangeDataAcquisitionStatus,userData.canSeeWebMainMenu="1"===data.CanSeeWebMainMenu,userData.canExportToExcel="1"===data.CanExportToExcel,userData.enableWebNavigation="1"===data.EnableWebNavigation,userData.canOverridePermissions="1"===data.CanOverridePermissions,userData.isExternalUser="1"===data.IsExternalUser,userData.useTwoFactor="1"===data.UseTwoFactor,userData.needToAcceptTermsOfUse="1"===data.needToAcceptTermsOfUse,userData.GuidWebMenu=data.GuidWebMenu,userData.userSupplier=data.userSupplier,userData.guidSupplier=data.guidSupplier,userData.guidPersonDepartment=data.guidPersonDepartment,userData.guidImage=data.guidImage,userData.MenuContext=data.MenuContext,userData.MenuParameters=data.MenuParameters,userData.email=data.email,userData.phone=data.phone,userData.cellPhone=data.cellPhone,userData.realName=data.realName,userData.guidUser=data.UserID,userData.guidPerson=data.guidPerson,userData.guidCustomer=data.guidCustomer,userData.personEmployeeNr=data.personEmployeeNr,userData.personFirstName=data.personFirstName,userData.personLastName=data.personLastName,userData.personResourceGroup=data.personResourceGroup,userData.guidPersonResourceGroup=data.guidPersonResourceGroup,userData.defaultSelection=data.selectedSelectionGuid,userData.defaultSelectionDescription=data.selectedSelectionDescription,userData.defaultDataOwner=data.selectedDataOwnerGuid,userData.userResourceGroup=data.userResourceGroup,userData.guidResourceGroup=data.guidResourceGroup,userData.userAccount=data.userAccount,userData.guidAccount=data.guidAccount,userData.userDepartment=data.userDepartment,userData.guidDepartment=data.guidDepartment,userData.guidPersonOrganization=data.guidPersonOrganization,userData.guidPersonOrganizationUnit=data.guidPersonOrganizationUnit,userData.guidPersonOrganizationSection=data.guidPersonOrganizationSection,userData.guidUserGroup=data.guidUserGroup,userData.language=data.language,data.additionalProperties&&(userData.additionalProperties=JSON.parse(data.additionalProperties)),$localStorage.userData=userData,$rootScope.events&&$rootScope.$broadcast($rootScope.events.userInfoChangedEvent),signalR.setQs({fingerprint:config.fingerprint,guidUser:userData.guidUser}),signalR.start()};repository.getPlaniaToken=function(){var token=angular.fromJson($localStorage.planiaToken);return token?(token.expiration=new Date(token.expiration),token.issued=new Date(token.issued),token):{access:"None",refresh:"none",expiration:new Date}},repository.getUserData=function(){if(!userData.isAuthenticated){var storageUserData=angular.fromJson($localStorage.userData);storageUserData&&(userData=storageUserData,repository.refreshAuthentication())}return userData},repository.hasAcceptedTermsOfUse=function(){userData.needToAcceptTermsOfUse=!1,$localStorage.userData=userData, $rootScope.events&&$rootScope.$broadcast($rootScope.events.userInfoChangedEvent)},repository.deleteLocalData=function(){delete $localStorage.userData,delete $localStorage.planiaToken,delete $localStorage.userAccess,delete $localStorage.filterData,delete $localStorage.webMenus,commonService.clearFilterData(),delete $http.defaults.headers.common.Authorization,resetUserData()},repository.removeAuthentication=function(){var deferred=$q.defer(),postData={method:"POST",url:config.baseUrl+"Logout?clientId="+config.clientId};return stopSignalR(),repository.refreshAuthentication().then(function(){$http(postData).then(function(result){repository.deleteLocalData(),result.headers("location")&&($window.location.href=result.headers("location")),deferred.resolve()},function(error){repository.deleteLocalData(),deferred.resolve()})}),deferred.promise};var refreshingDefer,refreshingToken=!1,refreshTries=0,refreshAuthentication=function(token,callback){var deferred=$q.defer(),postData={method:"POST",url:encodeURI(config.baseUrl+"Token"),headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},data:"grant_type=refresh_token&refresh_token="+token.refresh+"&client_id="+config.clientId+"&client_secret="+config.clientSecret+"&fingerprint="+config.fingerprint};return $http(postData).success(function(data){authenticationSuccess(data),callback&&"function"==typeof callback&&callback(data),refreshingToken=!1,refreshTries=0,deferred.resolve(data)}).catch(function(data){if(refreshTries<=3&&data.data&&"invalid_grant"!==data.data.error)return refreshTries++,refreshingToken=!1,void repository.refreshAuthentication();data.userData=userData,data.accessToken=token,delete $localStorage.userData,delete $localStorage.planiaToken,delete $localStorage.userAccess,delete $localStorage.filterData,delete $http.defaults.headers.common.Authorization,resetUserData(),stopSignalR(),deferred.reject("Invalid"),window.location.reload()}),deferred.promise};repository.forceRefreshAuthentication=function(){var token=repository.getPlaniaToken();refreshAuthentication(token)},repository.refreshAuthentication=function(){var deferred=$q.defer();if(refreshingToken)return refreshingDefer.promise;refreshingDefer=deferred;var token=repository.getPlaniaToken(),refreshTimeInterval=(token.expiration-token.issued)/2;return token.expiration-new Date",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null}]}),service.getAutoComplete("article/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.buildings=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id","Description","Estate.Id","Estate.Description","Address","CostCenter.Id","CostCenter.Description"];return searchParam||(searchParam={}),searchParam.PropertyFilter||(searchParam.PropertyFilter=[]),searchParam.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:"0"}),service.getAutoComplete("building/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.deliveryTerm=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("deliveryTerm/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id)})},service.contactPerson=function(searchParam,page,pageSize,sorting){var sort={FirstName:"asc"},columns=["FirstName","LastName","Email","Cellphone"];return sorting&&0!==sorting.length&&(sort.FirstName=sorting.id),service.getAutoComplete("contactPerson/",searchParam,page,pageSize,sort,function(r){var name="";return r.FirstName&&(name=r.FirstName),r.LastName&&(name+=r.FirstName?" "+r.LastName:r.LastName),service.getModel(r.Guid,name,null,r)},columns)},service.equipments=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id","Description","ConditionContextDescription","IsMaintainable","CanHaveDowntime","Area.Id","Area.Description","Building.Id","Building.Description","Building.Estate.Id","Building.Estate.Description","Building.Estate.Guid"];return service.getAutoComplete("equipment/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.equipmentOperatingHourType=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id"];return service.getAutoComplete("equipmentOperatingHourType/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,null,r)},columns)},service.equipmentCategories=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("EquipmentCategory/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)})},service.persons=function(searchParam,page,pageSize,sorting){var sort={FirstName:"asc"},columns=["FirstName","LastName","ResourceGroup.Id","ResourceGroup.Description","ResourceGroup.CostPrHour","ResourceGroup.Guid","Email","TelephoneWork","CellPhone","Department.Guid","Department.Id","Department.Description"];return sorting&&0!==sorting.length&&(sort.FirstName=sorting.id),service.getAutoComplete("person/",searchParam,page,pageSize,sort,function(r){var name="";return r.FirstName&&(name=r.FirstName),r.LastName&&(name+=r.FirstName?" "+r.LastName:r.LastName),service.getModel(r.Guid,name,null,r)},columns)},service.resourceResponsibles=function(searchParam,page,pageSize,sorting){var sort={FirstName:"asc"},columns=["FirstName","LastName"];return sorting&&0!==sorting.length&&(sort.FirstName=sorting.id),service.getAutoComplete("person/",searchParam,page,pageSize,sort,function(r){var name="";return r.FirstName&&(name=r.FirstName),r.LastName&&(name+=r.FirstName?" "+r.LastName:r.LastName),service.getModel(r.Guid,name,null,r)},columns)},service.suppliers=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id","Description","Telephone","Email"];return service.getAutoComplete("supplier/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.accounting=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("accountingDimension/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.resourceGroups=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id","Description","CostPrHour"];return service.getAutoComplete("ResourceGroup/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.hourType=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id","Description","Price","PriceType"];return service.getAutoComplete("HourType/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.cause=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("Cause/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id)})},service.checklist=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("Checklist/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.cleaningQuality=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("CleaningQuality/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.department=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("Department/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description)})},service.document=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("document/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.documentCategory=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("DocumentCategory/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)})},service.documentType=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("DocumentType/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id)})},service.priority=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};sorting&&0!==sorting.length&&(sort.description=sorting.id);var columns=["Description","HasDeadline","DeadlinePeriodNumber","DeadlinePeriodUnit"];return service.getAutoComplete("Priority/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)},columns)},service.account=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("Account/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.buildingCategory=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("BuildingCategory/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)},[])},service.paymentTerm=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("PaymentTerm/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id)})},service.invoicingTerm=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("InvoicingTerm/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id)})},service.contractType=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id"];return service.getAutoComplete("ContractType/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id)},columns)},service.contractCategory=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};sorting&&0!==sorting.length&&(sort.description=sorting.id);var columns=["Description"];return service.getAutoComplete("ContractCategory/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)},columns)},service.purchaseOrderForm=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("PurchaseOrderForm/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,r.GuidReport?"Tilgjengelig i web":"Ikke tilgjengelig i web",r)})},service.paymentOrderForm=function(searchParam,page,pageSize,sorting){var sort={id:"asc"};return sorting&&0!==sorting.length&&(sort.id=sorting.id),service.getAutoComplete("PaymentOrderForm/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Id,null,r)})},service.costCenter=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("CostCenter/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description)})},service.rentalGroup=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("RentalGroup/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id)})},service.postal=function(searchParam,page,pageSize,sorting){sorting&&sorting.id&&(sorting.zipCode=sorting.id,delete sorting.id);var columns=["ZipCode","PostalArea","County","MunicipalityName","CountryCode"];return service.getAutoComplete("PostalCode/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.ZipCode,r.PostalArea+" ("+r.MunicipalityName+")",r)},columns)},service.supplierLineOfBusiness=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("SupplierLineOfBusiness/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id)})},service.areaCategory=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("AreaCategory/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)})},service.areaType=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("areaType/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.activityCategory=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("ActivityCategory/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)})},service.organization=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={description:"asc"}),service.getAutoComplete("Organization/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.organizationUnit=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={description:"asc"}),service.getAutoComplete("OrganizationUnit/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.organizationSection=function(searchParam,page,pageSize,sorting){var columns=["Id","Description","GuidOrganizationUnit","OrganizationUnit.GuidOrganization"];return sorting&&0!==sorting.length||(sorting={description:"asc"}),service.getAutoComplete("OrganizationSection/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.PersonRole=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("PersonRole/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id)})},service.deviationType=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("deviationType/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.EstateCategory=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return searchParam.PropertyFilter||(searchParam.PropertyFilter=[]),0===_.filter(searchParam.PropertyFilter,{Property:"IsAbstract"}).length&&searchParam.PropertyFilter.push({Property:"IsAbstract",Operator:"=",Value:0}),sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("estateCategory/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)})},service.dataOwner=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("dataOwner/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.entityPermissionProfile=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("entitypermissionprofile/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.mobileMenuProfile=function(searchParam,page,pageSize,sorting){var sort={id:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("mobileMenuProfile/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.buildingSelection=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("buildingSelection/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)})},service.systemAdministrator=function(searchParam,page,pageSize,sorting){searchParam=normalizeSearchParams(searchParam),searchParam.FilterModel.Rules.push({Property:"IsSystemAdministrator",Operator:"=",Value:!0}),searchParam.dropdown&&(searchParam.FilterModel.Rules.push({Condition:"or",Rules:[{Property:"Username",Operator:"contains",Value:searchParam.dropdown},{Property:"RealName",Operator:"contains",Value:searchParam.dropdown}]}),searchParam.dropdown="");var sort={RealName:"asc"};sorting&&0!==sorting.length&&(sort.RealName=sorting.id);var columns=["RealName","Username","PhoneNumber","Email","CellPhone"];return service.getAutoComplete("user/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Username,r.RealName,r)},columns)},service.userGroup=function(searchParam,page,pageSize,sorting){var sort={RealName:"asc"},columns=["RealName","IsStartPageForced","CanPrintPurchaseOrder","Procuration","Person.FirstName","Person.LastName","ResourceGroup.Id","Department.Id","Department.Description","Account.Id","Account.Description","Supplier.Description","DefaultBuildingSelection.Description","Customer.Id","Customer.Description","AccessType","IsUserAdministrator","IsSystemAdministrator","CanRunNewPeriod","CanRunNewEnergyPeriod","CanChangeDataOwner","CanOverridePermissions","CanRunSystemFunction","IsBookingAdministrator","IsExternalUser","CanChangeRequestStatus","CanSeeWebMainMenu","CanExportToExcel","SqlCustomerFilter","GuidMobileMenuProfile","MobileMenuProfile.Id","MobileMenuProfile.Description"];return sorting&&0!==sorting.length&&(sort.RealName=sorting.id),service.getAutoComplete("user/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.RealName,null,r)},columns)},service.customer=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("Customer/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.customerCategory=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("customerCategory/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.customerLineOfBusiness=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("customerLineOfBusiness/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.customerGroup=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("customerGroup/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.component=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id","Description","Unit"];return service.getAutoComplete("component/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.componentCategory=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id), service.getAutoComplete("componentCategory/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)})},service.constructionType=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("ConstructionType/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id)})},service.cleaningTask=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("CleaningTask/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,null,r)})},service.project=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"desc"}),service.getAutoComplete("project/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.projectCategory=function(searchParam,page,pageSize,sorting){var sort={description:"asc"};return sorting&&0!==sorting.length&&(sort.description=sorting.id),service.getAutoComplete("ProjectCategory/",searchParam,page,pageSize,sort,function(r){return service.getModel(r.Guid,r.Description,null,r)},[])},service.projectType=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("projectType/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,null,r)})},service.drawing=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("drawing/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.activityGroup=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("activityGroup/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,null,r)})},service.region=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("region/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,null,r)})},service.referenceData=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={IndexPosition:"asc"});var columns=["Id","Description","IndexPosition","ExplanatoryText01","ExplanatoryText02","ReferenceType.Id","ReferenceType.Description","ReferenceType.ExplanatoryText"];return service.getAutoComplete("referenceData/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.referenceType=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("referenceType/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.entityAttribute=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),service.getAutoComplete("entityAttribute/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,null,r)})},service.service=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"asc"}),searchParam=normalizeSearchParams(searchParam),searchParam.FilterModel.Rules.push({Condition:"or",Rules:[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null}]}),service.getAutoComplete("service/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.sparePart=function(searchParam,page,pageSize,sorting){sorting={"ComponentXSupplier.PartNumber":"desc"};var columns=["ComponentXSupplier.PartNumber","Component.Id","Component.Description"];return service.getAutoComplete("sparePart/",searchParam,page,pageSize,sorting,function(r){var component=r.Component.Id+" - "+r.Component.Description;return service.getModel(r.Guid,r.ComponentXSupplier?r.ComponentXSupplier.PartNumber:null,component,r)},columns)},service.controlListLogItem=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id"];return service.getAutoComplete("controlListLogItem/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,null,r)},columns)},service.purchaseOrder=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id","Description","Building.Guid","Building.Id","Building.Description","Supplier.Guid","Supplier.Id","Supplier.Description","Equipment.Guid","Equipment.Id","Equipment.Description","Area.Guid","Area.Id","Area.Description"];return searchParam.IncludeWorkOrder=!0,service.getAutoComplete("purchaseOrder/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.report=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={Name:"asc"});var columns=["Id","Name","Description"];return service.getAutoComplete("report/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Name,r)},columns)},service.purchaseOrderItem=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["WorkOrder.Guid","WorkOrder.Id","WorkOrder.Description","WorkOrder.GuidArea","Id","Description","UnitPrice","OrderedQuantity","BudgetDate","Account.Guid","Account.Id","Account.Description","Accounting0.Guid","Accounting0.Id","Accounting0.Description","Accounting1.Guid","Accounting1.Id","Accounting1.Description","Accounting2.Guid","Accounting2.Id","Accounting2.Description","Accounting3.Guid","Accounting3.Id","Accounting3.Description","Accounting4.Guid","Accounting4.Id","Accounting4.Description","Building.Guid","Building.Id","Building.Description","Supplier.Guid","Supplier.Id","Supplier.Description","Equipment.Guid","Equipment.Id","Equipment.Description","PurchaseOrder.Guid","PurchaseOrder.Id","PurchaseOrder.Description","CostCenter.Guid","CostCenter.Id","CostCenter.Description","Department.Guid","Department.Id","Department.Description"];return service.getAutoComplete("purchaseOrderItem/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.consumable=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"asc"});var columns=["Id","Unit","UnitPrice","Accounting0.Guid","Accounting0.Id","Accounting0.Description","Accounting1.Guid","Accounting1.Id","Accounting1.Description","Accounting2.Guid","Accounting2.Id","Accounting2.Description","Accounting3.Guid","Accounting3.Id","Accounting3.Description","Accounting4.Guid","Accounting4.Id","Accounting4.Description"];return service.getAutoComplete("consumable/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.periodicTask=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"desc"}),service.getAutoComplete("periodicTask/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.workOrderTemplate=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={ID:"desc"}),searchParam||(searchParam={}),searchParam.PropertyFilter||(searchParam.PropertyFilter=[]),searchParam.PropertyFilter.push({Property:"TemplateType",Operator:"=",Value:2}),service.getAutoComplete("periodicTask/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)})},service.workOrder=function(searchParam,page,pageSize,sorting){sorting&&0!==sorting.length||(sorting={ID:"desc"});var columns=["Id","Description","Building.Guid","Building.Id","Building.Description","Building.CostCenter.Guid","Building.CostCenter.Id","Building.CostCenter.Description","Supplier.Guid","Supplier.Id","Supplier.Description","Equipment.Guid","Equipment.Id","Equipment.Description","Equipment.CostCenter.Guid","Equipment.CostCenter.Id","Equipment.CostCenter.Description","Area.Guid","Area.Id","Area.Description","Area.CostCenter.Guid","Area.CostCenter.Id","Area.CostCenter.Description"];return searchParam.ActivityStatus="Active",service.getAutoComplete("workOrder/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Id,r.Description,r)},columns)},service.webmenu=function(searchParam,page,pageSize,sorting){return sorting&&0!==sorting.length||(sorting={Name:"asc"}),columns=["Id","Name","Description","Type","Context","Reference","IsBuildingDependent"],service.getAutoComplete("webmenu/",searchParam,page,pageSize,sorting,function(r){return service.getModel(r.Guid,r.Name,r.Description,r)},columns)},service}angular.module("Plania").factory("AutoCompleteService",["genericRepository","$q","CommonService",autoCompleteService])}(),function(){function colorService(){var service={},getColorFromVariables=function(key){return getComputedStyle(document.body).getPropertyValue(key)},getPrimaryText=function(){return getColorFromVariables("--pl-text-primary")},getWhiteText=function(){return getColorFromVariables("--pl-text-white")};return service.getContrastText=function(bgColor){var lightColor=getWhiteText(),darkColor=getPrimaryText();try{var color="#"===bgColor.charAt(0)?bgColor.substring(1,7):bgColor,r=parseInt(color.substring(0,2),16),g=parseInt(color.substring(2,4),16),b=parseInt(color.substring(4,6),16),uicolors=[r/255,g/255,b/255],c=uicolors.map(function(col){return col<=.03928?col/12.92:Math.pow((col+.055)/1.055,2.4)});return.2126*c[0]+.7152*c[1]+.0722*c[2]>.179?darkColor:lightColor}catch(error){return darkColor}},service.convertToRainbow=function(color){if(!color||"string"!=typeof color)return"";if(color.startsWith("#"))switch(color.toLowerCase()){case"#00bcd4".toLowerCase():case"#2196F3".toLowerCase():return getColorFromVariables("--pl-palette-rainbow-blue");case"#f44336".toLowerCase():return getColorFromVariables("--pl-palette-rainbow-red");case"#000000".toLowerCase():return getColorFromVariables("--pl-palette-rainbow-black");case"#9E9E9E".toLowerCase():case"#607D8B".toLowerCase():return getColorFromVariables("--pl-palette-rainbow-gray");case"#673AB7".toLowerCase():return getColorFromVariables("--pl-palette-rainbow-purple");case"#ff9800".toLowerCase():return getColorFromVariables("--pl-palette-rainbow-orange");case"#4caf50".toLowerCase():return getColorFromVariables("--pl-palette-rainbow-green");case"#009688".toLowerCase():return getColorFromVariables("--pl-palette-rainbow-cyan");default:return color}else switch(color.toLowerCase()){case"bluegray":return"gray";case"lightblue":return"blue";case"teal":return"cyan";case"lightorange":return"orange";case"deeppurple":return"purple";default:return color}},service.getRainbowPalette=function(){var names=["blue","purple","cyan","green","orange","yellow","gray","red","black"],palette=[];return names.forEach(function(name){palette.push({name:name,hexColor:getColorFromVariables("--pl-palette-rainbow-"+name).toLowerCase()})}),palette},service}angular.module("Plania").factory("ColorService",[colorService])}(),function(){function columnFormatService($modal){var service={};return service.chooseColumn=function(model,modelProperty,entityName){var modalInstance=$modal.open({templateUrl:"app/common/views/addNewListColumnModal.html",controller:"AddNewListColumnController",resolve:{params:function(){return{prefix:entityName}}}});model[modelProperty]||(model[modelProperty]=""),modalInstance.result.then(function(selectedColumns){selectedColumns.forEach(function(col){var splitted=col.Property.split("."),propertyString=(entityName.charAt(0).toLowerCase()+entityName.slice(1)).replace(/([A-Z])/g,function(value){return"_"+value}).toUpperCase();splitted.forEach(function(colPart,index){colPart=colPart.charAt(0).toLowerCase()+colPart.slice(1);var snakeCaseCol=colPart.replace(/([A-Z])/g,function(value){return"_"+value}).toUpperCase();if(index===splitted.length-1)return void(propertyString+="."+snakeCaseCol);propertyString+="#GUID_"+snakeCaseCol+"\\"+snakeCaseCol}),model[modelProperty]+="["+propertyString+"]"})})},service}angular.module("Plania").factory("ColumnFormatService",["$modal",columnFormatService])}(),function(){function commonService($localStorage){var service={};service.filterData={isLoaded:!1},service.clearFilterData=function(){delete service.filterData,service.filterData={isLoaded:!1},service.setEmptyEstate(),service.setEmptyBuilding(),service.setEmptyDataOwner(),service.setEmptySelection()},service.setEmptyEstate=function(){var name="Velg eiendom",storageLanguageData=angular.fromJson($localStorage.languageData);if(storageLanguageData){var translatedName=storageLanguageData[$localStorage.locale+"web-estate-choose"];translatedName&&(name=translatedName)}service.filterData.selectedEstate={Name:name,Guid:""}},service.setEmptyEstate(),service.setEstate=function(estate){estate&&(service.filterData.selectedEstate.Guid=estate.Guid,estate.Name?service.filterData.selectedEstate.Name=estate.Name:service.filterData.selectedEstate.Name=estate.Caption,$localStorage.filterData=service.filterData)},service.setEmptyBuilding=function(){var name="Velg bygg",storageLanguageData=angular.fromJson($localStorage.languageData);if(storageLanguageData){var translatedName=storageLanguageData[$localStorage.locale+"web-building-choose"];translatedName&&(name=translatedName)}service.filterData.selectedBuilding={Name:name,Guid:""}},service.setEmptyBuilding(),service.setBuilding=function(building){service.filterData.selectedBuilding.Guid=building.Guid,building.Name?service.filterData.selectedBuilding.Name=building.Name:service.filterData.selectedBuilding.Name=building.Caption,building.Estate&&(service.filterData.selectedBuilding.Estate=building.Estate),$localStorage.filterData=service.filterData},service.setEmptyDataOwner=function(){var storageLanguageData=angular.fromJson($localStorage.languageData),description="Klient";storageLanguageData&&(description=storageLanguageData[$localStorage.locale+"web-dataowner"]),service.filterData.selectedDataOwner={Description:description,Guid:"",GuidDefaultDocumentType:"",DefaultDocumentTypeId:""}},service.setEmptyDataOwner(),service.setDataOwner=function(owner){service.filterData.selectedDataOwner.Guid=owner.Guid,service.filterData.selectedDataOwner.Description=owner.Description,service.filterData.selectedDataOwner.Dimension1=owner.Dimension1,service.filterData.selectedDataOwner.GuidImageLogo=owner.GuidImageLogo,service.filterData.selectedDataOwner.CountryCode=owner.CountryCode,owner.GuidDefaultDocumentType&&owner.DefaultDocumentType?(service.filterData.selectedDataOwner.GuidDefaultDocumentType=owner.GuidDefaultDocumentType,service.filterData.selectedDataOwner.DefaultDocumentTypeId=owner.DefaultDocumentType.Id):(service.filterData.selectedDataOwner.GuidDefaultDocumentType="",service.filterData.selectedDataOwner.DefaultDocumentTypeId=""),owner.GuidWoXEqDocumentCategory&&(owner.DocumentCategory1||owner.WoXEqDocumentCategory)?(service.filterData.selectedDataOwner.GuidWoXEqDocumentCategory=owner.GuidWoXEqDocumentCategory,owner.DocumentCategory1&&owner.DocumentCategory1.Description?service.filterData.selectedDataOwner.WoXEqDocumentCategory=owner.DocumentCategory1.Description:owner.WoXEqDocumentCategory&&owner.WoXEqDocumentCategory.Description&&(service.filterData.selectedDataOwner.WoXEqDocumentCategory=owner.WoXEqDocumentCategory.Description)):(service.filterData.selectedDataOwner.GuidWoXEqDocumentCategory="",service.filterData.selectedDataOwner.WoXEqDocumentCategory=""),$localStorage.filterData=service.filterData},service.setEmptySelection=function(){var storageLanguageData=angular.fromJson($localStorage.languageData),description="Velg utvalg";storageLanguageData&&(description=storageLanguageData[$localStorage.locale+"web-buildingselection-choose"]),service.filterData.selectedSelection={Description:description,Guid:""}},service.setEmptySelection(),service.setSelectedSelection=function(selection){service.filterData.selectedSelection.Guid=selection.Guid,selection.Description&&(service.filterData.selectedSelection.Description=selection.Description),$localStorage.filterData=service.filterData},service.getFilterData=function(){if(!service.filterData.isLoaded){var storageFilterData=angular.fromJson($localStorage.filterData);storageFilterData&&(service.setBuilding(storageFilterData.selectedBuilding),service.setDataOwner(storageFilterData.selectedDataOwner),service.setSelectedSelection(storageFilterData.selectedSelection),service.setEstate(storageFilterData.selectedEstate)),service.filterData.isLoaded=!0}return service.filterData},service.disableWebMenuNavigation=function(){return 0===service.getFilterData().selectedBuilding.Guid.length};var lastRegister={};return service.setLastRegisterGuid=function(object,guid){lastRegister[object]=guid},service.getLastRegisterGuid=function(object){var guid=lastRegister[object];return lastRegister={},guid},service.prefix={internalWeb:"internalWeb",Undefined:"undefined",Null:"Null",Account:"Account",AccountingDimension:"AccountingDimension",AccountingXAccounting:"AccountingXAccounting",AccountXAccounting:"AccountXAccounting",ActivityCategory:"ActivityCategory",ActivityConstraint:"ActivityConstraint",ActivityGroup:"ActivityGroup",Alarm:"Alarm",AlarmLog:"AlarmLog",ApiClient:"ApiCLient",ApiRequestLog:"ApiRequestLog",Area:"Area",AreaAvailability:"AreaAvailability",AreaCategory:"AreaCategory",AreaCategoryXAreaType:"AreaCategoryXAreaType",AreaPrice:"AreaPrice",AreaType:"AreaType",AreaXCleaningTask:"AreaXCleaningTask",AreaXEntity:"AreaXEntity",Article:"Article",Barcode:"Barcode",BcfProject:"BcfProject",BookingCategory:"BookingCategory",Budget:"Budget",Building:"Building",BuildingCategory:"BuildingCategory",BuildingMeanTemperature:"BuildingMeanTemperature",BuildingSelection:"BuildingSelection",BuildingTemperaturePower:"BuildingTemperaturePower",BuildingXAreaCategory:"BuildingXAreaCategory",BuildingXBuildingSelection:"BuildingXBuildingSelection",BuildingXContract:"BuildingXContract",BuildingXPerson:"BuildingXPerson",BuildingXSupplier:"BuildingXSupplier",Cause:"Cause",ChangeSet:"ChangeSet",ControlList:"ControlList",ControlListItemAnswer:"ControlListItemAnswer",ControlListXEntity:"ControlListXEntity",Cleaning:"Cleaning",CleaningCode:"CleaningCode",CleaningInterval:"CleaningInterval",CleaningMethod:"CleaningMethod",CleaningQuality:"CleaningQuality",CleaningQualityControl:"CleaningQualityControl",CleaningTask:"CleaningTask",CleaningType:"CleaningType",CleaningXArea:"CleaningXArea",CleaningXCleaningMethod:"CleaningXCleaningMethod",Component:"Component",ComponentCategory:"ComponentCategory",ComponentXArea:"ComponentXArea",ComponentXEquipment:"ComponentXEquipment",ComponentXSupplier:"ComponentXSupplier",Condition:"Condition",ConditionType:"ConditionType",Configuration:"Configuration",Consequence:"Consequence",ConsequenceType:"ConsequenceType",ConstructionType:"ConstructionType",Consumable:"Consumable",ContactPerson:"ContactPerson",Contract:"Contract",ContractAdjustment:"ContractAdjustment",ContractAdjustmentConditions:"ContractAdjustmentConditions",ContractCategory:"ContractCategory",ContractEntityPriceXService:"ContractEntityPriceXService",ContractItem:"ContractItem",ContractItemXService:"ContractItemXService",ContractLease:"ContractLease",ContractLeaseItem:"ContractLeaseItem",ContractType:"ContractType",ContractWarranty:"ContractWarranty",Cost:"Cost",CostCenter:"CostCenter",Customer:"Customer",CustomerCategory:"CustomerCategory",CustomerDeliveryAddress:"CustomerDeliveryAddress",CustomerGroup:"CustomerGroup",CustomerLineOfBusiness:"CustomerLineOfBusiness",CustomerLog:"CustomerLog",CustomerXAreaCategory:"CustomerXAreaCategory",CustomFunction:"CustomFunction",CustomReport:"CustomReport",CylinderType:"CylinderType",DatabaseConnection:"DatabaseConnection",DataImport:"DataImport",DataOwner:"DataOwner",DataTransfer:"DataTransfer",DataTransferXFunction:"DataTransferXFunction",DeliveryTerm:"DeliveryTerm",Department:"Department",Deviation:"Deviation",DeviationType:"DeviationType",Document:"Document",DocumentCategory:"DocumentCategory",DocumentRevision:"DocumentRevision",DocumentType:"DocumentType",DocumentWebAccess:"DocumentWebAccess",DocumentXEntity:"DocumentXEntity",DoorKey:"DoorKey",DoorKeySystem:"DoorKeySystem",DoorKeyTransaction:"DoorKeyTransaction",DoorKeyXDoorLock:"DoorKeyXDoorLock",DoorLock:"DoorLock",DoorLockXArea:"DoorLockXArea",Drawing:"Drawing",DrawingText:"DrawingText",DrawingXLayerGroup:"DrawingXLayerGroup",DutyLog:"DutyLog",DutyLogCategory:"DutyLogCategory",DutyLogCategoryXGroup:"DutyLogCategoryXGroup",DutyLogEvent:"DutyLogEvent",DutyLogGroup:"DutyLogGroup",EmailTemplate:"EmailTemplate",EnergyBlock:"EnergyBlock",EnergyCategory:"EnergyCategory",EnergyConsumption:"EnergyConsumption",EnergyCounter:"EnergyCounter",EnergyDataFormat:"EnergyDataFormat",EnergyMeter:"EnergyMeter",EnergyPeriodicTask:"EnergyPeriodicTask",EnergyReading:"EnergyReading",EnergyUnit:"EnergyUnit",EnergyWorkOrder:"EnergyWorkOrder",EnergyWorkOrderXCounter:"EnergyWorkOrderXCounter",EntityHistory:"EntityHistory",EntityComment:"EntityComment",EntityLink:"EntityLink",EntityTask:"EntityTask",EntityCounter:"EntityCounter",EntityMailList:"EntityMailList",EntityPermission:"EntityPermission",EntityPermissionProfile:"EntityPermissionProfile",Equipment:"Equipment",EquipmentCategory:"EquipmentCategory",EquipmentOperatingHours:"EquipmentOperatingHours",EquipmentOperatingHourType:"EquipmentOperatingHourType",EquipmentRelocation:"EquipmentRelocation",EquipmentRental:"EquipmentRental",EquipmentTemplate:"EquipmentTemplate",EquipmentTemplateXCategory:"EquipmentTemplateXCategory",Estate:"Estate",EstateCategory:"EstateCategory",Event:"Event",EventXEntity:"EventXEntity",FieldInfoOverride:"FieldInfoOverride",FollowUp:"FollowUp",GeneralOptions:"GeneralOptions",GisEntity:"GisEntity",Gmdn:"Gmdn",GroundXBuilding:"GroundXBuilding",Hatching:"Hatching",HatchingXArea:"HatchingXArea",HourType:"HourType",BimFile:"BimFile",BimProject:"BimProject",IfcSettings:"IfcSettings",Image:"Image",ImageXEntity:"ImageXEntity",IntegrationData:"IntegrationData",InvoicingTerm:"InvoicingTerm",KeyXCustomer:"KeyXCustomer",KeyXPerson:"KeyXPerson",KeyXPersonDelivery:"KeyXPersonDelivery",KeyXUser:"KeyXUser",LanguageEntry:"LanguageEntry",LanguageField:"LanguageField",LanguageXWebText:"LanguageXWebText",LayerGroup:"LayerGroup",LayerGroupSet:"LayerGroupSet",LayerGroupSetXLayerGroup:"LayerGroupSetXLayerGroup",LeaseFollowUp:"LeaseFollowUp",ListHighlight:"ListHighlight",ListInfo:"ListInfo",ListLayout:"ListLayout",Log:"Log",LogSettings:"LogSettings",LogRecord:"LogRecord",Meter:"Meter",MeterReading:"MeterReading",MeterXArea:"MeterXArea",MobileMenuProfile:"MobileMenuProfile",NamedSelection:"NamedSelection",NamedSelectionValue:"NamedSelectionValue",NonsReference:"NonsReference",OperationalMessage:"OperationalMessage",Organization:"Organization",OrganizationSection:"OrganizationSection",OrganizationUnit:"OrganizationUnit",OrganizationXArea:"OrganizationXArea",PasswordHistory:"PasswordHistory",PaymentOrder:"PaymentOrder",PaymentOrderDistribution:"PaymentOrderDistribution",PaymentOrderForm:"PaymentOrderForm",PaymentOrderItem:"PaymentOrderItem",PaymentOrderItemXService:"PaymentOrderItemXService",PaymentOrderXBuildingXAreaCategoryXService:"PaymentOrderXBuildingXAreaCategoryXService",PaymentOrderXCostCenterXService:"PaymentOrderXCostCenterXService",PaymentTerm:"PaymentTerm",PeriodicTask:"PeriodicTask",PeriodicTaskEmailList:"PeriodicTaskEmailList",PeriodicTaskXArea:"PeriodicTaskXArea",PeriodicTaskXCraft:"PeriodicTaskXCraft",PeriodicTaskXEquipment:"PeriodicTaskXEquipment",PeriodicTaskXSparePart:"PeriodicTaskXSparePart",PeriodicTaskXResourceGroup:"PeriodicTaskXResourceGroup",PeriodicTaskXStandardText:"PeriodicTaskXStandardText",PeriodOfNotice:"PeriodOfNotice",Person:"Person",PersonRole:"PersonRole",PostalCode:"PostalCode",Price:"Price",PriceSheet:"PriceSheet",PriceSheetCategory:"PriceSheetCategory",PriceSheetCategoryPrice:"PriceSheetCategoryPrice",PriceSheetRevision:"PriceSheetRevision",PriceSheetXBuilding:"PriceSheetXBuilding",Priority:"Priority",Project:"Project",ProjectCategory:"ProjectCategory",ProjectType:"ProjectType",ProxyEntity:"ProxyEntity",PurchaseOrder:"PurchaseOrder",PurchaseOrderEmailList:"PurchaseOrderEmailList",PurchaseOrderForm:"PurchaseOrderForm",PurchaseOrderItem:"PurchaseOrderItem",ReferenceData:"ReferenceData",ReferenceType:"ReferenceType",Region:"Region",ReminderTemplate:"ReminderTemplate",RentalGroup:"RentalGroup",Report:"Report",Request:"Request",ResourceGroup:"ResourceGroup",ResourceGroupXCause:"ResourceGroupXCause",Role:"Role",RoleXUser:"RoleXUser",ScheduledJob:"ScheduledJob",ScheduledJobExecution:"ScheduledJobExecution",Service:"Service",ServicePrice:"ServicePrice",ServiceXAreaCategory:"ServiceXAreaCategory",Session:"Session",SparePart:"SparePart",SparePartCounting:"SparePartCounting",SparePartCountingItem:"SparePartCountingItem",SparePartCountingList:"SparePartCountingList",SparePartWithdrawal:"SparePartWithdrawal",StandardText:"StandardText",StartPage:"StartPage",Supplier:"Supplier",SupplierAgreement:"SupplierAgreement",SupplierLineOfBusiness:"SupplierLineOfBusiness",Symbol:"Symbol",Task:"Task",TransactionLog:"TransactionLog",User:"User",UserProfile:"UserProfile",UserSession:"UserSession",UserXCustomer:"UserXCustomer",UserXSparePartCountingList:"UserXSparePartCountingList",UserXWebProfile:"UserXWebProfile",UserXUserNotification:"UserXUserNotification",VideoXEntity:"VideoXEntity",WebCustomer:"WebCustomer",WebDashboard:"WebDashboard",WebListView:"WebListView",WebListViewColumn:"WebListViewColumn",WebMenu:"WebMenu",WebProfile:"WebProfile",WebProfileXWebMenu:"WebProfileXWebMenu",WebUserToken:"WebUserToken",WorkingDaysOff:"WorkingDaysOff",WorkOrder:"WorkOrder",WorkOrderEmailList:"WorkOrderEmailList",WorkOrderTrace:"WorkOrderTrace",WorkOrderXArea:"WorkOrderXArea",WorkOrderXResourceGroup:"WorkOrderXResourceGroup",WorkOrderXSparePart:"WorkOrderXSparePart"},service.alreadyRefreshingReport=!1,service}angular.module("Plania").factory("CommonService",["$localStorage",commonService])}(),function(){function documentService(config,repository,$window,$q){var service={},docContextMap={RegulatoryCompliance:1,Attestation:2,Description:4,Operation:8,Maintenance:16,ProductInfo:32,Instruction:64,Protocol:128,Identification:256,Drawing:512,Image:1024};return service.getDocumentationContext=function(documentationContextList){var summarizedDocContext=0;return _.forEach(documentationContextList,function(docContext){var docContextValue=docContextMap[docContext];summarizedDocContext|=docContextValue}),summarizedDocContext},service.openDocument=function(document){var deferred=$q.defer();return document.FilePath&&0===document.FilePath.indexOf("http")?($window.open(document.FilePath),$.Deferred().resolve().promise()):(repository.createSingle(repository.apiData.documentData.url,{GuidDocument:document.Guid}).then(function(result){var dataOwner=repository.commonService.getFilterData().selectedDataOwner.Guid;return $window.open(config.baseUrlApi+repository.apiData.documentData.url+result.Data.GuidDocumentResponse+"?dataOwner="+dataOwner+"&token="+result.Data.Token,"_blank"),deferred.resolve(result)},function(error){return deferred.reject(error)}),deferred.promise)},service}angular.module("Plania").factory("DocumentService",["config","Repository","$window","$q",documentService])}(),function(){function serviceMethod(){var service={};return service.getItems=function(groups){var items=[];return Array.isArray(groups)?(groups.forEach(function(group){group.Items.forEach(function(item){"Category"===item.Type?item.Template&&item.Template.Groups&&service.getItems(item.Template.Groups).forEach(function(x){items.push(x)}):items.push(item)})}),items):items},service}angular.module("Plania").factory("DynamicPropertyService",serviceMethod)}(),function(){function enumService(translationService,$q,repository){var service={},enumValues={};return service.getUnits=function(){return[{value:"$Th$",translatedValue:translationService.translate("web-enum-unit-hour","timer")},{value:"$Mkg$",translatedValue:translationService.translate("web-enum-unit-kilogram","kg")},{value:"$Vl$",translatedValue:translationService.translate("web-enum-unit-liter","liter")},{value:"$Qp$",translatedValue:translationService.translate("web-enum-unit-quantity","stk")}]},service.timeUnit={Undefined:-1,Day:0,Week:1,Month:2,Year:3,HourOfUse:4,Second:5,Minute:6,Hour:7,Once:8,WorkDay:10},service.setTimeUnitOnRecurrence=function(recurrenceRule){switch(recurrenceRule.Unit){case translationService.translate("web-enum-timeunit-day"):recurrenceRule.Unit=service.timeUnit.Day;break;case translationService.translate("web-enum-timeunit-week"):recurrenceRule.Unit=service.timeUnit.Week;break;case translationService.translate("web-enum-timeunit-month"):recurrenceRule.Unit=service.timeUnit.Month;break;case translationService.translate("web-enum-timeunit-year"):recurrenceRule.Unit=service.timeUnit.Year}},service.EnumNumberToString=function(enumType,number){var deferred=$q.defer();return"number"!=typeof number?number:(service.GetEnumValues(enumType).then(function(result){var enumOption=_.find(result,function(enumOptions){return enumOptions.Value===number});enumOption?deferred.resolve(enumOption.StringValue):deferred.reject("Could not find valid enum")}),deferred.promise)},service.GetEnumValues=function(enumType){var deferred=$q.defer();return enumValues[enumType]?deferred.resolve(enumValues[enumType]):repository.getSingle(repository.apiData.enum.url,enumType).then(function(result){enumValues[enumType]=result,deferred.resolve(enumValues[enumType])},function(error){deferred.reject("Kunne ikke finne enum: "+enumType)}),deferred.promise},service.getTimeUnitDate=function(date,timeUnit,timeUnitValue){switch(date!==typeof Date&&(date=new Date(date)),timeUnit){case"Undefined":return date;case"Day":return new Date(date.setDate(date.getDate()+timeUnitValue));case"Week":return new Date(date.setDate(date.getDate()+7*timeUnitValue));case"Month":return new Date(date.getFullYear(),date.getMonth()+timeUnitValue,date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds());case"Year":return new Date(date.getFullYear()+timeUnitValue,date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds());case"HourOfUse":return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours()+timeUnitValue,date.getMinutes(),date.getSeconds());case"Second":return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds()+timeUnitValue);case"Minute":return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes()+timeUnitValue,date.getSeconds());case"Hour":return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours()+timeUnitValue,date.getMinutes(),date.getSeconds());case"Once":return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds())}},service}angular.module("Plania").factory("EnumService",["TranslationService","$q","Repository",enumService])}(),function(){angular.module("Plania").factory("focus",["$timeout","$window",function($timeout,$window){return function(id){$timeout(function(){var chosenElement=$window.document.getElementById(id).getElementsByClassName("chosen-container")[0];if(chosenElement)return void chosenElement.classList.add("chosen-with-drop");var element=$window.document.getElementById(id).getElementsByTagName("input")[0];element||(element=$window.document.getElementById(id).getElementsByTagName("textarea")[0]),element&&element.focus()})}}])}(),function(){function generalOptionsService($localStorage,repository,$rootScope,$q){var service={};return service.getGeneralOptionsAsync=function(skipCache){ var deferred=$q.defer();return!skipCache&&$localStorage.generalOptions&&deferred.resolve($localStorage.generalOptions),repository.getSingleWithNoParameter(repository.apiData.generalOptions.url).then(function(result){$localStorage.generalOptions=result.Data,$rootScope.customization.customerId=result.Data.CustomerId,deferred.resolve($localStorage.generalOptions)},function(error){swal("Feil ved henting av Kundeprofil",error,"error"),deferred.reject("Error getting general options")}),deferred.promise},service.refreshGeneralOptions=function(){service.getGeneralOptionsAsync(!0)},service}angular.module("Plania").factory("GeneralOptionsService",["$localStorage","Repository","$rootScope","$q",generalOptionsService])}(),function(){function genericRepository($http,upload,config,authService,$q,$cacheFactory){var cache=$cacheFactory("genericRepositoryHttpOnce"),httpConfig=function(relativeUrl,method,data){return authService.refreshAuthentication().then(function(result){return{method:method,url:encodeURI(config.baseUrlApi+relativeUrl),headers:{"Content-Type":"application/json; charset=UTF-8"},data:data}})};return{post:function(relativeUrl,data){return httpConfig(relativeUrl,"POST",data).then(function(result){return $http(result)})},postFile:function(relativeUrl,data,files){return authService.refreshAuthentication().then(function(result){var deferred=$q.defer(),url=encodeURI(config.baseUrlApi+relativeUrl),filePromises=[];return files&&0!==files.length||(data.fileId=data.FilePath,filePromises.push(upload.upload({url:url,method:"POST",data:data}).then(function(result){return result},function(error){return{status:400,data:{Data:"string"==typeof error.data?error.data:error.data.Data.Message},config:error.config}}))),files.forEach(function(file){deferred.notify({id:file.id,count:0,total:file.size});var fileData=_.cloneDeep(data);fileData.fileName=file.name,fileData.fileId=file.id,filePromises.push(upload.upload({url:url,method:"POST",data:fileData,file:file,resumeSizeUrl:url.replace("?dataOwner",file.id+"?dataOwner"),resumeSizeResponseReader:function(data){return data.Data.Size},resumeChunkSize:"8MB"}).then(function(result){return deferred.notify({id:file.id,count:100,total:100}),result},function(error){return{status:400,data:{Data:"string"==typeof error.data?error.data:error.data.Data.Message},config:error.config}},function(progress){var file={id:progress.config.data.file.id,count:progress.loaded,total:progress.total};deferred.notify(file)}))}),$q.all(filePromises).then(function(results){var res={savedFiles:[],errorFiles:[],status:0};results.forEach(function(result){0!==res.status&&200===result.status||(res.status=result.status),200===result.status?result.config.data.IsExternalLink?res.savedFiles.push({id:result.config.data.fileId,guid:result.data.Data}):res.savedFiles.push({id:result.config.file.id,guid:result.data.Data}):result.config.data.IsExternalLink?res.errorFiles.push({id:result.config.data.fileId,guid:result.data.Data,error:result.data.Data}):res.errorFiles.push({id:result.config.file.id,error:result.data.Data})}),deferred.resolve(res)}),deferred.promise})},putFile:function(relativeUrl,data,file){return authService.refreshAuthentication().then(function(result){var deferred=$q.defer(),url=encodeURI(config.baseUrlApi+relativeUrl),filePromises=[];deferred.notify({id:file.id,count:0,total:file.size});var fileData=data||{};return fileData.fileName=file.name,fileData.fileId=file.id,filePromises.push(upload.upload({url:url,method:"PUT",data:fileData,file:file,resumeSizeUrl:url.replace("?dataOwner",file.id+"?dataOwner"),resumeSizeResponseReader:function(data){return data.Data.Size},resumeChunkSize:"8MB"}).then(function(result){return deferred.notify({id:file.id,count:100,total:100}),result},function(error){return{status:400,data:{Data:"string"==typeof error.data?error.data:error.data.Data.Message},config:error.config}},function(progress){var file={id:progress.config.data.file.id,count:progress.loaded,total:progress.total};deferred.notify(file)})),$q.all(filePromises).then(function(results){var res={savedFiles:[],errorFiles:[],status:0};results.forEach(function(result){0!==res.status&&200===result.status||(res.status=result.status),200===result.status?result.config.data.IsExternalLink?res.savedFiles.push({id:result.config.data.fileId,guid:result.data.Data}):res.savedFiles.push({id:result.config.file.id,guid:result.data.Data}):result.config.data.IsExternalLink?res.errorFiles.push({id:result.config.data.fileId,guid:result.data.Data}):res.errorFiles.push({id:result.config.file.id,error:result.data.Data})}),deferred.resolve(res)}),deferred.promise})},put:function(relativeUrl,data){return httpConfig(relativeUrl,"PUT",data).then(function(result){return $http(result)})},get:function(relativeUrl){return httpConfig(relativeUrl,"GET",{}).then(function(result){var promise=cache.get(relativeUrl);return promise&&0===promise.$$state.status?promise:cache.put(relativeUrl,$http(result))})},delete:function(relativeUrl,data){return httpConfig(relativeUrl,"DELETE",data).then(function(result){return $http(result)})},patch:function(relativeUrl,data){return httpConfig(relativeUrl,"PATCH",data).then(function(result){return $http(result)})}}}angular.module("Plania").factory("genericRepository",["$http","Upload","config","authService","$q","$cacheFactory",genericRepository])}(),function(){function iconService(){var service={},symbolMap={"money-bills":"fa-money-bills","alert-circle":"fa-circle-exclamation","alert-octagon":"fa-octagon-exclamation","alert-polygon":"fa-seal-exclamation","alert-triangle":"fa-triangle-exclamation",help:"fa-circle-question",info:"fa-info-circle","notifications-active":"fa-bell-on",notifications:"fa-bell",chart:"fa-square-poll-vertical","chart-donut":"fa-chart-pie",assignment:"fa-clipboard-list",dns:"fa-server",flag:"fa-flag",home:"fa-home","puzzle-piece":"fa-puzzle-piece",money:"fa-dollar-sign","money-box":"fa-square-dollar","shopping-cart":"fa-shopping-cart","shopping-basket":"fa-shopping-basket",store:"fa-store","shield-security":"fa-shield-quartered","shield-check":"fa-shield-check",plus:"fa-plus","plus-circle":"fa-plus-circle",star:"fa-star","desktop-windows":"fa-desktop-alt","device-hub":"fa-sitemap","trending-down":"fa-arrow-trend-down","trending-flat":"fa-arrow-right","trending-up":"fa-arrow-trend-up",arrows:"fa-expand-arrows-alt","rotate-left":"fa-undo-alt","rotate-right":"fa-redo-alt","my-location":"fa-location-crosshairs",pin:"fa-location-dot",apps:"fa-grid","view-dashboard":"fa-table-layout","view-column":"fa-table-columns",widgets:"fa-th-large",grid:"fa-th","flower-alt":"fa-seedling",flash:"fa-bolt-lightning","file-text":"fa-file-alt","file-plus":"fa-file-plus",file:"fa-file",copy:"fa-copy",bookmark:"fa-bookmark",dumpster:"fa-dumpster","trash-can":"fa-trash-can",fire:"fa-fire","fire-smoke":"fa-fire-smoke","fire-flame-curved":"fa-fire-flame-curved","fire-extinguisher":"fa-fire-extinguisher","fire-burner":"fa-fire-burner","dumpster-fire":"fa-dumpster-fire","sensor-fire":"fa-sensor-fire","house-fire":"fa-house-fire","block-brick-fire":"fa-block-brick-fire",campfire:"fa-campfire","sprinkler-ceiling":"fa-sprinkler-ceiling","hose-reel":"fa-hose-reel",snowflake:"fa-snowflake","truck-front":"fa-truck-front",plug:"fa-plug","wheelchair-move":"fa-wheelchair-move","vial-virus":"fa-vial-virus","temperature-arrow-up":"fa-temperature-arrow-up","temperature-arrow-down":"fa-temperature-arrow-down","suitcase-medical":"fa-suitcase-medical","oil-well":"fa-oil-well",mosquito:"fa-mosquito","money-bill-trend-up":"fa-money-bill-trend-up","magnifying-glass":"fa-search-plus",explosion:"fa-radiation-alt",biohazard:"fa-biohazard","pump-soap":"fa-pump-soap","gauge-min":"fa-gauge-min","gauge-max":"fa-gauge-max",bolt:"fa-bolt",water:"fa-water","transformer-bolt":"fa-transformer-bolt","pipe-section":"fa-pipe-section","battery-low":"fa-battery-low","battery-full":"fa-battery-full","battery-bolt":"fa-battery-bolt",percent:"fa-percent","piggy-bank":"fa-piggy-bank","universal-access":"fa-universal-access","eye-low-vision":"fa-eye-low-vision","shield-keyhole":"fa-shield-keyhole","box-open-full":"fa-box-open-full",fingerprint:"fa-fingerprint","user-lock":"fa-user-lock","burger-soda":"fa-burger-soda","traffic-light":"fa-traffic-light",chimney:"fa-chimney",rainbow:"fa-rainbow","box-heart":"fa-box-heart","person-shelter":"fa-person-shelter","360-degrees":"fa-360-degrees","street-view":"fa-street-view","hand-sparkles":"fa-hand-sparkles","hands-bubbles":"fa-hands-bubbles","container-storage":"fa-container-storage","water-arrow-up":"fa-water-arrow-up","water-arrow-down":"fa-water-arrow-down","tank-water":"fa-tank-water",wave:"fa-wave","bridge-water":"fa-bridge-water","arrow-up-from-water-pump":"fa-arrow-up-from-water-pump","bridge-lock":"fa-bridge-lock",recycle:"fa-recycle","diamond-exclamation":"fa-diamond-exclamation",leaf:"fa-leaf",filter:"fa-filter",a:"fa-a",b:"fa-b",c:"fa-c"},objectMap={key:"fa-key",lock:"fa-lock",church:"fa-church",tombstone:"fa-tombstone",user:"fa-circle-user",users:"fa-users-rectangle","car-tunnel":"fa-car-tunnel",bridge:"fa-bridge","charging-station":"fa-charging-station","tower-observation":"fa-tower-observation",building:"fa-building",school:"fa-school",hotel:"fa-hotel",ship:"fa-ship",hospital:"fa-hospital",road:"fa-road","tree-city":"fa-tree-city","tower-cell":"fa-tower-cell","satellite-dish":"fa-satellite-dish","mountain-city":"fa-mountain-city","mattress-pillow":"fa-mattress-pillow","house-chimney":"fa-house-chimney","house-flag":"fa-house-flag","gas-pump":"fa-gas-pump","gas-pump-slash":"fa-gas-pump-slash","bridge-water":"fa-bridge-water",bed:"fa-bed","garage-open":"fa-garage-open","car-wash":"fa-car-wash","car-side-bolt":"fa-car-side-bolt","building-user":"fa-building-user",apartment:"fa-apartment",forklift:"fa-forklift","utility-pole":"fa-utility-pole","lamp-street":"fa-lamp-street","house-day":"fa-house-day","house-night":"fa-house-night",industry:"fa-industry","wind-turbine":"fa-wind-turbine","solar-panel":"fa-solar-panel",fan:"fa-fan","vent-damper":"fa-vent-damper",heat:"fa-heat",shower:"fa-shower",lightbulb:"fa-lightbulb",elevator:"fa-elevator",shelves:"fa-shelves","pallet-boxes":"fa-pallet-boxes","door-closed":"fa-door-closed","truck-bolt":"fa-truck-bolt",gears:"fa-gears","folder-gear":"fa-folder-gear",truck:"fa-truck","car-side":"fa-car-side",campground:"fa-campground",monkey:"fa-monkey",print:"fa-print","tombstone-blank":"fa-tombstone-blank",menorah:"fa-menorah",chair:"fa-chair","house-chimney-user":"fa-house-chimney-user","house-medical":"fa-house-medical","house-chimney-heart":"fa-house-chimney-heart",book:"fa-book","book-open-cover":"fa-book-open-cover","lamp-floor":"fa-lamp-floor",shop:"fa-shop",mosque:"fa-mosque","place-of-worship":"fa-place-of-worship","circle-parking":"fa-circle-parking","bench-tree":"fa-bench-tree",toilet:"fa-toilet",anchor:"fa-anchor","anchor-lock":"fa-anchor-lock",ferry:"fa-ferry",lighthouse:"fa-lighthouse",sailboat:"fa-sailboat",buoy:"fa-buoy","warehouse-full":"fa-warehouse-full",bath:"fa-bath",excavator:"fa-excavator",bulldozer:"fa-bulldozer"},activityMap={"assignment-check":"fa-clipboard-check","thumb-up":"fa-thumbs-up","thumb-up-down":"fa-thumbs-down",case:"fa-briefcase","check-all":"fa-check-double",check:"fa-check","comment-alert":"fa-comment-exclamation",comment:"fa-comment",comments:"fa-comments",camera:"fa-camera",keyboard:"fa-keyboard",phone:"fa-phone",smartphone:"fa-mobile-alt","view-list":"fa-list-ul",alarm:"fa-alarm-clock","alarm-check":"fa-calendar-check","time-interval":"fa-timer",time:"fa-clock","time-countdown":"fa-stopwatch",timer:"fa-hourglass-start",calendar:"fa-calendar-alt","format-list-bulleted":"fa-list-ul","format-list-numbered":"fa-list-ol",hammer:"fa-hammer","person-falling":"fa-person-falling","person-digging":"fa-person-digging","person-chalkboard":"fa-user-tie","id-card":"fa-id-card","faucet-drip":"fa-faucet-drip","road-lock":"fa-road",wrench:"fa-wrench","traffic-cone":"fa-traffic-cone","user-helmet-safety":"fa-hard-hat",toolbox:"fa-toolbox","shovel-snow":"fa-shovel-snow",wifi:"fa-wifi","arrow-right-top":"fa-arrow-up-right","person-to-door":"fa-person-to-door","person-through-window":"fa-person-through-window",siren:"fa-siren","siren-on":"fa-siren-on","temperature-snow":"fa-temperature-snow","temperature-sun":"fa-temperature-sun","light-emergency-on":"fa-light-emergency-on","light-emergency":"fa-light-emergency",snowplow:"fa-snowplow",shovel:"fa-shovel",broom:"fa-broom",bucket:"fa-bucket",vacuum:"fa-vacuum",headset:"fa-headset"},mapIconMap={city:"fas fa-city",home:"fas fa-home",circle:"fas fa-circle",star:"fas fa-star","circle-dot":"far fa-circle-dot",gear:"fas fa-gear",envelope:"fas fa-envelope","briefcase-blank":"fas fa-briefcase-blank"},availableIcons=_.union(Object.keys(activityMap),Object.keys(symbolMap),Object.keys(objectMap)),iconMap=Object.assign({},symbolMap,objectMap,activityMap);return service.GetAvailableIcons=function(){return availableIcons},service.GetTabContent=function(tab){return"objects"===tab?Object.keys(objectMap):"symbols"===tab?Object.keys(symbolMap):"activities"===tab?Object.keys(activityMap):void 0},service.GetIconMap=function(){return iconMap},service.getIcon=function(iconKey){return iconMap[iconKey]},service.getAvailableMapIcons=function(){return Object.assign({},mapIconMap)},service.getIconsForMapUsage=function(){var map=service.getAvailableMapIcons();return Object.entries(iconMap).forEach(function(entry){var key=entry[0],value=entry[1];map[key]||(map[key]="fas "+value)}),map},service.getMapIcon=function(iconKey){return service.getIconsForMapUsage()[iconKey]},service}angular.module("Plania").factory("IconService",[iconService])}(),function(){function imageService($http,$q){var service={};return service.isImage=function(src){var deferred=$q.defer(),image=new Image;return image.onerror=function(){deferred.resolve(!1)},image.onload=function(){deferred.resolve(!0)},image.src=src,deferred.promise},service}angular.module("Plania").factory("imageService",["$http","$q",imageService])}(),function(){angular.module("Plania").factory("ListCompressionService",[function(){var service={};service.encodeListUri=function(stateObject){var minified=minifyStateObject(stateObject);return rison.encode_uri(minified)},service.decodeListUri=function(encoded){var minified=rison.decode_uri(encoded);return decodeUrlFilter(minified)};var columnsMapping={Position:"i",Title:"t",Property:"p",PropertyType:"pt",AutocompleteService:"as",AutocompleteProperty:"ap",Filter:"f",SortingDisabled:"sd"},listSetupMapping={Columns:"c",IsDefaultView:"d",Guid:"g",GuidDataOwner:"gd",Id:"i",inMemory:"m",EntityName:"n",IsPublicView:"p",Sorting:"s",EntityType:"t",GroupBy:"b",ContextId:"ctx"},propertyFilterMapping={Operand:"a",Operator:"o",Property:"p",Value:"v"},minifyStateObject=function(stateObject){var minifiedStateObject=angular.copy(stateObject),minifiedPropertyFilter=[],minifiedListSetup={};if(minifiedStateObject.selectedListSetup){if(minifiedStateObject.selectedListSetup.Columns){var minifiedColumns=[];minifiedStateObject.selectedListSetup.Columns.forEach(function(column){var newColumn={};for(var property in column)newColumn[columnsMapping[property]]=column[property];minifiedColumns.push(newColumn)}),minifiedStateObject.selectedListSetup.Columns=minifiedColumns}for(var property in minifiedStateObject.selectedListSetup)minifiedListSetup[listSetupMapping[property]]=minifiedStateObject.selectedListSetup[property];minifiedStateObject.selectedListSetup=minifiedListSetup}return minifiedStateObject.filter.PropertyFilter&&minifiedStateObject.filter.PropertyFilter.length>0&&(minifiedStateObject.filter.PropertyFilter.forEach(function(filter){var newFilter={};for(var property in filter)newFilter[propertyFilterMapping[property]]=filter[property];minifiedPropertyFilter.push(newFilter)}),minifiedStateObject.filter.PropertyFilter=minifiedPropertyFilter),minifiedStateObject},decodeUrlFilter=function(filterString){var decodedUrlFilter=angular.copy(filterString),decodedColumns=[],decodedPropertyFilter=[];if(decodedUrlFilter.selectedListSetup){decodedListSetup={};for(var property in decodedUrlFilter.selectedListSetup)for(var mappingProperty in listSetupMapping)listSetupMapping[mappingProperty]===property&&(decodedListSetup[mappingProperty]=decodedUrlFilter.selectedListSetup[property]);decodedUrlFilter.selectedListSetup=decodedListSetup,decodedUrlFilter.selectedListSetup.Columns&&(decodedUrlFilter.selectedListSetup.Columns.forEach(function(column){var newColumn={};for(var property in column)for(var mappingProperty in columnsMapping)columnsMapping[mappingProperty]===property&&(newColumn[mappingProperty]=column[property]);decodedColumns.push(newColumn)}),decodedUrlFilter.selectedListSetup.Columns=decodedColumns)}return decodedUrlFilter.filter&&decodedUrlFilter.filter.PropertyFilter&&decodedUrlFilter.filter.PropertyFilter.length>0&&(decodedUrlFilter.filter.PropertyFilter.forEach(function(filter){var newFilter={};for(var property in filter)for(var mappingProperty in propertyFilterMapping)propertyFilterMapping[mappingProperty]===property&&(newFilter[mappingProperty]=filter[property]);decodedPropertyFilter.push(newFilter)}),decodedUrlFilter.filter.PropertyFilter=decodedPropertyFilter),decodedUrlFilter};return service}])}(),function(){angular.module("Plania").factory("ListService",["$filter","$q","Repository","ngTableParams","TranslationService","$localStorage","ListCompressionService","ColorService","$state","Constants","$sce",function($filter,$q,repository,ngTableParams,translationService,$localStorage,listCompressionService,colorService,$state,constants,$sce){function isJson(str){try{JSON.parse(str)}catch(e){return!1}return!0}function sanitize(textField){try{return(textField.toString()||"").replace(/>/g,">").replace(/maxLength?result+"...":result}var service={},tableCellMaxLength=50,modifyResult=function(entityData,resultList,columns,filter){if(entityData.prefix===repository.apiData.areaXCleaningTask.prefix){if(!resultList||!columns)return;resultList.forEach(function(data){"Possible"===data.ExitCleaningRequestStatus?data.ExitCleaningConfirmedDate=null:data.ExitCleaningDecisionDate=null,-1!==data.ExitCleaningRequestStatus&&"Undefined"!==data.ExitCleaningRequestStatus||(data.ExitCleaningRequestStatus=null)})}};service.getNextCleaningDateString=function(task,usePeriodicEndDate){if(!task.NextCleaningDate)return translationService.translate("web-areaXCleaningTask-NextCleaning-oneTimeTask","Engangsoppgave");if(usePeriodicEndDate&&"PeriodicCleaning"===task.CleaningTask.CleaningType)return translationService.translate("web-areaXCleaningTask-periodicCleaning-within","Innen")+" "+$filter("date")(task.RecurrenceRule.EndDate,"dd.MM.yyyy");var date=new Date(task.NextCleaningDate);date.setHours(0,0,0,0);var today=new Date;today.setHours(0,0,0,0);var tomorrow=new Date(today);return tomorrow.setDate(tomorrow.getDate()+1),date.getTime()===today.getTime()?translationService.translate("web-areaXCleaningTask-NextCleaning-today","I dag"):date.getTime()===tomorrow.getTime()?translationService.translate("web-areaXCleaningTask-NextCleaning-tomorrow","I morgen "):date.getTime()1?(properties.shift(),temp=getJsonValue(temp.JsonData,properties.join("."))):properties.forEach(function(prop){temp&&(temp="Recurrence"===prop?temp.RecurrenceRule:temp[prop])&&temp.Prefix&&(prefixOfValue=temp.Prefix)}),!temp&&"bool"!==column.PropertyType&&0!==temp)return"";if("bool"===column.PropertyType)return temp?'':"";if("Severity"===column.Property){if(!temp)return"";switch(temp){case"Error":return' '+temp+"";case"Warning":return' '+temp+"";case"Info":return' '+temp+""}}if(row.Prefix===repository.commonService.prefix.OperationalMessage&&"Type"===column.Property){var operationalMessageTypeText=getEnumText(column.PropertyType,temp);if(!operationalMessageTypeText)return"";switch(temp){case"Information":return''+operationalMessageTypeText+"";case"Downtime":return''+operationalMessageTypeText+"";default:return operationalMessageTypeText}}if("CleaningEstimateYear"===column.Property||"AverageCleaningPerYear"===column.Property)return temp?$filter("time")(temp,"mm","hht mmm",!1):0;if("ExitCleaningDecisionDate"===column.Property||"ExitCleaningConfirmedDate"===column.Property)return temp?$filter("date")(temp,"HH:mm"):null;if(row.Prefix===repository.commonService.prefix.SparePartWithdrawal&&"Quantity"===column.Property){var sparePartWithDrawalQuantityText=temp>0?translationService.translate("web-sparePartWidthdrawal-quantity-consumption","Forbruk av"):translationService.translate("mobile-sparePartWidthdrawal-quantity-deposit","Påfyll av"),quantityText=temp||0;return quantityText=quantityText>0?quantityText:-quantityText,quantityText=$filter("number")(quantityText,2),""+sparePartWithDrawalQuantityText+" "+quantityText+""}if(row.Prefix===repository.commonService.prefix.AreaXCleaningTask&&"NextCleaningDate"===column.Property)return service.getNextCleaningDateString(row);if(row.Prefix===repository.commonService.prefix.WebMenu&&"Reference"===column.Property&&temp&&"string"==typeof temp&&isJson(temp)){var parsed=JSON.parse(temp);return parsed&&parsed.PropertyFilter?parsed.PropertyFilter.map(function(item){return item.Property+" "+item.Operator+" "+item.Value}).join(", "):temp}if(row.Prefix===repository.commonService.prefix.LogRecord&&"Message"===column.Property)return temp;if(row.Prefix===repository.commonService.prefix.LogRecord&&"CreationDate"===column.Property)return $filter("date")(temp,"dd.MM.yyyy, HH:mm:ss.sss");if("date"===column.PropertyType)return"CreationDate"===column.Property||"UpdatedDate"===column.Property?$filter("date")(temp,"dd.MM.yyyy, HH:mm:ss"):$filter("date")(temp,"dd.MM.yyyy");if("datetime"===column.PropertyType)return $filter("date")(temp,"dd.MM.yyyy, HH:mm:ss");if(!("double"!==column.PropertyType||column.Property&&column.Property.endsWith("CompletionRate")||"PaymentOrderCoverageRate"===column.Property))return 0===temp?0:$filter("number")(temp,2);if("recurrence"===column.PropertyType||"Recurrence"===column.Property)return $filter("plRecurrenceRuleFilter")(temp);if("progress"===column.PropertyType||column.Property&&column.Property.endsWith("CompletionRate")){column.Property&&column.Property.endsWith("CompletionRate")&&(temp=Number((100*temp).toFixed(0)));var progressValue=$filter("number")(temp,0),returnValue="";return temp<30?returnValue+=''+progressValue+"%":temp<60?returnValue+=''+progressValue+"%":temp<100?returnValue+=''+progressValue+"%":100===temp&&("success",returnValue+=' '+progressValue+"%"),returnValue}if("PaymentOrderCoverageRate"===column.Property)return temp=Number(Math.floor(100*temp).toFixed(0)),row.ReinvoicingStatus&&"None"!==row.ReinvoicingStatus&&temp<100?''+temp+"%":""+temp+"%";if(column.Property&&column.Property.endsWith("Priority.Description")){var splitProperties=column.Property.split("."),nestedProperty=row;if(splitProperties.slice(0,splitProperties.length-1).forEach(function(prop){nestedProperty&&"object"==typeof nestedProperty&&(nestedProperty=nestedProperty[prop])}),nestedProperty&&void 0!==nestedProperty.Color){var trustedText=$sce.getTrustedHtml(temp);return $sce.trustAsHtml(''+trustedText+"")}}if(column.PropertyType&&column.PropertyType.startsWith("enum.")){var enumText=getEnumText(column.PropertyType,temp);if(enumText)return enumText}if(column.Property&&(column.Property.endsWith("Consequence.Id")||column.Property.endsWith("ConditionType.Id"))){var splittedProperties=column.Property.split("."),nestedEntity=row;if(splittedProperties.slice(0,splittedProperties.length-1).forEach(function(prop){nestedEntity&&"object"==typeof nestedEntity&&(nestedEntity=nestedEntity[prop])}),nestedEntity&&void 0!==nestedEntity.LikertScale){var trustedTemp=$sce.getTrustedHtml(temp);return $sce.trustAsHtml(''+trustedTemp+"")}}if(column.Property&&(column.Property.startsWith("Combo")||"Deviation"===prefixOfValue&&"Cause"===column.Property)&&temp.startsWith("[")&&temp.endsWith("]"))return JSON.parse(temp).join(", ");return temp=sanitize(temp),"ReferencedTemplateNames"===column.Property?temp:limitResult(temp,tableCellMaxLength)},service.getWebListViews=function(selectedSetup,prefix,overrideDefault,contextId,filters){var deferred=$q.defer();return repository.GetPaginated(repository.apiData.webListView.url,0,100,{},{Prefix:prefix,ContextId:contextId}).then(function(result){var defaultListSetup,selectedListSetup,preSelectedSetup,listOptions=result.List;listOptions.forEach(function(setup){setup.IsDefaultView&&!overrideDefault&&(defaultListSetup=setup),selectedSetup&&setup.Guid===selectedSetup.Guid&&(preSelectedSetup=setup),setup.Columns.forEach(function(col){col.Filter&&"string"==typeof col.Filter&&(col.Filter=JSON.parse(col.Filter)),col.GroupBy&&(col.title=col.Title,col.field=col.Property,col.groupable=col.Property,col.show=!0)}),setup.VisibleColumns=_.filter(setup.Columns,function(c){return!c.Filter||!c.Filter.some(function(f){return f.Hidden})}),setup.Sorting&&"string"==typeof setup.Sorting&&(setup.Sorting=JSON.parse(setup.Sorting)),setup.IsPublicView?setup.isPublicViewText=translationService.translate("web-webListView-isPublicViewText-common","Felles"):setup.isPublicViewText=translationService.translate("web-webListView-isPublicViewText-personal","Personlig")});var plStandard=service.getStandardView(prefix,filters,contextId);plStandard.IsDefaultView=!defaultListSetup,plStandard.EntityName=plStandard.EntityType,plStandard.isPublicViewText=translationService.translate("web-webListView-isPublicViewText-common","Felles"),plStandard.ContextId||(plStandard.ContextId="List-"+plStandard.EntityType),_.find(listOptions,function(o){return o.Id===plStandard.Id})||listOptions.unshift(plStandard),selectedSetup&&selectedSetup.inMemory?(_.findWhere(listOptions,{Guid:selectedSetup.Guid})||"plania standard"===selectedSetup.Id.toLowerCase()||listOptions.push(selectedSetup),selectedListSetup=selectedSetup):selectedListSetup=preSelectedSetup||(defaultListSetup||listOptions[0]),selectedListSetup.VisibleColumns=_.filter(selectedListSetup.Columns,function(c){return!c.Filter||!c.Filter.some(function(f){return f.Hidden})}),deferred.resolve({listOptions:listOptions,selectedListSetup:selectedListSetup})},function(error){var plStandard=service.getStandardView(prefix,filters,contextId);plStandard.IsDefaultView=!0,plStandard.EntityName=plStandard.EntityType,deferred.resolve({listOptions:[plStandard],selectedListSetup:plStandard})}),deferred.promise},service.currentListSetup={},service.updateSelectedListSetup=function(prefix,listSetup){service.currentListSetup[prefix]=listSetup},service.updateUrl=function(tableParams,listSetup){var stateObject={};stateObject.filter=angular.copy(tableParams.filter()),delete stateObject.filter.selectedWebListView,stateObject.sorting=angular.copy(tableParams.sorting());var selectedListSetup={};selectedListSetup.inMemory=!0,selectedListSetup.Columns=_.map(listSetup.Columns,function(col){var newCol={Position:col.Position,Title:col.Title,Property:col.Property,PropertyType:col.PropertyType,AutocompleteService:col.AutocompleteService,AutocompleteProperty:col.AutocompleteProperty,Filter:col.Filter};return col.SortingDisabled&&(newCol.SortingDisabled=!0),newCol}),selectedListSetup.Guid=listSetup.Guid,selectedListSetup.GuidDataOwner=listSetup.GuidDataOwner,selectedListSetup.Id=listSetup.Id,selectedListSetup.ContextId=listSetup.ContextId,selectedListSetup.IsPublicView=listSetup.IsPublicView,selectedListSetup.IsDefaultView=listSetup.IsDefaultView,selectedListSetup.EntityName=listSetup.EntityName,selectedListSetup.EntityType=listSetup.EntityType,selectedListSetup.GroupBy=listSetup.GroupBy,selectedListSetup.Sorting=stateObject.sorting,stateObject.selectedListSetup=selectedListSetup,repository.location.search("filter",listCompressionService.encodeListUri(stateObject)).replace()},service.getNgTableParams=function(selectedListSetup,navigation,entityData,preSelected,filterParams,modifyResultFunc){service.updateSelectedListSetup(selectedListSetup.EntityName,selectedListSetup),$localStorage.listParams||($localStorage.listParams={}),$localStorage.listParams[entityData.prefix]||($localStorage.listParams[entityData.prefix]={});var menuParams=filterParams||{};if(menuParams.PropertyFilter||(menuParams.PropertyFilter=[]),navigation.params.menuGuid){var loadedParams=repository.getMenuParameters(navigation.params.menuGuid);for(var property in loadedParams)"PropertyFilter"!==property&&("selectedWebListView"===property&&"00000000-0000-0000-0000-000000000000"===loadedParams[property].Guid||Object.prototype.hasOwnProperty.call(loadedParams,property)&&(menuParams[property]=loadedParams[property]));if(loadedParams.PropertyFilter&&loadedParams.PropertyFilter.length>0){var webMenuFilter=angular.copy(loadedParams.PropertyFilter);menuParams.PropertyFilter.forEach(function(paramFilter){_.find(loadedParams.PropertyFilter,function(webFilter){return[paramFilter.Operand,paramFilter.Operator,paramFilter.Property,paramFilter.Value].join()===[webFilter.Operand,webFilter.Operator,webFilter.Property,webFilter.Value].join()})||webMenuFilter.push(paramFilter)}),menuParams.PropertyFilter=webMenuFilter}filterParams.searchString&&(menuParams.searchString=filterParams.searchString)}if(entityData.prefix===repository.apiData.userGroup.prefix&&menuParams.PropertyFilter.push({Property:"IsUserGroup",Operator:"=",Value:1}), entityData.prefix===repository.apiData.controlListItemAnswer.prefix&&(menuParams.FilterAnswerList=!0),entityData.contextId===planiaUtils.contextIds.dataAcquisitionDocXEntity&&(menuParams.FilterOnEquipment=!0),!(void 0!==menuParams.ActivityStatus&&null!==menuParams.ActivityStatus||entityData.prefix!==repository.apiData.workOrder.prefix&&entityData.prefix!==repository.apiData.project.prefix)){var filter=_.filter(menuParams.PropertyFilter,function(row){switch(entityData.prefix){case repository.apiData.workOrder.prefix:return"stage"===row.Property.toLowerCase();case entityData.prefix===repository.apiData.project.prefix:return"projectstatus.stage"===row.Property.toLowerCase()}});if(filter[0]){var stage=filter[0];menuParams.ActivityStatus="1"===stage.Value&&("="===stage.Operator||"in"===stage.Operator||"contains"===stage.Operator)||"1"!==stage.Value&&"="!==stage.Operator&&"in"!==stage.Operator&&"contains"!==stage.Operator?"Active":"History"}else switch(entityData.prefix){case repository.apiData.workOrder.prefix:menuParams.ActivityStatus=$localStorage.workOrderActivityStatus;break;case repository.apiData.project.prefix:"projectTemplate.list"!==$state.current.name&&(menuParams.ActivityStatus=$localStorage.projectActivityStatus)}}delete menuParams.Prefill;var items=new ngTableParams({page:$localStorage.listParams[entityData.prefix].page?$localStorage.listParams[entityData.prefix].page:1,count:$localStorage.listParams[entityData.prefix].count?$localStorage.listParams[entityData.prefix].count:20,sorting:selectedListSetup.Sorting,filter:menuParams},{total:0,counts:[20,50,100,200],filterDelay:10,paginationMaxBlocks:8,getData:function($defer,params){for($defer.promise.id=Math.random().toString(36).substr(2),items.newestPromise=$defer.promise,selectedListSetup.VisibleColumns=_.filter(selectedListSetup.Columns,function(c){return!c.Filter||!c.Filter.some(function(f){return f.Hidden})});items.data.length>0;)items.data.pop();var filter=_.cloneDeep(menuParams),columns=[];filter.PropertyFilter||(filter.PropertyFilter=[]),service.currentListSetup[selectedListSetup.EntityName].Columns.forEach(function(col){col.Filter&&(filter.PropertyFilter=filter.PropertyFilter.concat(col.Filter)),columns.push(col.Property)}),$localStorage.listParams[entityData.prefix]={page:params.page(),count:params.count()},selectedListSetup.EntityName!==repository.apiData.deviation.prefix&&selectedListSetup.EntityName!==repository.apiData.condition.prefix||(columns.push.apply(columns,["Estate.Id","Estate.Description","Building.Id","Building.Description","Area.Id","Area.Description","Equipment.Id","Equipment.Description"]),columns=_.uniq(columns)),selectedListSetup.EntityName===repository.apiData.controlListXEntity.prefix&&(columns.push.apply(columns,["ControlList.Color","ControlList.UseImage","ControlList.Guid"]),columns=_.uniq(columns)),selectedListSetup.ContextId===planiaUtils.contextIds.dataAcquisitionDocXEntity&&(columns.push.apply(columns,["Document.DocumentationContext","Document.FilePath"]),columns=_.uniq(columns)),selectedListSetup.EntityName===repository.apiData.area.prefix&&(columns.push.apply(columns,["GuidIfc"]),columns=_.uniq(columns)),selectedListSetup.EntityName===repository.apiData.dataImport.prefix&&(columns.push.apply(columns,["InputConfigJson"]),columns=_.uniq(columns)),service.updateUrl(params,service.currentListSetup[selectedListSetup.EntityName]);var sorting=params.sorting(),listSetup=service.currentListSetup[entityData.prefix];if(listSetup.GroupBy){var groupSort={};groupSort[listSetup.GroupBy]="asc";for(var attrname in sorting)groupSort[attrname]=sorting[attrname];sorting=groupSort,items.$params.sorting=groupSort}repository.GetPaginated(entityData.url,params.page()-1,params.count(),sorting,filter,preSelected,JSON.stringify(columns)).then(function(result){if(items.newestPromise.id!==$defer.promise.id)return void $defer.reject("not the most recent promise, ignoring result");items.settings().total=result.TotalCount,items.settings().filterDelay=500,0===result.List.length&&result.TotalCount>0&&items.page(1),modifyResultFunc&&modifyResultFunc(result.List),modifyResult(entityData,result.List,columns,filter),$defer.resolve(result.List),preSelected=null},function(error){repository.growl(error,"danger")})}});return items},service.getGroupName=function(prefix,obj){return service.getGroupNameFromListSetup(service.currentListSetup[prefix],obj)},service.getGroupNameFromListSetup=function(listSetup,obj,prefix){return!(!listSetup||!listSetup.GroupBy)&&(prefix||(prefix=listSetup.EntityType),listSetup.GroupBy.split(".").forEach(function(attr){if(obj=obj?obj[attr]:"","AreaXCleaningTask"===prefix&&"NextCleaningDate"===attr)if(obj){var date=new Date(obj);date.setHours(0,0,0,0);var today=new Date;today.setHours(0,0,0,0);var tomorrow=new Date(today);tomorrow.setDate(tomorrow.getDate()+1),obj=date.getTime()===today.getTime()?translationService.translate("web-areaXCleaningTask-NextCleaningDate-today","I dag"):date.getTime()===tomorrow.getTime()?translationService.translate("web-areaXCleaningTask-NextCleaningDate-tomorrow","I morgen "):date.getTime()",Value:3},{Property:"Status",Operator:"<>",Value:4}]},{Position:8,Title:translationService.translate("web-condition-year","År"),Property:"Year",PropertyType:"number"},{Position:9,Title:translationService.translate("web-condition-estimate","Overslag"),Property:"Estimate",PropertyType:"double"}]};case repository.apiData.request.prefix:return{Sorting:{Id:"desc"},Columns:[{Position:1,Title:translationService.translate("web-request-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-id"),Property:"Building.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidBuilding",AutocompleteService:"building"},{Position:3,Title:translationService.translate("web-building-description"),Property:"Building.Description",PropertyType:"autocomplete",AutocompleteProperty:"GuidBuilding",AutocompleteService:"building"},{Position:4,Title:translationService.translate("web-request-description"),Property:"Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-request-contactperson"),Property:"ContactPerson",PropertyType:"string"},{Position:6,Title:translationService.translate("web-request-status"),Property:"Status",PropertyType:"enum.requeststatus"},{Position:7,Title:translationService.translate("web-request-duedate"),Property:"DueDate",PropertyType:"date"},{Position:8,Title:translationService.translate("web-request-telephone"),Property:"Telephone",PropertyType:"string"}]};case repository.apiData.periodicTask.prefix:var columns=[],sorting={Id:"desc"};return columns=contextId===planiaUtils.contextIds.periodicTaskTemplate?[{Position:1,Title:translationService.translate("web-periodicTask-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-equipment-id"),Property:"Equipment.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidEquipment",AutocompleteService:"equipment"},{Position:3,Title:translationService.translate("web-equipment-description"),Property:"Equipment.Description",PropertyType:"autocomplete",AutocompleteProperty:"GuidEquipment",AutocompleteService:"equipment"},{Position:4,Title:translationService.translate("web-periodicTask-description"),Property:"Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-periodictask-interval"),Property:"Interval",PropertyType:"string"},{Position:6,Title:translationService.translate("web-periodictask-period"),Property:"Period",PropertyType:"enum.timeunit"},{Position:7,Title:translationService.translate("web-periodictask-must-link-instances"),Property:"MustLinkInstances",PropertyType:"bool"},{Position:8,Title:translationService.translate("web-periodictask-is-fire-related"),Property:"IsFireRelated",PropertyType:"bool"},{Position:9,Title:translationService.translate("web-periodictask-is-electro-related"),Property:"IsElectroRelated",PropertyType:"bool"}]:[{Position:1,Title:translationService.translate("web-periodictask-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-id"),Property:"Building.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidBuilding",AutocompleteService:"building"},{Position:3,Title:translationService.translate("web-building-description"),Property:"Building.Description",PropertyType:"autocomplete",AutocompleteProperty:"GuidBuilding",AutocompleteService:"building"},{Position:4,Title:translationService.translate("web-equipment-description"),Property:"Equipment.Description",PropertyType:"autocomplete",AutocompleteProperty:"GuidEquipment",AutocompleteService:"equipment"},{Position:5,Title:translationService.translate("web-periodictask-description"),Property:"Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-periodictask-interval"),Property:"Interval",PropertyType:"string"},{Position:7,Title:translationService.translate("web-periodictask-period"),Property:"Period",PropertyType:"enum.timeunit"},{Position:8,Title:translationService.translate("web-periodictask-duedate"),Property:"DueDate",PropertyType:"date"}],{Sorting:sorting,Columns:columns};case repository.apiData.webProfile.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-webprofile-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-webprofile-description","Beskrivelse"),Property:"Description",PropertyType:"string"}]};case repository.apiData.webMenu.prefix:return{Sorting:{Name:"asc"},Columns:[{Position:1,Title:translationService.translate("web-webmenu-name"),Property:"Name",PropertyType:"string"},{Position:2,Title:translationService.translate("web-webmenu-description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-webmenu-context"),Property:"Context",PropertyType:"string"},{Position:4,Title:translationService.translate("web-webmenu-reference"),Property:"Reference",PropertyType:"string"}]};case repository.apiData.webListView.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-webListView-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-webListView-EntityType","Entitet"),Property:"EntityType",PropertyType:"enum.PreFix"},{Position:3,Title:translationService.translate("web-webListView-IsPublicView","Felles"),Property:"IsPublicView",PropertyType:"bool"},{Position:4,Title:translationService.translate("web-webListView-ContextId","Kontekst"),Property:"ContextId",PropertyType:"string"},{Position:5,Title:translationService.translate("web-webListView-Username","Brukernavn"),Property:"User.Username",PropertyType:"string"},{Position:6,Title:translationService.translate("web-webListView-UserUpdatedBy","Oppdatert av"),Property:"UserUpdatedBy.RealName",PropertyType:"string"},{Position:7,Title:translationService.translate("web-webListView-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}],GroupBy:"EntityType"};case repository.apiData.buildingSelection.prefix:return{Sorting:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-buildingselection-description","Beskrivelse"),Property:"Description",PropertyType:"string"}]};case repository.apiData.controlList.prefix:return{Sorting:{Id:"desc"},Columns:[{Position:1,Title:translationService.translate("web-controlList-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-controlList-name","Navn"),Property:"Name",PropertyType:"string"},{Position:3,Title:translationService.translate("web-controlList-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-controlList-versionStatus","Status"),Property:"VersionStatus",PropertyType:"enum.ControlListVersionStatus"},{Position:5,Title:translationService.translate("web-controlList-versionComment","Revisjonskommentar"),Property:"VersionComment",PropertyType:"string"},{Position:6,Title:translationService.translate("web-controlList-isMandatory","Obligatorisk"),Property:"IsMandatory",PropertyType:"bool"},{Position:7,Title:translationService.translate("web-controlList-useImage","Bilder tillat"),Property:"UseImage",PropertyType:"bool"},{Position:8,Title:translationService.translate("web-controlList-useWithWorkOrder","Arbeidsordre"),Property:"UseWithWorkOrder",PropertyType:"bool"},{Position:9,Title:translationService.translate("web-controlList-useWithEquipment","Anlegg"),Property:"UseWithEquipment",PropertyType:"bool"},{Position:10,Title:translationService.translate("web-controlList-useWithArea","Areal"),Property:"UseWithArea",PropertyType:"bool"}]} ;case repository.apiData.controlListXEntity.prefix:var controlListXEntityColumns=[],controlListXEntitySorting={ClosedDate:"asc"};return contextId===planiaUtils.contextIds.controlListControlListXEntityPeriodicTask?(controlListXEntitySorting={"PeriodicTask.Id":"desc"},controlListXEntityColumns=[{Position:1,Title:translationService.translate("web-periodicTask-id","Periodisk Nr."),Property:"PeriodicTask.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-periodicTask-description","Periodisk Beskrivelse"),Property:"PeriodicTask.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-estate-id","Eiendom"),Property:"PeriodicTask.Estate.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-building-id","Bygg"),Property:"PeriodicTask.Building.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-periodicTask-dueDate","Forfallsdato"),Property:"PeriodicTask.DueDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-periodicTask-lastExecutedDate","Sist utført"),Property:"PeriodicTask.LastExecutedDate",PropertyType:"date"}]):controlListXEntityColumns=[{Position:1,Title:translationService.translate("web-controlList-id","Id"),Property:"ControlList.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-controlList-name","Navn"),Property:"ControlList.Name",PropertyType:"string"},{Position:3,Title:translationService.translate("web-controlList-description","Beskrivelse"),Property:"ControlList.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-workOrder-id","Id"),Property:"WorkOrder.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-workOrder-description","Beskrivelse"),Property:"WorkOrder.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-controlListXEntity-ClosedDate","Fullført dato"),Property:"ClosedDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-controlListXEntity-UserClosedBy","Fullført av"),Property:"UserClosedBy.RealName",PropertyType:"string"}],{Sorting:controlListXEntitySorting,Filter:{PropertyFilter:[{Property:"ClosedDate",Operator:"<>",Value:null}]},Columns:controlListXEntityColumns};case repository.apiData.controlListItemAnswer.prefix:return{Sorting:{"ControlListItem.Name":"asc"},Filter:{},Columns:[{Position:1,Title:translationService.translate("web-ControlList-Name","Kontrolliste"),Property:"ControlListXEntity.ControlList.Name",PropertyType:"string"},{Position:1,Title:translationService.translate("web-ControlList-Description","Beskrivelse"),Property:"ControlListXEntity.ControlList.Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-controlListItem-Name","Kontrollpunkt"),Property:"ControlListItem.Name",PropertyType:"string"},{Position:3,Title:translationService.translate("web-controlListItemAnswer-Name","Svar"),Property:"Value",PropertyType:"string"},{Position:4,Title:translationService.translate("web-workorder-id","Ao nr."),Property:"ControlListXEntity.WorkOrder.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-workOrder-description","Beskrivelse"),Property:"ControlListXEntity.WorkOrder.Description",PropertyType:"string"}]};case repository.apiData.translate.prefix:return{Sorting:{"WebText.SystemName":"asc"},Columns:[{Position:1,Title:translationService.translate("web-translation-SystemName","Systemnavn"),Property:"WebText.SystemName",PropertyType:"string"},{Position:2,Title:translationService.translate("web-translation-defaultvalue","Standard verdi"),Property:"DefaultTranslatedValue",PropertyType:"string"},{Position:2,Title:translationService.translate("web-translation-value","Verdi"),Property:"TranslatedValue",PropertyType:"string"},{Position:3,Title:translationService.translate("web-translation-language","Språk"),Property:"Language.Locale",PropertyType:"string"},{Position:3,Title:translationService.translate("web-translation-updateddate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.log.prefix:return{Sorting:{CreationDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-log-severity","Severity"),Property:"Severity",PropertyType:"enum.logseverity"},{Position:2,Title:translationService.translate("web-log-message","Melding"),Property:"Message",PropertyType:"string"},{Position:3,Title:translationService.translate("web-log-category","Kategori"),Property:"Category",PropertyType:"enum.RestrictedLogCategory",Filter:[{Property:"Category",Operator:"=",Value:4}]},{Position:4,Title:translationService.translate("web-log-creationdate","Opprettet dato"),Property:"CreationDate",PropertyType:"date"}]};case repository.apiData.dataOwner.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-dataowner-id","Klient ID"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-dataowner-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-dataowner-updateddate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.webDashboard.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-dashboard-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-dashboard-description","Beskrivelse"),Property:"Description",PropertyType:"string"}]};case repository.apiData.userGroup.prefix:return{Sorting:{RealName:"asc"},Columns:[{Position:1,Title:translationService.translate("web-user-realname","Navn"),Property:"RealName",PropertyType:"string"},{Position:2,Title:translationService.translate("web-user-administratorComment","Admin kommentar"),Property:"AdministratorComment",PropertyType:"string"},{Position:3,Title:translationService.translate("web-user-licenseType","Lisenstype"),Property:"LicenseType",PropertyType:"enum.LicenseType"},{Position:4,Title:translationService.translate("web-user-updatedDate","Sist redigert"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.user.prefix:return{Sorting:{Username:"asc"},Columns:[{Position:1,Title:translationService.translate("web-user-username","Brukernavn"),Property:"Username",PropertyType:"string"},{Position:2,Title:translationService.translate("web-user-realname","Navn"),Property:"RealName",PropertyType:"string"},{Position:3,Title:translationService.translate("web-user-phonenumber","Telefon"),Property:"PhoneNumber",PropertyType:"string"},{Position:4,Title:translationService.translate("web-user-email","E-post"),Property:"Email",PropertyType:"string"},{Position:5,Title:translationService.translate("web-user-licenseType","Lisenstype"),Property:"LicenseType",PropertyType:"enum.LicenseType"}]};case repository.apiData.userXWebProfile.prefix:return{Sorting:{"User.Username":"asc"},Columns:[{Position:1,Title:translationService.translate("web-userXWebprofile-IndexPosition","Rekkefølge"),Property:"IndexPosition",PropertyType:"string"},{Position:2,Title:translationService.translate("web-user-username","Brukernavn"),Property:"User.Username",PropertyType:"string"},{Position:3,Title:translationService.translate("web-webprofile-id","Id"),Property:"WebProfile.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-webprofile-description","Beskrivelse"),Property:"WebProfile.Description",PropertyType:"string"}]};case repository.apiData.conditionType.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-conditionType-id","TG"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-conditionType-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-conditionType-value","Verdi"),Property:"Value",PropertyType:"double"},{Position:4,Title:translationService.translate("web-conditionType-IsApproved","Godkjent"),Property:"IsApproved",PropertyType:"bool"},{Position:5,Title:translationService.translate("web-conditionType-likert","Farge"),Property:"LikertScale",PropertyType:"int"},{Position:6,Title:translationService.translate("web-conditionType-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.activityGroup.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-activityGroup-description","Navn"),Property:"Id",PropertyType:"string"}]};case repository.apiData.standardText.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-standardText-Id","Navn"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-standardText-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-standardText-descriptivetext","Tekst"),Property:"DescriptiveText",PropertyType:"string"},{Position:4,Title:translationService.translate("web-standardText-Oppdatert dato","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.deviationType.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-deviationType-Id","ID"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-deviationType-Deviation","Avvik"),Property:"Description",PropertyType:"string"},{Position:1,Title:translationService.translate("web-deviationType-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.hourType.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-hourType-Id","ID"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-hourType-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:1,Title:translationService.translate("web-hourType-Price","Pris"),Property:"Price",PropertyType:"double"}]};case repository.apiData.personRole.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-personRole-Id","ID"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-personRole-IsFireRelated","Brann"),Property:"IsFireRelated",PropertyType:"bool"},{Position:3,Title:translationService.translate("web-personRole-IsElectroRelated","Elektro"),Property:"IsElectroRelated",PropertyType:"bool"},{Position:4,Title:translationService.translate("web-personRole-IsHseRelated","HMS"),Property:"IsHseRelated",PropertyType:"bool"},{Position:5,Title:translationService.translate("web-personRole-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.costCenter.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-costCenter-Id","ID"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-costcenter-description","Description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-costcenter-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.department.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-department-Id","ID"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-department-description","Description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-department-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.account.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-account-Id","ID"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-account-description","Description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-account-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.entityPermissionProfile.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-entityPermissionprofile-licenseType","Lisenstype"),Property:"Type",PropertyType:"enum.EntityPermissionProfileLicenseType"},{Position:2,Title:translationService.translate("web-entityPermissionprofile-Id","ID"),Property:"Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-entityPermissionprofile-description","Description"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-entityPermissionprofile-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:5,Title:translationService.translate("web-entityPermissionprofile-CreationDate","Opprettet Dato"),Property:"CreationDate",PropertyType:"date"}]};case repository.apiData.areaXCleaningTask.prefix:return{Sorting:{"Area.Id":"asc"},Columns:[{Position:1,Title:translationService.translate("web-cleaning-id"),Property:"Area.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cleaning-description","Romnavn"),Property:"Area.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-cleaning-cleaning","Renhold"),Property:"CleaningTask.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-cleaning-cleaner","Renholder"),Property:"Cleaner",PropertyType:"string"},{Position:5,Title:translationService.translate("web-cleaning-team","Team"),Property:"ResourceGroup.Id",PropertyType:"string"},{Position:6,Title:translationService.translate("web-cleaning-nextCleaningDate","Utføres"),Property:"NextCleaningDate",PropertyType:"string"},{Position:7,Title:translationService.translate("web-cleaning-lastCompletedDate","Sist utført"),Property:"LastCleanedDate",PropertyType:"date"},{Position:8,Title:translationService.translate("web-cleaning-lastcompletedby","Sist utført av"),Property:"LastCleanedBy",PropertyType:"string"}]};case repository.apiData.cleaningQuality.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-cleaningQuality-Id","ID"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cleaningQuality-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cleaningQuality-note","Kommentar"),Property:"Note",PropertyType:"string"},{Position:3,Title:translationService.translate("web-cleaningQuality-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.cleaningQualityControl.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-cleaningQualityControl-Id","ID"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cleaningQualityControl-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-cleaningQualityControl-Status","Status"),Property:"Status",PropertyType:"string",SortingDisabled:!0},{Position:4,Title:translationService.translate("web-cleaningQualityControl-PercentComplete","Fremdrift"),Property:"PercentComplete",PropertyType:"progress",SortingDisabled:!0},{Position:5,Title:translationService.translate("web-cleaningQualityControl-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.cleaningTask.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-cleaningTask-Id","Navn"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cleaningTask-estimatedTime","Renholdsnormtall"),Property:"EstimatedTime",PropertyType:"number"},{Position:3,Title:translationService.translate("web-cleaningTask-estimatedCost","Estimert kost"),Property:"EstimatedCost",PropertyType:"double"},{Position:4,Title:translationService.translate("web-cleaningTask-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.cleaningCompletion.prefix:return{Sorting:{CompletionDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-cleaningCompletion-id","Romnummer"),Property:"Area.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cleaningCompletion-description","Romnavn"),Property:"Area.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-cleaningCompletion-cleaning","Renhold"),Property:"CleaningTask.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-cleaningCompletion-CompletionStatus","Status"),Property:"CompletionStatus",PropertyType:"enum.completionStatus"},{Position:5,Title:translationService.translate("web-cleaningCompletion-CompletionDate","Fullført dato"),Property:"CompletionDate",PropertyType:"date"}]};case repository.apiData.priority.prefix:return{Sorting:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-priority-Description","Navn"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-priority-EntityType","Entitetstype"),Property:"EntityType",PropertyType:"enum.prefix"},{Position:3,Title:translationService.translate("web-priority-level","Prioritetsnivå"),Property:"Level",PropertyType:"enum.priorityLevel"},{Position:4,Title:translationService.translate("web-priority-color","Farge"),Property:"Color",PropertyType:"string"},{Position:5,Title:translationService.translate("web-priority-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.customer.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-customer-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-customer-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-customer-Telephone","Telefon"),Property:"Telephone",PropertyType:"string"},{Position:2,Title:translationService.translate("web-customer-Email","Epost"),Property:"Email",PropertyType:"string"},{Position:2,Title:translationService.translate("web-customer-StreetAddress","Addresse"),Property:"StreetAddress",PropertyType:"string"},{Position:3,Title:translationService.translate("web-customer-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.invoicingTerm.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-invoicing-term-Id","Id"),Property:"Id",PropertyType:"string"}]};case repository.apiData.paymentTerm.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-payment-term-Id","Id"),Property:"Id",PropertyType:"string"},{Position:1,Title:translationService.translate("web-payment-term-Days","Days"),Property:"Days",PropertyType:"number"}]};case repository.apiData.paymentOrderForm.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-payment-order-form-Id","Id"),Property:"Id",PropertyType:"string"}]};case repository.apiData.contractType.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-contract-type-Id","Id"),Property:"Id",PropertyType:"string"}]};case repository.apiData.areaCategory.prefix:return{Sorting:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-areaCategory-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-areaCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"},{Position:3,Title:translationService.translate("web-areaCategory-Differentiated","Differensiert"),Property:"Differentiated",PropertyType:"string"},{Position:4,Title:translationService.translate("web-areaCategory-Factor","Faktor"),Property:"Factor",PropertyType:"number"},{Position:5,Title:translationService.translate("web-areaCategory-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-areaCategory-ReferencedTemplateNames","Refererte maler"),Property:"ReferencedTemplateNames",PropertyType:"string"}]};case repository.apiData.equipmentCategory.prefix:return{Sorting:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-equipmentCategory-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-equipmentCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"},{Position:3,Title:translationService.translate("web-equipmentCategory-Icon","Ikon"),Property:"Icon",PropertyType:"string"},{Position:4,Title:translationService.translate("web-equipmentCategory-Color","Farge"),Property:"Color",PropertyType:"string"},{Position:5,Title:translationService.translate("web-equipmentCategory-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-equipmentCategory-ReferencedTemplateNames","Refererte maler"),Property:"ReferencedTemplateNames",PropertyType:"string"}]};case repository.apiData.buildingCategory.prefix:return{Sorting:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-buildingCategory-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-buildingCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"},{Position:3,Title:translationService.translate("web-buildingCategory-Icon","Ikon"),Property:"Icon",PropertyType:"string"},{Position:4,Title:translationService.translate("web-buildingCategory-Color","Farge"),Property:"Color",PropertyType:"string"},{Position:5,Title:translationService.translate("web-buildingCategory-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-buildingCategory-ReferencedTemplateNames","Refererte maler"),Property:"ReferencedTemplateNames",PropertyType:"string"}]};case repository.apiData.estateCategory.prefix:return{Sorting:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-estateCategory-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-estateCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"},{Position:3,Title:translationService.translate("web-estateCategory-Icon","Ikon"),Property:"Icon",PropertyType:"string"},{Position:4,Title:translationService.translate("web-estateCategory-Color","Farge"),Property:"Color",PropertyType:"string"},{Position:5,Title:translationService.translate("web-estateCategory-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-estateCategory-ReferencedTemplateNames","Refererte maler"),Property:"ReferencedTemplateNames",PropertyType:"string"}]};case repository.apiData.componentCategory.prefix:return{Sorting:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-componentCategory-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-componentCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"},{Position:3,Title:translationService.translate("web-componentCategory-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:4,Title:translationService.translate("web-componentCategory-ReferencedTemplateNames","Refererte maler"),Property:"ReferencedTemplateNames",PropertyType:"string"}]};case repository.apiData.activityCategory.prefix:return{Sorting:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-activityCategory-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-activityCategory-UseInWorkOrder","Arbeidsordre"),Property:"UseInWorkOrder",PropertyType:"bool"},{Position:3,Title:translationService.translate("web-activityCategory-UseInRequest","Melding"),Property:"UseInRequest",PropertyType:"bool"},{Position:4,Title:translationService.translate("web-activityCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"},{Position:5,Title:translationService.translate("web-activityCategory-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-activityCategory-ReferencedTemplateNames","Refererte maler"),Property:"ReferencedTemplateNames",PropertyType:"string"}]};case repository.apiData.projectCategory.prefix:return{Sorting:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-projectCategory-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-projectCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"},{Position:3,Title:translationService.translate("web-projectCategory-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:4,Title:translationService.translate("web-projectCategory-ReferencedTemplateNames","Refererte maler"),Property:"ReferencedTemplateNames",PropertyType:"string"}]};case repository.apiData.projectType.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-priority-Id","Navn"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-priority-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.consequenceType.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-consequenceType-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-consequenceType-Description","Navn"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-consequenceType-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.consequence.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-consequence-id","TG"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-consequence-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-consequence-value","Verdi"),Property:"Value",PropertyType:"double"},{Position:4,Title:translationService.translate("web-consequence-likert","Farge"),Property:"LikertScale",PropertyType:"int"},{Position:5,Title:translationService.translate("web-consequence-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.cylinderType.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-cylinderType-Id","Navn"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-cylinderType-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.article.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-article-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-article-Description","Beskrivelse"),Property:"Description",PropertyType:"string"}]};case repository.apiData.resourceGroup.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-resourceGroup-Id","Id"),Property:"Id",PropertyType:"string"},{Position:1,Title:translationService.translate("web-resourceGroup-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-resourceGroup-CostPrHour","Timerate"),Property:"CostPrHour",PropertyType:"string"},{Position:2,Title:translationService.translate("web-resourceGroup-updateDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.namedSelection.prefix:return{Sorting:{Value:"asc"},Columns:[{Position:1,Title:translationService.translate("web-namedSelection-entityType","Entitetstype"),Property:"EntityType",PropertyType:"enum.prefix"},{Position:2,Title:translationService.translate("web-namedSelection-value","Verdi"),Property:"Value",PropertyType:"string"},{Position:3,Title:translationService.translate("web-namedSelection-SizeOfCombo","Visningsstørrelse"),Property:"SizeOfCombo",PropertyType:"enum.namedSelectionSize"},{Position:4,Title:translationService.translate("web-namedSelection-DefaultNamedSelectionValue-value","Standardverdi"),Property:"DefaultNamedSelectionValue.Value",PropertyType:"string"},{Position:5,Title:translationService.translate("web-namedSelection-updatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}],GroupBy:"EntityType"};case repository.apiData.alarmLog.prefix:return{Sorting:{CreationDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-alarmLog-EmailFrom","Fra"),Property:"EmailFrom",PropertyType:"string"},{Position:2,Title:translationService.translate("web-alarmLog-EmailTo","Til"),Property:"EmailTo",PropertyType:"string"},{Position:3,Title:translationService.translate("web-alarmLog-EmailCopyTo","Kopi til"),Property:"EmailCopyTo",PropertyType:"string"},{Position:4,Title:translationService.translate("web-alarmLog-EmailSubject","Emne"),Property:"EmailSubject",PropertyType:"string"},{Position:5,Title:translationService.translate("web-alarmLog-Status","Status"),Property:"Status",PropertyType:"enum.alarmstatus"},{Position:6,Title:translationService.translate("web-alarmLog-SentDate","Dato sendt"),Property:"SentDate",PropertyType:"date"},{Position:7,Title:translationService.translate("web-alarmLog-CreationDate","Dato opprettet"),Property:"CreationDate",PropertyType:"date"}]};case repository.apiData.purchaseOrder.prefix:return{Sorting:{Id:"desc"},Columns:[addColumn(1,"web-purchaseOrder-Id","Id","Id","string"),addColumn(2,"web-purchaseOrder-Description","Beskrivelse","Description","string"),addColumn(3,"web-supplier-Description","Leverandør","Supplier.Description","string"),addColumn(4,"web-purchaseOrder-Status","Status","Status","enum.purchaseorderstatus"),addColumn(4,"web-purchaseOrder-Amount","Beløp","Amount","double"),addColumn(5,"web-purchaseOrder-OrderingDate","Bestilt dato","OrderingDate","date"),addColumn(6,"web-purchaseOrder-DeliveryDate","Leveringsdato","DeliveryDate","date"),addColumn(7,"web-purchaseOrder-OurReference","Vår ref.","OurReference","string")]};case repository.apiData.purchaseOrderItem.prefix:return{Sorting:{Id:"desc"},Columns:[{Position:1,Title:translationService.translate("web-purchaseOrder-Id"),Property:"PurchaseOrder.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-purchaseOrderItem-Id"),Property:"Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-purchaseOrderItem-Description"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-supplier-Description","Leverandør navn"),Property:"Supplier.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-purchaseOrderItem-OrderedQuantity","Bestilt antall"),Property:"OrderedQuantity",PropertyType:"number"},{Position:6,Title:translationService.translate("web-purchaseOrderItem-UnitPrice","Enhetspris"),Property:"UnitPrice",PropertyType:"double"},{Position:7,Title:translationService.translate("web-purchaseOrderItem-OrderedAmount","Bestilt beløp"), Property:"OrderedAmount",PropertyType:"double"},{Position:8,Title:translationService.translate("web-purchaseOrderItem-Status","Status"),Property:"Status",PropertyType:"enum.PurchaseOrderItemStatus"}]};case repository.apiData.purchaseOrderForm.prefix:return{Sorting:{Description:"asc"},Columns:[addColumn(1,"web-purchaseOrderForm-Description","Beskrivelse","Description","string"),addColumn(2,"web-purchaseOrderForm-FilePath","Filsti","FilePath","string"),addColumn(3,"web-purchaseOrderForm-WebReport","Web rapport","Report.Name","string")]};case repository.apiData.cost.prefix:return{Sorting:{InvoiceDate:"desc"},Columns:[addColumn(1,"web-supplier-id","Leverandør nr","Supplier.Id","string"),addColumn(2,"web-supplier-description","Leverandør navn","Supplier.Description","string"),addColumn(3,"web-cost-InvoiceNumber","Fakturanr.","InvoiceNumber","string"),addColumn(4,"web-cost-VoucherNumber","Bilagsnr.","VoucherNumber","string"),addColumn(5,"web-cost-Description","Fakturabeskrivelse","Description","string"),addColumn(6,"web-cost-InvoiceDate","Fakturadato","InvoiceDate","date"),addColumn(7,"web-building-Id","Bygg Id","Building.Id","string"),addColumn(8,"web-workOrder-id","Ao nr","WorkOrder.Id","string"),addColumn(9,"web-purchaseOrder-id","Best. nr.","PurchaseOrder.Id","string"),addColumn(10,"web-cost-entityId","Objekt Id","EntityId","string"),addColumn(11,"web-cost-entityDescription","Objekt beskrivelse","EntityDescription","string"),addColumn(12,"web-cost-amount","Beløp","Amount","double"),addColumn(13,"web-cost-postingDate","Budsjettperiode","PostingDate","date"),addColumn(14,"web-costCenter-id","Kost sted","CostCenter.Id","string"),addColumn(15,"web-account-id","Konto","Account.Id","string"),addColumn(16,"web-cost-UpdatedDate","Oppdatert dato","UpdatedDate","date"),addColumn(17,"web-cost-CreationDate","Opprettet dato","CreationDate","date")]};case repository.apiData.budget.prefix:return{Sorting:{Year:"desc"},Columns:[addColumn(1,"web-budget-Year","År","Year","number"),addColumn(2,"web-budget-Account","Konto","Account.Id","string"),addColumn(3,"web-budget-AccountDescription","Konto Beskrivelse","Account.Description","string"),addColumn(4,"web-budget-CostCenter","Koststed Id","CostCenter.Id","string"),addColumn(5,"web-budget-CostCenterDescription","Koststed","CostCenter.Description","string"),addColumn(6,"web-budget-Department","Avdeling","Department.Id","string"),addColumn(7,"web-budget-Budget","Sum budjsett","SumBudget","double"),addColumn(8,"web-budget-SumCost","Sum kostnader","SumCost","double"),addColumn(9,"web-budget-SumDisposal","Til disposisjon","SumForDisposal","double")]};case repository.apiData.documentCategory.prefix:return{Sorting:{Description:"asc"},Columns:[addColumn(1,"web-documentCategory-Description","Kategori dokument","Description","string"),addColumn(2,"web-documentCategory-IsAbstract","Mal","IsAbstract","bool"),addColumn(3,"web-documentCategory-updateDate","Oppdatert dato","UpdatedDate","date"),addColumn(4,"web-documentCategory-ReferencedTemplateNames","Refererte maler","ReferencedTemplateNames","string")]};case repository.apiData.documentType.prefix:return{Sorting:{Id:"asc"},Columns:[addColumn(1,"web-documentType-Id","Dok. type","Id","string"),addColumn(2,"web-documentType-updateDate","Oppdatert dato","UpdatedDate","date")]};case repository.apiData.region.prefix:return{Sorting:{Id:"asc"},Columns:[addColumn(1,"web-region-Id","Region","Id","string"),addColumn(2,"web-region-updateDate","Oppdatert dato","UpdatedDate","date")]};case repository.apiData.equipmentOperatingHours.prefix:return{Sorting:{ReadDate:"desc"},Columns:[addColumn(1,"web-equipmentOperatingHours-equipment-Id","Anleggs id","Equipment.Id","string"),addColumn(1,"web-equipmentOperatingHours-equipment-Id","Anleggs beskrivelse","Equipment.Description","string"),addColumn(1,"web-equipmentOperatingHours-equipmentOperatingHourType-Id","Id","EquipmentOperatingHourType.Id","string"),addColumn(2,"web-equipmentOperatingHours-Value","Verdi","Value","double"),addColumn(2,"web-equipmentOperatingHours-ReadDate","Avlest dato","ReadDate","date")]};case repository.apiData.equipmentOperatingHourType.prefix:return{Sorting:{Id:"asc"},Columns:[addColumn(1,"web-equipmentOperatingHourType-Id","Id","Id","string"),addColumn(2,"web-equipmentOperatingHourType-updateDate","Oppdatert dato","UpdatedDate","date")]};case repository.apiData.customerGroup.prefix:return{Sorting:{Id:"asc"},Columns:[addColumn(1,"web-customerGroup-Id","Kundegruppe","Id","string"),addColumn(2,"web-customerGroup-updateDate","Oppdatert dato","UpdatedDate","date")]};case repository.apiData.customerCategory.prefix:return{Sorting:{Id:"asc"},Columns:[addColumn(1,"web-customerCategory-Id","Kategori","Id","string"),addColumn(2,"web-customerCategory-updateDate","Oppdatert dato","UpdatedDate","date")]};case repository.apiData.contractCategory.prefix:return{Sorting:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-contractCategory-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-contractCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"},{Position:3,Title:translationService.translate("web-contractCategory-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:4,Title:translationService.translate("web-contractCategory-ReferencedTemplateNames","Refererte maler"),Property:"ReferencedTemplateNames",PropertyType:"string"}]};case repository.apiData.customerLineOfBusiness.prefix:return{Sorting:{Id:"asc"},Columns:[addColumn(1,"web-customerLineOfBusiness-Id","Kategori","Id","string"),addColumn(2,"web-customerLineOfBusiness-updateDate","Oppdatert dato","UpdatedDate","date")]};case repository.apiData.sparePart.prefix:return{Sorting:{CreationDate:"asc"},Columns:[addColumn(1,"web-ComponentXSupplier-PartNumber","Delenummer","ComponentXSupplier.PartNumber","string"),addColumn(2,"web-Component-Id","Id","Component.Id","string"),addColumn(3,"web-Component-Description","Navn","Component.Description","string"),addColumn(4,"web-ComponentXSupplier-Manufacturer","Fabrikat","ComponentXSupplier.Manufacturer","string"),addColumn(5,"web-sparePart-Inventory","Beholdning","Inventory","number"),addColumn(6,"web-sparePart-Location","Plassering","Location","string"),addColumn(7,"web-Supplier-SupplierName","Leverandørnavn","ComponentXSupplier.Supplier.Description","string")]};case repository.apiData.mobileMenuProfile.prefix:return{Sorting:{Id:"desc"},Columns:[addColumn(1,"web-mobileMenuProfile-Id","Id","Id","string"),addColumn(2,"web-mobileMenuProfile-Description","Beskrivelse","Description","string")]};case repository.apiData.sparePartCounting.prefix:return{Sorting:{Id:"desc"},Columns:[addColumn(1,"web-sparePartCounting-Id","Id","Id","string"),addColumn(2,"web-sparePartCounting-Description","Beskrivelse","Description","string"),addColumn(3,"web-sparePartCounting-StartDate","Start dato","StartDate","date"),addColumn(4,"web-sparePartCounting-EndDate","Fullført dato","EndDate","datetime")]};case repository.apiData.sparePartCountingItem.prefix:return{Sorting:{CountedDate:"desc"},Filter:{PropertyFilter:[{Property:"QuantityDeviation",Operator:"<>",Value:"0"}]},Columns:[addColumn(1,"web-sparePartCountingItem-SparepartId","Id","SparePart.Component.Id","string"),addColumn(2,"web-sparePartCountingItem-SparepartDescription","Beskrivelse","SparePart.Component.Description","string"),addColumn(3,"web-sparePartCountingItem-CountedDate","Telledato","CountedDate","datetime"),addColumn(4,"web-sparePartCountingItem-UserCountedBy","Talt av","UserCountedBy.RealName","string"),addColumn(5,"web-sparePartCountingItem-RecordQuantity","Forventet antall","RecordQuantity","string"),addColumn(5,"web-sparePartCountingItem-PhysicalQuantity","Talt antall","PhysicalQuantity","string"),addColumn(5,"web-sparePartCountingItem-QuantityDeviation","Avvik","QuantityDeviation","string")]};case repository.apiData.sparePartWithdrawal.prefix:return{Sorting:{CreationDate:"desc"},Columns:[addColumn(1,"web-sparePart-component-Id","Komponent Id","SparePart.Component.Id","string"),addColumn(2,"web-sparePart-component-Description","Komponentbeskrivelse","SparePart.Component.Description","string"),addColumn(3,"web-sparePartWithdrawal-equipment-Id","Anlegg Id","Equipment.Id","string"),addColumn(4,"web-sparePartWithdrawal-equipment-Description","Anleggs navn","Equipment.Description","string"),addColumn(5,"web-sparePartWithdrawal-workorder-Id","AO nr","WorkOrderXSparePart.WorkOrder.Id","string"),addColumn(6,"web-sparePartWithdrawal-Quantity","Antall tatt ut","Quantity","number"),addColumn(7,"web-sparePartWithdrawal-Price","Pris","WorkOrderXSparePart.Price","number"),addColumn(8,"web-sparePartWithdrawal-WithdrawalDate","Uttaks dato","WithdrawalDate","date"),addColumn(9,"web-sparePartWithdrawal-User1","Tatt ut av","UserCreatedBy.RealName","string")]};case repository.apiData.cause.prefix:return{Sorting:{Id:"desc"},Columns:[addColumn(1,"web-cause-Id","Årsak","Id","string"),addColumn(2,"web-cause-creationDate","Opprettet dato","CreationDate","date")]};case repository.apiData.bimFile.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-bimFile-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-bimFile-Description","Beskrivelse"),Property:"Description",PropertyType:"string"}]};case repository.apiData.operationalMessage.prefix:return{Sorting:{DueDate:"asc"},Columns:[{Position:1,Title:translationService.translate("web-operationalMessage-type","Type"),Property:"Type",PropertyType:"enum.OperationalMessageType"},{Position:2,Title:translationService.translate("web-operationalMessage-building-id","Byggnr"),Property:"Building.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-operationalMessage-building-description","Byggnavn"),Property:"Building.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-operationalMessage-equipment-id","Anleggsnr"),Property:"Equipment.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-operationalMessage-equipment-description","Anleggsnavn"),Property:"Equipment.Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-operationalMessage-startDate","Startdato"),Property:"StartDate",PropertyType:"date"},{Position:7,Title:translationService.translate("web-operationalMessage-dueDate","Fristdato"),Property:"DueDate",PropertyType:"date"},{Position:8,Title:translationService.translate("web-operationalMessage-workorderId","AO Id"),Property:"WorkOrder.Id",PropertyType:"number"},{Position:9,Title:translationService.translate("web-operationalMessage-message","Melding"),Property:"Message",PropertyType:"string"},{Position:10,Title:translationService.translate("web-operationalMessage-status","Status"),Property:"Status",PropertyType:"enum.OperationalMessageStatus"}]};case repository.apiData.apiClient.prefix:return{Sorting:{Id:"asc"},Columns:[addColumn(1,"web-apiClient-Id","Id","Id","string"),addColumn(2,"web-apiClient-Description","Navn","Description","string"),addColumn(3,"web-apiClient-RefreshTokenLifetime","Utløpstid refresh token (minutt)","RefreshTokenLifetime","number"),addColumn(4,"web-apiClient-AccessTokenLifetime","Utløpstid access token (minutt)","AccessTokenLifetime","number"),addColumn(5,"web-apiClient-updatedDate","Oppdatert dato","UpdatedDate","date")]};case repository.apiData.apiRequestLog.prefix:return{Sorting:{CreationDate:"desc"},Columns:[addColumn(1,"web-apiRequestLog-creationDate","Opprettet dato","CreationDate","date"),addColumn(2,"web-apiRequestLog-user-realName","Opprettet av","UserCreatedBy.Username","string"),addColumn(3,"web-apiRequestLog-responseStatus","Respons status","ResponseStatus","number"),addColumn(4,"web-apiRequestLog-request","Forespørsel","Request","string"),addColumn(5,"web-apiRequestLog-response","Svar","Response","string")]};case repository.apiData.changeSet.prefix:return{Sorting:{CreationDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-changeSet-EntityType","Entitet"),Property:"EntityType",PropertyType:"enum.prefix"},{Position:2,Title:translationService.translate("web-changeSet-UserCreatedBy","Opprettet av"),Property:"UserCreatedBy.RealName",PropertyType:"string"},{Position:3,Title:translationService.translate("web-changeSet-CreationDate","Opprettet dato"),Property:"CreationDate",PropertyType:"date"},{Position:4,Title:translationService.translate("web-changeSet-Status","Status"),Property:"Status",PropertyType:"enum.ChangeSetStatus"}]};case repository.apiData.scheduledJob.prefix:return{Sorting:{Type:"asc"},Columns:[addColumn(1,"web-scheduledJob-Description","Navn","Description","string"),addColumn(2,"web-scheduledJob-JobType","Type","Type","enum.ScheduledJobType"),addColumn(3,"web-scheduledJob-RunType","Kjøretype","RunType","enum.ScheduledJobRunType"),addColumn(4,"web-scheduledJob-ScheduledJobExecutionDatetime","Siste kjøring","ScheduledJobExecution.UpdatedDate","date"),addColumn(5,"web-scheduledJob-ExecutionStatus","Siste status","ExecutionStatus","enum.ScheduledJobExecutionStatus")]};case repository.apiData.scheduledJobExecution.prefix:return{Sorting:{JobId:"asc"},Columns:[addColumn(1,"web-scheduledJobExecution-JobId","Jobid","JobId","string"),addColumn(2,"web-scheduledJob-Description","Navn","ScheduledJob.Description","string"),addColumn(3,"web-scheduledJobExecution-CreationDate","Opprettet dato","CreationDate","date"),addColumn(4,"web-scheduledJobExecution-UpdatedDate","Oppdatert dato","UpdatedDate","date"),addColumn(5,"web-scheduledJobExecution-Status","Status","Status","enum.ScheduledJobExecutionResult"),addColumn(6,"web-scheduledJobExecution-UserCreatedBy","Opprettet av","UserCreatedBy.RealName","string")]};case repository.apiData.emailTemplate.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-emailTemplate-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-emailTemplate-EntityType","Entitet"),Property:"EntityType",PropertyType:"enum.prefix"},{Position:3,Title:translationService.translate("web-emailTemplate-IsDefault","Standard"),Property:"IsDefault",PropertyType:"bool"},{Position:4,Title:translationService.translate("web-emailTemplate-CreationDate","Opprettet dato"),Property:"CreationDate",PropertyType:"date"}]};case repository.apiData.project.prefix:var projectColumns=[];return projectColumns=contextId===planiaUtils.contextIds.projectTemplate?[{Position:1,Title:translationService.translate("web-project-Id","Prosjektnummer"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-project-Description","Prosjektnavn"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-project-ManagerPerson-FirstName","Prosjektleder Fornavn"),Property:"ManagerPerson.FirstName",PropertyType:"string"},{Position:4,Title:translationService.translate("web-project-ManagerPerson-LastName","Prosjektleder Etternavn"),Property:"ManagerPerson.LastName",PropertyType:"string"},{Position:5,Title:translationService.translate("web-project-CreationDate","Opprettet dato"),Property:"CreationDate",PropertyType:"date"}]:[{Position:1,Title:translationService.translate("web-project-Id","Prosjektnummer"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-project-Description","Prosjektnavn"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-project-building-id","Byggnr"),Property:"Building.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-project-building-description","Byggnavn"),Property:"Building.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-project-phase","Fase"),Property:"ProjectStatus.ProjectPhase.Id",PropertyType:"string"},{Position:6,Title:translationService.translate("web-project-status","Status"),Property:"ProjectStatus.Id",PropertyType:"string"},{Position:7,Title:translationService.translate("web-project-status-stage","Stage"),Property:"ProjectStatus.Stage",PropertyType:"string"},{Position:8,Title:translationService.translate("web-project-ManagerPerson-FirstName","Prosjektleder Fornavn"),Property:"ManagerPerson.FirstName",PropertyType:"string"},{Position:9,Title:translationService.translate("web-project-ManagerPerson-LastName","Prosjektleder Etternavn"),Property:"ManagerPerson.LastName",PropertyType:"string"}],{Sorting:{Id:"desc"},Columns:projectColumns};case repository.apiData.report.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-report-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-report-Type","Type"),Property:"ReportType",PropertyType:"enum.ReportType"},{Position:3,Title:translationService.translate("web-report-Name","Navn"),Property:"Name",PropertyType:"string"},{Position:4,Title:translationService.translate("web-report-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-report-IsDeactivated","Deaktivert"),Property:"IsDeactivated",PropertyType:"bool"}]};case repository.apiData.entityLink.prefix:return{Sorting:{EntityType:"asc",IndexPosition:"asc"},Columns:[{Position:1,Title:translationService.translate("web-entityLink-EntityType","Entitetstype"),Property:"EntityType",PropertyType:"enum.prefix"},{Position:2,Title:translationService.translate("web-entityLink-IndexPosition","Rekkefølge"),Property:"IndexPosition",PropertyType:"number"},{Position:3,Title:translationService.translate("web-entityLink-name","Navn"),Property:"Name",PropertyType:"string"},{Position:4,Title:translationService.translate("web-entityLink-url","Url"),Property:"Url",PropertyType:"string"}]};case repository.apiData.entityTask.prefix:return{Sorting:{UpdatedDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-entityTask-updatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"datetime"},{Position:2,Title:translationService.translate("web-entityTask-id","Id"),Property:"Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-entityTask-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-entityTask-status","Status"),Property:"Status",PropertyType:"enum.EntityTaskStatus"},{Position:5,Title:translationService.translate("web-entityTask-url","Url"),Property:"Url",PropertyType:"string"},{Position:6,Title:translationService.translate("web-entityTask-userName","Brukernavn"),Property:"UserUpdatedBy.Username",PropertyType:"string"}]};case repository.apiData.entityCounter.prefix:return{Sorting:{EntityType:"desc"},Columns:[{Position:1,Title:translationService.translate("web-entityCounter-entityType","Register"),Property:"EntityType",PropertyType:"enum.Prefix"},{Position:2,Title:translationService.translate("web-entityCounter-fieldName","Felt"),Property:"FieldName",PropertyType:"string"},{Position:3,Title:translationService.translate("web-entityCounter-value","Verdi"),Property:"Value",PropertyType:"number"},{Position:4,Title:translationService.translate("web-entityCounter-clientId","Klient Id"),Property:"LinkedDataOwner.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-entityCounter-clientDescription","Klient Beskrivelse"),Property:"LinkedDataOwner.Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-entityCounter-CreationDate","Opprettet dato"),Property:"CreationDate",PropertyType:"datetime"}]};case repository.apiData.integrationData.prefix:return{Sorting:{CreationDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-integrationData-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-integrationData-JobId","Job id"),Property:"JobId",PropertyType:"enum.IntegrationDataJobId"},{Position:3,Title:translationService.translate("web-IntegrationData-Status","Status"),Property:"Status",PropertyType:"enum.IntegrationDataStatus"},{Position:4,Title:translationService.translate("web-IntegrationData-FileName","Filnavn"),Property:"FileName",PropertyType:"string"},{Position:5,Title:translationService.translate("web-integrationdata-message","Melding"),Property:"Message",PropertyType:"string"},{Position:6,Title:translationService.translate("web-integrationData-ProcessedDate","Prosessert dato"),Property:"ProcessedDate",PropertyType:"datetime"},{Position:7,Title:translationService.translate("web-integrationData-CreationDate","Opprettet dato"),Property:"CreationDate",PropertyType:"datetime"}]};case repository.apiData.webUserToken.prefix:return{Sorting:{CreationDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-webUserToken-User-RealName","Navn"),Property:"User.RealName",PropertyType:"string"},{Position:2,Title:translationService.translate("web-webUserToken-User-Username","Brukernavn"),Property:"User.Username",PropertyType:"string"},{Position:3,Title:translationService.translate("web-webUserToken-ApiClient-ID","Klient ID"),Property:"ApiClient.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-webUserToken-CreationDate","Første innlogging"),Property:"CreationDate",PropertyType:"date"},{Position:5,Title:translationService.translate("web-webUserToken-RefreshTokenExpirationDate","Utgår"),Property:"RefreshTokenExpirationDate",PropertyType:"datetime"},{Position:6,Title:translationService.translate("web-webUserToken-LogoutReason","Kastet ut grunnlag"),Property:"LogoutReason",PropertyType:"enum.LogoutReason",Filter:[{Property:"LogoutReason",Operator:"<",Value:1}]},{Position:7,Title:translationService.translate("web-webUserToken-Fingerprint","Fingeravtrykk"),Property:"Fingerprint",PropertyType:"string"}]};case repository.apiData.workOrderXResourceGroup.prefix:return{Sorting:{RegisteredDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-workOrderXResourceGroup-RegisteredDate","Dato registrert"),Property:"RegisteredDate",PropertyType:"date"},{Position:2,Title:translationService.translate("web-workOrderXResourceGroup-RealTime","Registrert tid"),Property:"RealTime",PropertyType:"double"},{Position:3,Title:translationService.translate("web-workOrderXResourceGroup-EstimatedTime","Estimert tid"),Property:"EstimatedTime",PropertyType:"double"},{Position:4,Title:translationService.translate("web-workOrderXResourceGroup-workOrder-Id","AO Id"),Property:"WorkOrder.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-workOrderXResourceGroup-workOrder-Description","AO Beskrivelse"),Property:"WorkOrder.Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-workOrderXResourceGroup-project-Id","Prosjekt Id"),Property:"WorkOrder.Project.Id",PropertyType:"string"},{Position:7,Title:translationService.translate("web-workOrderXResourceGroup-project-Description","Prosjektbeskrivelse"),Property:"WorkOrder.Project.Description",PropertyType:"string"},{Position:8,Title:translationService.translate("web-workOrderXResourceGroup-ResourceGroup-Id","Ressurs Id"),Property:"ResourceGroup.Id",PropertyType:"string"},{Position:9,Title:translationService.translate("web-workOrderXResourceGroup-ResourceGroup-Description","Ressurs Beskrivelse"),Property:"ResourceGroup.Description",PropertyType:"string"},{Position:10,Title:translationService.translate("web-workOrderXResourceGroup-hourType.Id","Timetype Id"),Property:"HourType.Id",PropertyType:"string"},{Position:11,Title:translationService.translate("web-workOrderXResourceGroup-hourType.Description","Timetype Beskrivelse"),Property:"HourType.Description",PropertyType:"string"}]};case repository.apiData.dataImport.prefix:return{Sorting:{UpdatedDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-dataImport-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-dataImport-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-dataImport-EntityType","Entitet"),Property:"EntityType",PropertyType:"enum.PreFix"},{Position:4,Title:translationService.translate("web-dataImport-Status","Status"),Property:"Status",PropertyType:"enum.DataImportStatus"},{Position:5,Title:translationService.translate("web-dataImport-User","Navn"),Property:"UserUpdatedBy.RealName",PropertyType:"string"},{Position:6,Title:translationService.translate("web-dataImport-StatusMessage","Statusmelding"),Property:"StatusMessage",PropertyType:"string"},{Position:7,Title:translationService.translate("web-dataImport-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.referenceType.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-referenceType-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-referenceType-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-referenceType-EntityType","Entitet"),Property:"EntityType",PropertyType:"enum.PreFix"},{Position:4,Title:translationService.translate("web-referenceType-Context","Kontekst"),Property:"Context",PropertyType:"enum.ReferenceTypeContext"},{Position:5,Title:translationService.translate("web-referenceType-IsHierarchy","Hierarki"),Property:"IsHierarchy",PropertyType:"bool"}]};case repository.apiData.userProfile.prefix:return{Sorting:{"LinkedDataOwner.Id":"asc"},Columns:[{Position:1,Title:translationService.translate("web-userProfile-user-realName","Bruker"),Property:"User.RealName",PropertyType:"string"},{Position:2,Title:translationService.translate("web-userProfile-entityPermissionProfile-Id","Rettighetsprofil"),Property:"EntityPermissionProfile.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-userProfile-linkedDataOwner-Id","Klient ID"),Property:"LinkedDataOwner.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-userProfile-linkedDataOwner-Id","Klient beskrivelse"),Property:"LinkedDataOwner.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-userProfile-updatedDate","Oppdatert"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.alarm.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-alarm-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-alarm-entityType","Register"),Property:"EntityType",PropertyType:"enum.Prefix"},{Position:3,Title:translationService.translate("web-alarm-action","Aksjonstype"),Property:"Action",PropertyType:"string"},{Position:4,Title:translationService.translate("web-alarm-isEnabled","Aktiv"),Property:"IsEnabled",PropertyType:"bool"},{Position:5,Title:translationService.translate("web-alarm-updatedDate","Oppdatert"),Property:"UpdatedDate",PropertyType:"date"}]};case repository.apiData.doorKeySystem.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-doorKeySystem-accessSystemType","Type adgangssystem"),Property:"AccessSystemType",PropertyType:"enum.DoorKeyAccessSystemType"},{Position:2,Title:translationService.translate("web-doorKeySystem-id","Id"),Property:"Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-doorKeySystem-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-doorKeySystem-manufacturer","Fabrikat"),Property:"Manufacturer",PropertyType:"string"},{Position:5,Title:translationService.translate("web-doorKeySystem-estate-id","Eiendom ID"),Property:"Estate.Id",PropertyType:"string"}]};case repository.apiData.doorKey.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-doorKey-type","Type"),Property:"Type",PropertyType:"enum.DoorKeyType"},{Position:2,Title:translationService.translate("web-doorKey-id","Id"),Property:"Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-doorKey-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-doorKey-inStock","Antall på lager"),Property:"InStock",PropertyType:"number"},{Position:5,Title:translationService.translate("web-doorKey-doorKeySystem-id","System Id"),Property:"DoorKeySystem.Id",PropertyType:"string"},{Position:6,Title:translationService.translate("web-doorKey-doorKeySystem-description","SystemNavn"),Property:"DoorKeySystem.Description",PropertyType:"string"}]};case repository.apiData.doorLock.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-doorLock-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-doorLock-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-doorLock-doorNr","Dør"),Property:"DoorNr",PropertyType:"string"},{Position:4,Title:translationService.translate("web-doorLock-cylinderType","CylinderType"),Property:"CylinderType.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-doorLock-doorKeySystem-AccessSystemType","Type Adgangssystem"),Property:"DoorKeySystem.AccessSystemType",PropertyType:"enum.DoorKeyAccessSystemType"},{Position:6,Title:translationService.translate("web-doorLock-doorKeySystem-Id","System Id"),Property:"DoorKeySystem.Id",PropertyType:"string"},{Position:7,Title:translationService.translate("web-doorLock-doorKeySystem-description","Systemnavn"),Property:"DoorKeySystem.Description",PropertyType:"string"},{Position:8,Title:translationService.translate("web-doorLock-doorKeySystem-manufacturer","Fabrikat"),Property:"DoorKeySystem.Manufacturer",PropertyType:"string"},{Position:9,Title:translationService.translate("web-doorLock-doorKeySystem-estate-id","Eiendom ID"),Property:"DoorKeySystem.Estate.Id",PropertyType:"string"}]};case repository.apiData.doorKeyXUser.prefix:return{Sorting:{"DoorKey.DoorKeySystem.Description":"asc"},Columns:[{Position:1,Title:translationService.translate("web-doorKeySystem-description"),Property:"DoorKey.DoorKeySystem.Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-doorKey-id"),Property:"DoorKey.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-doorKey-description"),Property:"DoorKey.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-doorKeyXUser-id"),Property:"Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-doorKeyXUser-description"),Property:"Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-doorKeyXUser-quantity"),Property:"Quantity",PropertyType:"number"},{Position:7,Title:translationService.translate("web-doorKeyXUser-note"),Property:"Note",PropertyType:"number"}]};case repository.apiData.doorLockXArea.prefix:return{Sorting:{"DoorLock.DoorKeySystem.Description":"asc"},Columns:[{Position:1,Title:translationService.translate("web-doorKeySystem-description"),Property:"DoorLock.DoorKeySystem.Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-doorLock-id"),Property:"DoorLock.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-doorLock-description"),Property:"DoorLock.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-cylinderType-id"),Property:"DoorLock.CylinderType.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-area-id"),Property:"Area.Id",PropertyType:"string"},{Position:6, Title:translationService.translate("web-area-description"),Property:"Area.Description",PropertyType:"string"},{Position:7,Title:translationService.translate("web-areaCategory-description"),Property:"Area.AreaCategory.Description",PropertyType:"string"},{Position:8,Title:translationService.translate("web-building-id"),Property:"Area.Building.Id",PropertyType:"string"},{Position:9,Title:translationService.translate("web-building-description"),Property:"Area.Building.Description",PropertyType:"string"}]};case repository.apiData.doorKeyXDoorLock.prefix:return{Sorting:{"DoorKey.DoorKeySystem.Description":"asc"},Columns:[{Position:1,Title:translationService.translate("web-doorKeySystem-description"),Property:"DoorKey.DoorKeySystem.Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-doorKey-id"),Property:"DoorKey.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-doorKey-description"),Property:"DoorKey.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-doorLock-id"),Property:"DoorLock.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-doorLock-description"),Property:"DoorLock.Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-doorLock-doorNr"),Property:"DoorLock.DoorNr",PropertyType:"string"},{Position:7,Title:translationService.translate("web-cylinderType-id"),Property:"DoorLock.CylinderType.Id",PropertyType:"string"}]};case repository.apiData.doorKeyTransaction.prefix:return{Sorting:{"Supply.DoorKey.DoorKeySystem.Description":"asc"},Columns:[{Position:1,Title:translationService.translate("web-doorKeySystem-description"),Property:"Supply.DoorKey.DoorKeySystem.Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-doorKeyTransaction-supplyDate"),Property:"SupplyDate",PropertyType:"date"},{Position:3,Title:translationService.translate("web-doorKeyXUser-id"),Property:"Supply.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-doorKeyXUser-description"),Property:"Supply.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-doorKeyTransaction-status"),Property:"Status",PropertyType:"enum.DoorKeyTransactionStatus"},{Position:6,Title:translationService.translate("web-doorKeyTransaction-quantity"),Property:"Quantity",PropertyType:"number"},{Position:7,Title:translationService.translate("web-doorKeyTransaction-uniqueKeyId"),Property:"UniqueKeyId",PropertyType:"string"},{Position:8,Title:translationService.translate("web-doorKeyTransaction-note"),Property:"Note",PropertyType:"string"}]};case repository.apiData.bcfProject.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-bcfProject-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-bcfProject-name"),Property:"Name",PropertyType:"string"},{Position:3,Title:translationService.translate("web-BcfProject-estate-id","Eiendom"),Property:"Estate.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-bcfProject-status"),Property:"Status",PropertyType:"enum.BcfProjectStatus"},{Position:5,Title:translationService.translate("web-bcfProject-exportedDate"),Property:"ExportedDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-bcfProject-exportedByUser"),Property:"ExportedByUser.RealName",PropertyType:"string"}]};case repository.apiData.workingDaysOff.prefix:return{Sorting:{StartDate:"asc"},Columns:[{Position:1,Title:translationService.translate("web-workingDaysOff-name"),Property:"Name",PropertyType:"string"},{Position:2,Title:translationService.translate("web-workingDaysOff-startDate"),Property:"StartDate",PropertyType:"date"},{Position:3,Title:translationService.translate("web-workingDaysOff-endDate"),Property:"EndDate",PropertyType:"date"},{Position:4,Title:translationService.translate("web-workingDaysOff-countryCode"),Property:"CountryCode",PropertyType:"string"},{Position:5,Title:translationService.translate("web-workingDaysOff-explanatoryText"),Property:"ExplanatoryText",PropertyType:"string"}]};case repository.apiData.userXExternalLogin.prefix:return{Sorting:{CreationDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-externalLoginProvider-name"),Property:"ExternalLoginProvider.Name",PropertyType:"string"},{Position:2,Title:translationService.translate("web-user-userName"),Property:"User.Username",PropertyType:"date"},{Position:3,Title:translationService.translate("web-user-realName"),Property:"User.RealName",PropertyType:"date"},{Position:4,Title:translationService.translate("web-userXExternalLogin-creationDate"),Property:"CreationDate",PropertyType:"date"}]};case repository.apiData.userXUserNotification.prefix:return{Sorting:{CreationDate:"desc"},Columns:[{Position:1,Title:translationService.translate("web-userNotification-entityType"),Property:"UserNotification.EntityType",PropertyType:"enum.Prefix"},{Position:2,Title:translationService.translate("web-userNotification-type"),Property:"UserNotification.Type",PropertyType:"enum.UserNotificationType"},{Position:3,Title:translationService.translate("web-userNotification-id"),Property:"UserNotification.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-userNotification-description"),Property:"UserNotification.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-userXUserNotification-creationDate"),Property:"CreationDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-userXUserNotification-readDate"),Property:"ReadDate",PropertyType:"date"},{Position:7,Title:translationService.translate("web-user-userName"),Property:"User.Username",PropertyType:"string"},{Position:8,Title:translationService.translate("web-userNotification-handledDate"),Property:"UserNotification.HandledDate",PropertyType:"date"}]};default:return{Id:"Plania FEIL",Sorting:{Guid:"asc"},EntityType:"Undefined",Columns:[{Position:1,Title:"PLANIA ERROR",Property:"Guid",PropertyType:"string"}]}}};return service.getStandardView=function(prefix,filters,contextId){var standardView=getStandardViewInternal(prefix,filters,contextId);return angular.isUndefined(standardView.Id)&&(standardView.Id="Plania standard"),angular.isUndefined(standardView.IsPublicView)&&(standardView.IsPublicView=!0),angular.isUndefined(standardView.IsPlaniaStandard)&&(standardView.IsPlaniaStandard=!0),angular.isUndefined(standardView.EntityType)&&(standardView.EntityType=prefix),angular.isUndefined(standardView.ContextId)&&(standardView.ContextId=contextId),standardView},service}])}(),function(){angular.module("Plania").service("messageService",["$resource",function($resource){var ms={};return ms.getMessage=function(img,user,text){return $resource("data/messages-notifications.json").get({img:img,user:user,text:text})},ms}])}(),function(){angular.module("Plania").service("scrollService",function(){var ss={};return ss.malihuScroll=function(selector,theme,mousewheelaxis){$(selector).mCustomScrollbar({autoExpandScrollbar:!0,theme:theme,scrollInertia:100,axis:"yx",mouseWheel:{enable:!0,axis:mousewheelaxis,preventDefault:!0}})},ss})}(),function(){angular.module("Plania").service("growlService",function(){var gs={};return gs.growl=function(message,type,options){options||(options={}),options.enter||(options.enter="animated bounceIn"),options.exit||(options.exit="animated bounceOut"),$.growl({message:message},{type:type,allow_dismiss:!0,label:"Cancel",className:"btn-xs btn-inverse",placement:{from:"top",align:"right"},showProgressbar:!0,z_index:2e3,delay:"danger"===type?1e4:3e3,animate:{enter:options.enter,exit:options.exit},offset:{x:20,y:85}})},gs})}(),function(){angular.module("Plania").factory("MenuService",["Repository","$state","CommonService","states","$localStorage",function(repository,$state,commonService,states,$localStorage){var service={};service.getShortcuts=function(){return repository.getShortcuts()},service.isDisabled=function(webMenu){return!(!webMenu.state||!webMenu.isBuildingDependent)&&commonService.disableWebMenuNavigation()},service.getParams=function(webMenu){if(service.isDisabled(webMenu)||!webMenu.state)return null;var params={menuGuid:webMenu.guid};return webMenu.isBuildingDependent&&"building.edit"===webMenu.state&&(params.guid=commonService.getFilterData().selectedBuilding.Guid),params},service.cleanupBeforeNavigation=function(webMenu){try{var splittedState=webMenu.state.split(".");if(splittedState[1]&&"list"===splittedState[1]){var state=_.find(states.list,function(state){return state.name===webMenu.state});if(state&&state.params&&state.params.entityData&&state.params.entityData.prefix){var prefix=state.params.entityData.prefix;$localStorage.listParams&&$localStorage.listParams[prefix]&&delete $localStorage.listParams[prefix].page}}}catch(ex){}},service.navigate=function(webMenu){var params=service.getParams(webMenu);return!!params&&(service.cleanupBeforeNavigation(webMenu),$state.go(webMenu.state,params,{reload:!0,inherit:!1}),!0)};var isModifiedEvent=function(event){return!!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)},shouldNavigateInternally=function(event){var target=event.target.target;return!(0!==event.button||target&&"_self"!==target||isModifiedEvent(event))};return service.navigateFromLink=function(event,webMenu){return shouldNavigateInternally(event)&&service.navigate(webMenu)?(event.preventDefault(),!0):(service.cleanupBeforeNavigation(),!1)},service.getHref=function(webMenu){var params=service.getParams(webMenu);return params?$state.href(webMenu.state,params,{reload:!0,inherit:!1}):null},service}])}(),function(){function moduleService($localStorage,$rootScope){var moduleData={isLoaded:!1},moduleFlag={None:0,Core:1,Activity:2,Budget:4,SparePart:8,Document:16,Energy:32,Area:64,Cleaning:128,Key:256,Rent:512,Invoice:1024,InternalRent:2048,DutyLog:4096,Housing:8192,Alarm:16384,Deviation:32768,Mobile:65536,Map:1<<17,CleaningWeb:1<<18,FireManual:1<<19,HSEManual:1<<20,ElectroManual:1<<21,DataAcquisition:1<<22,Booking:1<<23,EntityComment:1<<26,InventoryControl:1<<27,ExtendedConditionControl:1<<28,ControlList:1<<29,Api:1<<30,ProjectManagement:Math.pow(2,31),EntityLink:Math.pow(2,33),Sms:Math.pow(2,34),IFCBimsyncHosting:Math.pow(2,35),DataImport:Math.pow(2,36),Elhub:Math.pow(2,37),Brand:Math.pow(2,38)},moduleIcons={None:"fa-cube",Core:"fa-power-off",Activity:"fa-tasks",Budget:"fa-money-bill-alt",SparePart:"fa-plug",Document:"fa-file",Energy:"fa-bolt",Area:"fa-layer-group",Cleaning:"fa-broom",Key:"fa-key",Rent:"fa-building",Invoice:"fa-file-invoice-dollar",InternalRent:"fa-store-alt",Housing:"fa-home",DutyLog:"fa-shield-alt",Alarm:"fa-bell",Deviation:"fa-exclamation-triangle",Mobile:"fa-mobile-alt",Map:"fa-map",CleaningWeb:"fa-vacuum",FireManual:"fa-fire-extinguisher",HSEManual:"fa-hospital",ElectroManual:"fa-battery-half",DataAcquisition:"fa-download",Booking:"fa-hotel",EntityComment:"fa-comments",InventoryControl:"fa-archive",ExtendedConditionControl:"fa-tasks",ControlList:"fa-list-ul",Api:"fa-share-alt",ProjectManagement:"fa-chart-waterfall",EntityLink:"fa-link",Sms:"fa-lock",IFCBimsyncHosting:"fa-cube",DataImport:"fa-upload",Elhub:"fa-plug",Brand:"fa-palette"},bitwiseAnd=function(a,b){if(b<=2147483648)return a&b;var w=4294967296;return(a/w&b/w)*w+(a%w&b%w)};return{moduleFlags:moduleFlag,resetModules:function(){moduleData={isLoaded:!1},delete $localStorage.moduleData},setModules:function(stringModules){var modules=stringModules.split(", "),mod=0,stringRepresentation="";modules.forEach(function(module){stringRepresentation+=", "+module,mod+=moduleFlag[module]}),moduleData.modules=mod,moduleData.stringModules=stringRepresentation,$localStorage.moduleData=moduleData,moduleData.isLoaded=!0,$rootScope.$broadcast($rootScope.events.updatedModuleData)},hasModule:function(module){if(!moduleData.isLoaded){var storageModuleData=angular.fromJson($localStorage.moduleData);storageModuleData&&(moduleData=storageModuleData),moduleData.isLoaded=!0}return!!bitwiseAnd(moduleData.modules,module)},getModuleIcon:function(moduleName){return moduleIcons[moduleName]},getModuleData:function(){return angular.copy(moduleData)}}}angular.module("Plania").factory("ModuleService",["$localStorage","$rootScope",moduleService])}(),function(){function persistentDataService($localStorage){return{getPersistedData:function(key){if($localStorage.persistedData)return $localStorage.persistedData[key]},setPersistedData:function(key,data){$localStorage.persistedData||($localStorage.persistedData={}),$localStorage.persistedData[key]=data},clearPersistedData:function(key){key?delete $localStorage.persistedData[key]:delete $localStorage.persistedData}}}angular.module("Plania").factory("PersistentDataService",["$localStorage",persistentDataService])}(),function(){function reactService(){var service={};return service.uniqueReactIds=[],service.generateSuffix=function(){return""+Math.random().toString(36).substr(2,9)},service.generateId=function(){for(var suffix=service.generateSuffix(),id="";;)if(id="react-migration-"+suffix,!service.uniqueReactIds.includes(id)){service.uniqueReactIds.push(id);break}return id},service.removeId=function(id){var index=service.uniqueReactIds.indexOf(id);-1!==index&&service.uniqueReactIds.splice(index,1)},service}angular.module("Plania").factory("ReactService",reactService)}();!function(){function regisredFieldService(translationService,repository,$q){var service={},registeredFields={};return service.getRegisteredField=function(prefix,forceApiLoad){var deferred=$q.defer();return registeredFields[prefix]&&!forceApiLoad?deferred.resolve(registeredFields[prefix]):repository.getSingle(repository.apiData.registeredField.url,prefix).then(function(result){registeredFields[prefix]=result,deferred.resolve(registeredFields[prefix])},function(error){deferred.reject("Kunne ikke finne definering av felter for: "+prefix)}),deferred.promise},service.getFieldRule=function(prefix,column,forceApiLoad){var deferred=$q.defer();return service.getRegisteredField(prefix,forceApiLoad).then(function(result){var fieldrule=_.filter(result,{DomainFieldName:column})[0];fieldrule?deferred.resolve(fieldrule):deferred.reject("Kunne ikke finne fieldrule: "+prefix+"."+column)}),deferred.promise},service.getFieldRuleByEntityAndColumn=function(entityAndColumn){var deferred=$q.defer();if(!entityAndColumn)return $.Deferred().reject("Ugyldig input").promise();var splitByDot=entityAndColumn.split(".");return 2!==splitByDot.length?$.Deferred().reject("Kunne ikke finne fieldrule: "+entityAndColumn).promise():(this.getFieldRule(splitByDot[0],splitByDot[1]).then(function(fieldrule){return deferred.resolve(fieldrule)},function(error){return deferred.reject(error)}),deferred.promise)},service.getLocalRegisteredField=function(prefix,column){if(registeredFields||!registeredFields[prefix])return _.filter(registeredFields[prefix],{DomainFieldName:column})[0]},service}angular.module("Plania").factory("RegisteredFieldService",["TranslationService","Repository","$q",regisredFieldService])}(),function(){angular.module("Plania").factory("Repository",["genericRepository","$q","CommonService","ModuleService","authService","config","PersistentDataService","$location","$rootScope","growlService","apiData","MapService","ValidationService","$localStorage",function(genericRepository,$q,commonService,moduleService,authService,config,persistedDataService,$location,$rootScope,growlsService,apiData,mapService,validationService,$localStorage){var service={};service.commonService=commonService,service.persistedData=persistedDataService,service.moduleService=moduleService,service.authService=authService,service.location=$location,service.apiData=apiData,service.mapService=mapService,service.validationService=validationService;var getStringFromModelState=function(modelstate){var propertyName=Object.getOwnPropertyNames(modelstate);return propertyName?modelstate[propertyName][0]:""},getStringFromErrorObject=function(error){if(error&&"object"==typeof error){if(error.ModelState)return getStringFromModelState(error.ModelState);if(error.Data&&error.Data.ModelState)return getStringFromModelState(error.Data.ModelState);if(error.Message&&""!==error.Message)return error.Message;if(error.Data&&"string"==typeof error.Data)return error.Data;if(error.Data&&Array.isArray(error.Data))return error.Data;if(error.Data.Message&&"string"==typeof error.Data.Message)return error.Data.Message}return error},handleLoggedInOnAnotherDevice=function(status){authService.deleteLocalData();var storage=window.localStorage,d=(new Date).getTime(),fingerprint="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=(d+16*Math.random())%16|0;return d=Math.floor(d/16),("x"===c?r:3&r|8).toString(16)});storage.setItem("Fingerprint",fingerprint),config.fingerprint=fingerprint;var sessionStorage=window.sessionStorage;471===status?sessionStorage.setItem("logoutError","Du ble kastet ut av Plania av en administrator"):sessionStorage.setItem("logoutError","Du ble logget inn i en annen browser eller på en annen maskin, vennligst logg inn igjen"),location.reload()},getErrorMessageFromStatus=function(status,error){471!==status&&472!==status||handleLoggedInOnAnotherDevice(status);var message=getStringFromErrorObject(error);if("string"==typeof message&&message.length>0)return message;if(Array.isArray(message))return message;switch(status){case 401:return authService.getUserData().isAuthenticated?"Mangler tilgang":"Du må logge inn for å se denne informasjonen";case 404:return"Ingen data funnet";case 409:return"Konflikt i Api";default:return"Ukjent feil oppstod. Http status kode: "+status}},updateAccess=function(accessData){authService.updateUserAccess(accessData)};service.getLocale=function(){return $localStorage.locale},service.setLocale=function(newLocale){$localStorage.locale=newLocale||"nb-no"},service.getUrlParameters=function(separator){return separator||(separator="?"),separator+"dataOwner="+commonService.getFilterData().selectedDataOwner.Guid},service.getFilter=function(filter){var tmpFilter=_.cloneDeep(filter)||{};return tmpFilter.GuidBuilding="",tmpFilter.GuidSelection="",tmpFilter.GuidDataOwner="",tmpFilter.GuidEstate="",!1!==tmpFilter.isBuildingDependent&&(tmpFilter.isBuildingDependent=!0),commonService.getFilterData().selectedBuilding.Guid&&tmpFilter.isBuildingDependent&&!tmpFilter.excludeBuilding&&(tmpFilter.GuidBuilding=commonService.getFilterData().selectedBuilding.Guid),commonService.getFilterData().selectedSelection.Guid&&(tmpFilter.GuidSelection=commonService.getFilterData().selectedSelection.Guid),commonService.getFilterData().selectedDataOwner.Guid&&(tmpFilter.GuidDataOwner=commonService.getFilterData().selectedDataOwner.Guid),$localStorage.generalOptions&&$localStorage.generalOptions.WebEstateHeaderSelection&&commonService.getFilterData().selectedEstate.Guid&&!tmpFilter.excludeEstate&&(tmpFilter.GuidEstate=commonService.getFilterData().selectedEstate.Guid),tmpFilter},service.getSingle=function(serviceUrl,guid,columns,setHtmlTitle,presets){var deferred=$q.defer(),url=serviceUrl+guid+service.getUrlParameters();return columns&&(url+="&columns="+columns),presets&&(url+="&presets="+presets),genericRepository.get(url,{}).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status?(updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),setHtmlTitle&&result.Data&&$rootScope.setHtmlTitleByModel(result.Data),deferred.resolve(result)):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))},function(error){deferred.reject(error)}),deferred.promise},service.getMainModel=function(serviceUrl,guid,columns,presets){return service.getSingle(serviceUrl,guid,columns,!0,presets)},service.getWithUrlParameter=function(serviceUrl,urlParameter,filter){var deferred=$q.defer(),filterstring="";filter&&(filterstring="&filter="+encodeURIComponent(JSON.stringify(service.getFilter(filter))));var url=serviceUrl+"?"+urlParameter+filterstring+service.getUrlParameters("&");return genericRepository.get(url,{}).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status?(result&&result.EntityName&&updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),deferred.resolve(result)):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))}).catch(function(error){deferred.reject(error)}),deferred.promise},service.getSingleWithNoParameter=function(serviceUrl){var deferred=$q.defer(),url=serviceUrl+service.getUrlParameters();return genericRepository.get(url,{}).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status?(updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),deferred.resolve(result)):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))}).catch(function(error){deferred.reject(error)}),deferred.promise},service.filterKeyWords=["@GuidLoggedInPerson","@GuidLoggedInPersonDepartment","@GuidLoggedInPersonResourceGroup","@GuidUser","@GuidUserCustomer","@GuidCurrentBuilding","@GuidSupplier","@GuidCurrentProperty","@GuidCurrentDataOwner"],service.prefillKeyWords=["@LoggedInPerson","@User","@CurrentBuilding","@UserSupplier","@UserCustomer","@GuidCurrentProperty"],service.timeKeywords=["@Today","@Month","@Year","@CurrentYear"],service.GetKeywordFilters=function(propertyFilters){if(!propertyFilters||!Array.isArray(propertyFilters))return propertyFilters;var filters=[],returnFilters=[];filters=_.cloneDeep(propertyFilters);for(var i=0;i=",returnFilters.push(filter),returnFilters.push({Operator:"<=",Property:filter.Property,Value:service.GetKeywordValue("@Today")})):returnFilters.push(filter):(filter.Value=service.GetKeywordValue(filter.Value),returnFilters.push(filter))}return returnFilters},service.GetKeywordValue=function(value){return angular.isUndefined(value)||null===value?"":(value=value.toString().replace("@GuidUserCustomer",authService.getUserData().guidCustomer),value=value.toString().replace("@GuidUser",authService.getUserData().guidUser),value=value.toString().replace("@GuidLoggedInPersonDepartment",authService.getUserData().guidPersonDepartment),value=value.toString().replace("@GuidLoggedInPersonResourceGroup",authService.getUserData().guidPersonResourceGroup),value=value.toString().replace("@GuidLoggedInPerson",authService.getUserData().guidPerson),value=value.toString().replace("@Today",moment().utc().startOf("day").hours(0).toISOString()),value=value.toString().replace("@Month",moment().utc().startOf("day").subtract(1,"month").toISOString()),value=value.toString().replace("@Year",moment().utc().startOf("day").subtract(1,"year").toISOString()),value=value.toString().replace("@CurrentYear",moment().startOf("day").utc().startOf("year").toISOString()),commonService.getFilterData().selectedBuilding&&""!==commonService.getFilterData().selectedBuilding.Guid&&(value=value.toString().replace("@GuidCurrentBuilding",commonService.getFilterData().selectedBuilding.Guid)),value=authService.getUserData().guidSupplier?value.toString().replace("@GuidSupplier",authService.getUserData().guidSupplier):value.toString().replace("@GuidSupplier",""),value=value.toString().replace("@GuidCurrentDataOwner",service.commonService.getFilterData().selectedDataOwner.Guid),value=value.toString().replace("@GuidCurrentProperty",service.commonService.getFilterData().selectedEstate.Guid))};var uniqueString=function(serviceUrl,page,pageSize,sorting,filter,columns){return serviceUrl+page+pageSize+JSON.stringify(sorting)+JSON.stringify(filter)+JSON.stringify(columns)};service.GetPaginated=function(serviceUrl,page,pageSize,sorting,filter,includeGuid,columns){var tmpfilter=service.getFilter(filter);tmpfilter.PropertyFilter&&(tmpfilter.PropertyFilter=service.GetKeywordFilters(tmpfilter.PropertyFilter),_.remove(tmpfilter.PropertyFilter,function(f){return"@GuidCurrentBuilding"===f.Value})),includeGuid&&(tmpfilter.includeGuid=includeGuid),tmpfilter.searchString&&(tmpfilter.searchString=tmpfilter.searchString.replace(/#/g,""));var url=(uniqueString(serviceUrl,page,pageSize,sorting,tmpfilter,columns),serviceUrl+"?page="+page+"&pageSize="+pageSize+"&sorting="+JSON.stringify(sorting)+"&filter="+encodeURIComponent(JSON.stringify(tmpfilter))+"&columns="+columns+service.getUrlParameters("&")),deferred=$q.defer();return genericRepository.get(url,{}).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status?result.EntityName||result.EntityType?(updateAccess({EntityName:result.EntityName||result.EntityType,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),deferred.resolve(result.Data)):deferred.resolve(result):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))},function(error){deferred.reject(getErrorMessageFromStatus(error.status,error.data))}),deferred.promise},service.updateSingle=function(serviceUrl,model,urlParams){var deferred=$q.defer(),id=model.Guid?model.Guid:"",url=serviceUrl+id+service.getUrlParameters();return urlParams&&(url=url+"&"+urlParams),validationService.validateModel(model),genericRepository.put(url,model).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status?"string"==typeof result?deferred.resolve(result):(updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),deferred.resolve(result.Data)):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))},function(error){deferred.reject(getErrorMessageFromStatus(error.status,error.data))}),deferred.promise},service.runAction=function(serviceUrl,bodyParameters,urlParams){var deferred=$q.defer(),url=serviceUrl+service.getUrlParameters();return urlParams&&(url=url+"&"+urlParams),genericRepository.put(url,bodyParameters).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status?"string"==typeof result||void 0===result.Data?deferred.resolve(result):deferred.resolve(result.Data):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))},function(error){deferred.reject(getErrorMessageFromStatus(error.status,error.data))}),deferred.promise},service.createSingle=function(serviceUrl,model,urlParams){var deferred=$q.defer(),url=serviceUrl+service.getUrlParameters()+"&"+urlParams;return validationService.validateModel(model),genericRepository.post(url,model).then(function(apiResponse){var result=apiResponse.data;201===apiResponse.status?(updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),deferred.resolve(result.Data?result.Data:result)):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result.Data))},function(apiResponse){apiResponse.data&&deferred.reject(getErrorMessageFromStatus(apiResponse.status,apiResponse.data))}),deferred.promise},service.createSingleWithBinary=function(serviceUrl,model,binaries){var deferred=$q.defer(),url=serviceUrl+service.getUrlParameters();return genericRepository.postFile(url,model,binaries).then(function(apiResponse){200===apiResponse.status?deferred.resolve(apiResponse):deferred.reject(apiResponse.errorFiles)},function(error){deferred.reject(getErrorMessageFromStatus(error.status,error.data.Data))},function(progress){deferred.notify(progress)}).catch(function(apiResponse){deferred.reject(getErrorMessageFromStatus(apiResponse.status,apiResponse.data.Data))}),deferred.promise},service.updateSingleWithBinary=function(serviceUrl,model,binaries){var deferred=$q.defer(),url=serviceUrl+model.Guid+service.getUrlParameters();return genericRepository.putFile(url,model,binaries).then(function(apiResponse){200===apiResponse.status?deferred.resolve(apiResponse):deferred.reject(apiResponse.errorFiles)},function(error){deferred.reject(getErrorMessageFromStatus(error.status,error.data.Data))},function(progress){deferred.notify(progress)}).catch(function(apiResponse){deferred.reject(getErrorMessageFromStatus(apiResponse.status,apiResponse.data.Data))}),deferred.promise},service.createMultipleWithGuid=function(serviceUrl,guid,model){var deferred=$q.defer(),url=serviceUrl+guid;return url+=service.getUrlParameters(),genericRepository.post(url,model).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status?(updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),deferred.resolve(result.Data)):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))},function(error){deferred.reject(getErrorMessageFromStatus(error.status,error.data))}),deferred.promise},service.createMultiple=function(serviceUrl,model,urlParams){var deferred=$q.defer(),url=serviceUrl;return url+="/multiple",url+=service.getUrlParameters(),url+="&"+urlParams,genericRepository.post(url,model).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status||201===apiResponse.status?(updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),deferred.resolve(result.Data||result)):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))},function(error){deferred.reject(getErrorMessageFromStatus(error.status,error.data))}),deferred.promise},service.updateMultiple=function(serviceUrl,model){var deferred=$q.defer(),url=serviceUrl+service.getUrlParameters();return genericRepository.put(url,model).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status||201===apiResponse.status?(updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),deferred.resolve(result.Data)):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))},function(error){deferred.reject(getErrorMessageFromStatus(error.status,error.data))}),deferred.promise},service.updateMultipleWithGuid=function(serviceUrl,guid,model,urlParams){var deferred=$q.defer(),url=serviceUrl+guid+service.getUrlParameters();return urlParams&&(url=url+"&"+urlParams),genericRepository.put(url,model).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status||201===apiResponse.status?(updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),deferred.resolve(result.Data)):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))},function(error){deferred.reject(getErrorMessageFromStatus(error.status,error.data))}),deferred.promise},service.growl=function(message,type){growlsService.growl(message,type,{enter:"animated fadeInRight",exit:"animated fadeOutRight"})},service.showError=function(error){var message=getStringFromErrorObject(error);service.growl(message,"danger")},service.deleteSingle=function(serviceUrl,guid,urlParameter){var deferred=$q.defer(),url=serviceUrl+guid;return url+=urlParameter?"?"+urlParameter+service.getUrlParameters("&"):service.getUrlParameters(),genericRepository.delete(url,{}).then(function(apiResponse){var result=apiResponse.data;if(200===apiResponse.status)updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),deferred.resolve(result.Data);else{var errorMessage=getErrorMessageFromStatus(error.status,error.data);swal("Error!",errorMessage,"error"),deferred.reject(errorMessage)}},function(error){ var errorMessage=getErrorMessageFromStatus(error.status,error.data);error.data.IsDeactivateable?deferred.reject(error.data):swal("Error!",errorMessage,"error")}),deferred.promise},service.patch=function(serviceUrl,guid,model){var deferred=$q.defer(),url=serviceUrl;return guid&&(url+=guid),url+=service.getUrlParameters(),genericRepository.patch(url,model).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status?result.Data?deferred.resolve(result.Data):deferred.resolve(result):deferred.reject(getErrorMessageFromStatus(apiResponse.status,result))},function(error){deferred.reject(getErrorMessageFromStatus(error.status,error.data))}),deferred.promise},service.apiUrl={base:config.baseUrl,api:config.baseUrlApi},service.setMenuParameters=function(guidWebMenu,parameters,isBuildingDependent){var webMenus=angular.fromJson($localStorage.webMenus)||{};if(parameters){var paramObj=JSON.parse(parameters);paramObj.isBuildingDependent=isBuildingDependent,webMenus[guidWebMenu]=JSON.stringify(paramObj),$localStorage.webMenus=webMenus}},service.getMenuParameters=function(guidWebMenu){if(!guidWebMenu)return{};if(guidWebMenu===authService.getUserData().GuidWebMenu)return JSON.parse(authService.getUserData().MenuParameters);var webMenus=angular.fromJson($localStorage.webMenus);if(!webMenus)return service.getShortcuts(),{};var params=webMenus[guidWebMenu];return void 0===params?(service.getShortcuts(),{}):JSON.parse(params)},service.parseAndStoreWebMenu=function(webMenu){if(webMenu){var filter={};return webMenu.Reference&&(filter=webMenu.Reference.replace(/(\r\n|\n|\r)/gm,"")),service.setMenuParameters(webMenu.Guid,filter,webMenu.IsBuildingDependent),{guid:webMenu.Guid,text:webMenu.Name,state:webMenu.Context,isBuildingDependent:webMenu.IsBuildingDependent,params:filter}}return null};var userMenus=[];return service.getShortcuts=function(){var defer=$q.defer();return service.GetPaginated(service.apiData.userXWebProfile.url,0,100,{IndexPosition:"asc"},{LoggedInUser:!0}).then(function(result){for(;userMenus.length>0;)userMenus.pop();result.List.length>0&&result.List.forEach(function(userWebProfile){var children=[];userWebProfile.WebProfile.WebMenus&&userWebProfile.WebProfile.WebMenus.forEach(function(webMenu){var parsed=service.parseAndStoreWebMenu(webMenu);parsed&&children.push(parsed)}),userMenus.push({guid:userWebProfile.WebProfile.Guid,icon:userWebProfile.WebProfile.Icon,text:userWebProfile.WebProfile.Description,open:userWebProfile.WebProfile.IsExpanded,children:children})}),defer.resolve(userMenus)},function(error){defer.reject(error)}),defer.promise},service}])}(),function(){angular.module("Plania").factory("ScrollService",["$window","$timeout",function($window,$timeout){var service={};return service.scrollToElement=function(elementId){"string"!=typeof elementId&&(elementId=elementId.toString()),$timeout(function(){var element=$window.document.getElementById(elementId),parentScrollElement=$(element).parents().filter(function(){return"auto"===$(this).css("overflow")}).first();parentScrollElement[0]?parentScrollElement[0].scrollTop=element.offsetTop:window.scrollTo({behavior:"smooth",top:element.offsetTop})})},service}])}(),function(){angular.module("Plania").service("setSavingInterceptorService",["$q","$injector","$rootScope",function($q,$injector,rootScope){var saveInterceptorService={},request=function(config){return"GET"===config.method?config:(rootScope.isSaving=!0,config)},requestError=function(config){return"GET"===config.method?config:(rootScope.isSaving=!1,$q.reject(config))},response=function(res){return"GET"===res.config.method?res:(rootScope.isSaving=!1,res)},responseError=function(res){return"GET"===res.config.method?res:(rootScope.isSaving=!1,$q.reject(res))};return saveInterceptorService.request=request,saveInterceptorService.requestError=requestError,saveInterceptorService.response=response,saveInterceptorService.responseError=responseError,saveInterceptorService}])}(),function(){function telerikService(translationService,$localStorage){var service={};return service.setTelerikCulture=function(locale){if(kendo&&kendo.cultures&&kendo.culture&&"object"==typeof kendo.cultures){for(var selectedCultureKey,cultureKeys=Object.keys(kendo.cultures),i=0;i-1?$scope.navigation.current.name.replace(".edit",""):$scope.navigation.current.name.replace(".create",""),$scope.deadlineUnits=[{text:"Dager",value:0},{text:"Uker",value:1},{text:"Måneder",value:2},{text:"År",value:3},{text:"Timer",value:7},{text:"Ganger",value:4}];var prefix=routeEntity.charAt(0).toUpperCase()+routeEntity.slice(1);$scope.prefix=repository.commonService.prefix[prefix],$scope.isUpdate=$scope.navigation.current.name===routeEntity+".edit",$scope.titleSystemName=$scope.isUpdate?"web-"+routeEntity+"-title":"web-"+routeEntity+"-title-create",$scope.titleDefaultName=$scope.isUpdate?translationService.translate("web-"+routeEntity,routeEntity):"Opprett "+translationService.translate("web-"+routeEntity,routeEntity),$scope.hasDescription=$stateParams.hasDescription,$scope.propertyLabels={Id:{systemName:"web-"+routeEntity+"-id",defaultName:"Id"},Description:{systemName:"web-"+routeEntity+"-description",defaultName:"Description"}};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix[prefix],checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix[prefix],checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix[prefix]),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix[prefix])};updateAccess(),$scope.isUpdate&&repository.getSingle(repository.apiData[routeEntity].url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess()},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("web-entity-update-success","Objektet har blitt oppdatert!"):translationService.translate("web-entity-create-success","Objektet har blitt opprettet!"),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(routeEntity+"."+destination,guid),$rootScope.goBack(routeEntity+"."+destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData[routeEntity].url,$scope.model).then(success,error):repository.createSingle(repository.apiData[routeEntity].url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-entity-message","Objektet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-entity-button-confirm","Ja, fjern objektet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData[routeEntity].url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-delete-success","Sletting fullført!"),result,"success"),$scope.goBack(routeEntity+".list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.goBack=function(){$rootScope.goBack(routeEntity+".list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("SimpleGenericFormController",["$scope","Repository","$stateParams","TranslationService","$rootScope",controller])}(),function(){function controller($scope,$modalInstance,modalParams,repository,ngTableParams,listService){$scope.modalParams=modalParams,$scope.getPropertyValue=function(row,column){var propertyColumn={Property:column.Property};return column.PropertyType&&(propertyColumn.PropertyType=column.PropertyType),listService.GetPropertyValue(row,propertyColumn)};var capitalizedColumns=[];$scope.modalParams.columns.forEach(function(col){var keys=Object.keys(col),newCol={};keys.forEach(function(key){newCol[key.charAt(0).toUpperCase()+key.slice(1)]=col[key]}),capitalizedColumns.push(newCol)});var columns=_.map(capitalizedColumns,"Property");$scope.visibleColumns=_.filter(capitalizedColumns,function(c){return!c.Hidden});var sorting=modalParams.sorting;!sorting&&$scope.visibleColumns&&$scope.visibleColumns[0]&&$scope.visibleColumns[0].Property&&(sorting={},sorting[$scope.visibleColumns[0].Property]="asc"),$scope.itemTable=new ngTableParams({page:1,count:10,sorting:sorting,filter:modalParams.filter},{total:0,counts:[10,25,50],getData:function($defer,params){var filter=angular.copy(params.filter());_.remove(filter.PropertyFilter,function(prop){return prop.isDisabled}),repository.GetPaginated(modalParams.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.save=function(item){$modalInstance.close(item)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("SingleSelectModalController",["$scope","$modalInstance","modalParams","Repository","ngTableParams","ListService",controller])}(),function(){function controller($scope,$modalInstance,$modal,ngTableParams,content){$scope.header=content.header,$scope.singleColumn=content.singleValue,$scope.idTitle=content.idTitle,$scope.onType=content.onType,$scope.createHandler=content.createHandler,$scope.defaultSort=content.defaultSort,content.displayColumns?$scope.columns=content.displayColumns:($scope.columns=[{Title:$scope.idTitle,Property:"id"}],$scope.singleColumn||$scope.columns.push({Title:"Beskrivelse",Property:"description"})),$scope.items=new ngTableParams({page:1,count:10,filter:{searchString:content.params.dropdown},sorting:$scope.defaultSort?$scope.defaultSort:{id:"asc"}},{total:0,counts:[10,20,50],paginationMaxBlocks:5,getData:function($defer,params){content.params.dropdown=params.filter().searchString;var columns=[];$scope.columns.forEach(function(col){columns.push(col.Property)}), content.data(content.params,params.page()-1,params.count(),params.sorting(),columns).then(function(result){result.totalCount?(params.total(result.totalCount),$defer.resolve(result.dropdown)):(params.total(result.dropdown.length),$defer.resolve(result.dropdown.slice((params.page()-1)*params.count(),params.page()*params.count())))})}});var selectedItem={};$scope.getProperty=function(item,property){return"id"===property||"description"===property?item[property]:$scope.getDescendantProp(item.object,property)},$scope.getDescendantProp=function(item,property){for(var arr=property.split(".");arr.length&&(item=item[arr.shift()]););return item},$scope.selectItem=function(item){selectedItem=item},$scope.isItemSelected=function(guid){return!!selectedItem.guid&&selectedItem.guid===guid},$scope.ok=function(item){item?$modalInstance.close(item):$modalInstance.close(selectedItem)},$scope.cancel=function(){$modalInstance.dismiss()},$scope.can=function(operation){if(!$scope.createHandler)return!1;if($scope.createHandler.can)return $scope.createHandler.can(operation);var permissionHandler=$scope["has"+operation+"Access"];return!!permissionHandler&&permissionHandler($scope.onType)};var capitalizeFirstLetter=function(str){return str?str.charAt(0).toUpperCase()+str.slice(1):str};$scope.createEntity=function(){if(!$scope.createHandler)return!1;var templateUrl=$scope.createHandler.templateUrl,controller=$scope.createHandler.controller?$scope.createHandler.controller:capitalizeFirstLetter($scope.onType)+"Controller",cancelModal=$scope.createHandler.cancelModal?$scope.createHandler.cancelModal:function(){modalInstance.dismiss("canceled")},closeModal=$scope.createHandler.closeModal?$scope.createHandler.closeModal:function(){modalInstance.close()};modalInstance=$modal.open({templateUrl:templateUrl,size:"md",animation:!1,controller:controller,resolve:{$stateParams:function(){return{isModal:!0,isUpdate:!1,closeModal:closeModal,cancelModal:cancelModal}}}}),modalInstance.result.then(function(result){$scope.items.reload()},function(error){})}}angular.module("Plania").controller("TableModalController",["$scope","$modalInstance","$modal","ngTableParams","content",controller])}(),function(){function controller($scope,$rootScope,repository,commonService){}angular.module("Plania").controller("UnAuthorizedController",["$scope",controller])}(),function(){function controller($scope){$scope.tooltipText=$scope.userInfo.realName+" "+$scope.userInfo.username,$scope.toggled=function(open){open?$scope.tooltipText="":($scope.tooltipText=$scope.userInfo.realName+" "+$scope.userInfo.username,$scope.isDropdownOpen=!1)}}angular.module("Plania").controller("UserInfoController",["$scope",controller])}(),function(){function controller($scope,$modalInstance,repository,params){$scope.user=params.user,$scope.close=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("UserInformationModalController",["$scope","$modalInstance","Repository","params",controller])}(),function(){function controller($scope,$rootScope,authService,repository,$timeout,signalR,$localStorage){$scope.showNotificationBell=!1,$scope.showSubMenu=!1,$scope.notificationListData={TotalCount:0,List:[]},$scope.unreadNotificationListData={TotalCount:0,List:[]},$scope.pageSize={recent:10,unread:10},$scope.currentTab="recent";var userData=authService.getUserData();userData.guidPerson&&repository.getSingle(repository.apiData.person.url,userData.guidPerson).then(function(response){$scope.showNotificationBell=$rootScope.hasReadAccess("UserXUserNotification")&&(response.Data.DoesCleaningTasks||$localStorage.generalOptions.EnableWebWorkOrderNotifications),$scope.showNotificationBell&&(getNotifications(),getNotifications(!0),signalR.on("newUserNotification",function(userXUserNotification){$scope.notificationListData.List.find(function(item){item.Guid,userXUserNotification.Guid})||($scope.notificationListData.List.unshift(userXUserNotification),$scope.notificationListData.TotalCount++,$scope.pageSize.recent++),userXUserNotification.ReadDate||$scope.unreadNotificationListData.List.find(function(item){item.Guid,userXUserNotification.Guid})||($scope.unreadNotificationListData.List.unshift(userXUserNotification),$scope.unreadNotificationListData.TotalCount++,$scope.pageSize.unread++)}),signalR.on("updatedUserNotification",function(userXUserNotification){$scope.unreadNotificationListData.List=$scope.unreadNotificationListData.List.map(function(notification){return notification.Guid===userXUserNotification.Guid?userXUserNotification:notification}),$scope.notificationListData.List=$scope.notificationListData.List.map(function(notification){return notification.Guid===userXUserNotification.Guid?userXUserNotification:notification})}),signalR.on("userXUserNotificationDeleted",function(guidDeleted){$scope.unreadNotificationListData.List=$scope.unreadNotificationListData.List.filter(function(notification){return notification.Guid!==guidDeleted||($scope.unreadNotificationListData.TotalCount--,!1)}),$scope.notificationListData.List=$scope.notificationListData.List.filter(function(notification){return notification.Guid!==guidDeleted||($scope.notificationListData.TotalCount--,!1)})}))},function(error){$scope.showNotificationBell=!1});var getNotifications=function(getUnread){var filter={PropertyFilter:[{Property:"GuidUser",Operator:"=",Value:userData.guidUser}]};getUnread&&filter.PropertyFilter.push({Property:"ReadDate",Operator:"=",Value:null}),repository.GetPaginated(repository.apiData.userXUserNotification.url,0,getUnread?$scope.pageSize.unread:$scope.pageSize.recent,{CreationDate:"desc"},filter).then(function(result){getUnread?$scope.unreadNotificationListData=result:$scope.notificationListData=result})};$scope.getNotificationListData=function(){return"recent"===$scope.currentTab?$scope.notificationListData:$scope.unreadNotificationListData},$scope.setNotificationAsSeen=function(notification){if(!notification.ReadDate){var setDate=function(date){$scope.unreadNotificationListData.List.forEach(function(notice){notice.Guid===notification.Guid&&(notice.ReadDate=date)}),$scope.notificationListData.List.forEach(function(notice){notice.Guid===notification.Guid&&(notice.ReadDate=date)})};setDate((new Date).toISOString()),repository.updateSingle(repository.apiData.userXUserNotification.url,notification).then(function(){$scope.unreadNotificationListData.TotalCount--,$scope.unreadNotificationListData.TotalCount<0&&($scope.unreadNotificationListData.TotalCount=0),$scope.unreadNotificationListData.List=$scope.unreadNotificationListData.List.filter(function(item){return!item.ReadDate})},function(error){setDate(null),repository.growl(error,"danger")})}},$scope.navigateToEntity=function(notification){"AreaXCleaningTask"!==notification.UserNotification.EntityType&&252!==notification.UserNotification.EntityType||!notification.GuidDrawing||$scope.navigation.go("dwg.view",{guid:notification.GuidDrawing,selectedTheme:"cleaning",guidArea:notification.GuidArea},{reload:!0}),"EntityComment"!==notification.UserNotification.EntityType&&65!==notification.UserNotification.EntityType||(notification.GuidWorkOrder&&$scope.navigation.go("workOrder.edit",{guid:notification.GuidWorkOrder},{reload:!0}),notification.GuidRequest&&$scope.navigation.go("request.edit",{guid:notification.GuidRequest},{reload:!0})),"WorkOrder"!==notification.UserNotification.EntityType&&6!==notification.UserNotification.EntityType||!notification.GuidWorkOrder||$scope.navigation.go("workOrder.edit",{guid:notification.GuidWorkOrder},{reload:!0}),"Request"!==notification.UserNotification.EntityType&&179!==notification.UserNotification.EntityType||!notification.GuidRequest||$scope.navigation.go("request.edit",{guid:notification.GuidRequest},{reload:!0})},$scope.setAllAsRead=function(){var guids=[];$scope.unreadNotificationListData.List.forEach(function(notification){guids.push(notification.Guid),notification.ReadDate=(new Date).toISOString()}),$scope.notificationListData.List.forEach(function(notification){guids.indexOf(notification.Guid)>-1&&(notification.ReadDate=(new Date).toISOString())}),$scope.unreadNotificationListData.List=[],$scope.unreadNotificationListData.TotalCount=0,guids.length>0&&repository.updateMultiple(repository.apiData.userXUserNotification.endpoint.setAsRead,guids)},$scope.respondToNotification=function(notification){notification.blockRespondAction||(notification.blockRespondAction=!0,"AreaXCleaningTask"!==notification.UserNotification.EntityType&&252!==notification.UserNotification.EntityType||!notification.UserNotification.GuidEntity||notification.UserNotification.GuidUserHandledBy||!userData.guidPerson?notification.blockRespondAction=!1:repository.patch(repository.apiData.areaXCleaningTask.url,notification.UserNotification.GuidEntity,{GuidCleaner:userData.guidPerson}).then(function(result){notification.blockRespondAction=!1},function(error){notification.blockRespondAction=!1,repository.growl(error,"danger")}))},$scope.setTab=function(tab){disableAnimation=!0,$scope.currentTab=tab,$timeout(function(){disableAnimation=!1},100)},$scope.getMoreNotifications=function(){"recent"===$scope.currentTab?$scope.pageSize.recent+=10:$scope.pageSize.unread+=10,getNotifications("unread"===$scope.tab)},$scope.getTimeSinceNotification=function(notification){var creationDate=moment(notification.CreationDate),now=moment();return now.diff(creationDate,"month")?now.diff(creationDate,"month")+(now.diff(creationDate,"month")>1?" måneder":" måned"):now.diff(creationDate,"week")?now.diff(creationDate,"week")+(now.diff(creationDate,"week")>1?" uker":" uke"):now.diff(creationDate,"days")?now.diff(creationDate,"days")+(now.diff(creationDate,"days")>1?" dager":" dag"):now.diff(creationDate,"hours")?now.diff(creationDate,"hours")+(now.diff(creationDate,"hours")>1?" timer":" time"):now.diff(creationDate,"minutes")?now.diff(creationDate,"minutes")+(now.diff(creationDate,"minutes")>1?" minutter":" minutt"):now.diff(creationDate,"seconds")?now.diff(creationDate,"seconds")+(now.diff(creationDate,"seconds")>1?" sekunder":" sekund"):void 0},$scope.$on("$destroy",function(){signalR.off("newUserNotification"),signalR.off("updatedUserNotification")}),$scope.toggleSubMenuVisibility=function(){$scope.showSubMenu=!$scope.showSubMenu},$scope.mainDropdownToggled=function(open){open||($scope.showSubMenu=!1)},$scope.getHandledByUserName=function(notification){return notification.UserNotification&¬ification.UserNotification.HandledByUser?notification.UserNotification.HandledByUser.Person&¬ification.UserNotification.HandledByUser.FirstName?notification.UserNotification.HandledByUser.Person.FirstName+" "+notification.UserNotification.HandledByUser.Person.LastName:notification.UserNotification.HandledByUser.RealName?notification.UserNotification.HandledByUser.RealName:"":""}}var planiaModule=angular.module("Plania"),disableAnimation=!1;planiaModule.animation(".notificationList",[function(){return{enter:function(element,doneFn){if(disableAnimation)return void doneFn();element.css("display","none"),jQuery(element).slideDown(500,doneFn)},leave:function(element,doneFn){if(disableAnimation)return void doneFn();jQuery(element).fadeOut(500,doneFn)}}}]),planiaModule.controller("UserNotificationController",["$scope","$rootScope","authService","Repository","$timeout","SignalR","$localStorage",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,ngTableParams,translationService,listService,$localStorage){$scope.isUpdate="component.edit"===$scope.navigation.current.name,$scope.persons=[],$scope.activateAutocomplete=!1,$scope.barcode={},$scope.viewMode=!!$scope.isUpdate,$scope.model={Guid:$stateParams.guid},$scope.useComponentCounter=$localStorage.generalOptions.UseComponentCounter,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Component,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Component,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Component),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Component)};updateAccess(),$scope.componentEquipmentColumns=[{Position:1,Title:translationService.translate("web-equipment-id"),Property:"Equipment.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-equipment-description"),Property:"Equipment.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-componentxequipment-quantity","Antall"),Property:"Quantity",PropertyType:"string"},{Position:4,Title:translationService.translate("web-area-id"),Property:"Equipment.Area.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-area-description"),Property:"Equipment.Area.Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-equipment-updatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}],$scope.componentAreaColumns=[{Position:1,Title:translationService.translate("web-area-id"),Property:"Area.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-area-description"),Property:"Area.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-componentxarea-quantity","Antall"),Property:"Quantity",PropertyType:"string"},{Position:4,Title:translationService.translate("web-componentxequipment-updatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"string"}];var supplierColumns=["Supplier.Id","Supplier.Description","Supplier.Telephone","Manufacturer","Price","PartNumber","DeliveryTimePeriodUnit","DeliveryTimePeriodNumber"],getCardTables=function(){$scope.equipmentTable=new ngTableParams({page:1,count:10,sorting:{"Equipment.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidComponent",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,30],paginationMaxBlocks:6,getData:function($defer,params){var columns=_.map($scope.componentEquipmentColumns,"Property");columns.push.apply(columns,["Note","Equipment.Building.Id","Equipment.Building.Description"]),repository.GetPaginated(repository.apiData.componentEquipment.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.equipmentTable.settings().total=result.TotalCount,$scope.equipmentTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.supplierTable=new ngTableParams({page:1,count:10,sorting:{"Supplier.Id":"asc"},filter:{GuidComponent:$scope.model.Guid}},{total:0,filterDelay:10,counts:[10,20,30],paginationMaxBlocks:6,getData:function($defer,params){repository.GetPaginated(repository.apiData.componentSupplier.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(supplierColumns)).then(function(result){$scope.supplierTable.settings().total=result.TotalCount,$scope.supplierTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.areaTable=new ngTableParams({page:1,count:10,sorting:{"Area.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidComponent",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,30],paginationMaxBlocks:6,getData:function($defer,params){var columns=_.map($scope.componentAreaColumns,"Property");columns.push.apply(columns,["Area.Building.Id","Area.Building.Description"]),repository.GetPaginated(repository.apiData.componentArea.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.areaTable.settings().total=result.TotalCount,$scope.areaTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})},columns=["ComponentCategory.Description","PreferredComponent.Id","PreferredComponent.Description"];if($scope.isUpdate)repository.getMainModel(repository.apiData.component.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.reload=!0,updateAccess(),$scope.reloadDocumentTable=!0,$scope.reloadQrCodes=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}),getCardTables();else{var getCategoryPrefill=function(guid){var guidCategory=guid||$scope.model.GuidComponentCategory;guidCategory&&repository.getSingle(repository.apiData.componentCategory.url,guidCategory).then(function(result){$scope.model.DynamicProperty=result.Data.DynamicProperty},function(error){repository.growl(error,"danger")})},webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value)switch(prefill.Property){case"ComponentCategory":$scope.model.ComponentCategory={Guid:prefill.Value.Guid,Description:prefill.Value.Label,Caption:prefill.Value.Label},$scope.model.GuidComponentCategory=prefill.Value.Guid}else $scope.model[prefill.Property]=prefill.Value}),getCategoryPrefill(),$scope.activateAutocomplete=!0}$scope.getPropertyValue=function(row,columns){return listService.GetPropertyValue(row,columns)},$scope.onComponentCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidComponentCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidComponentCategory=category.Guid},$scope.updateComponent=function(destination){var success=function(result){repository.growl($scope.isUpdate?"Komponenten ble oppdatert":"Komponenten ble lagret","success");var componentGuid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,componentGuid),"component.create"===destination?$scope.navigation.go(destination,{},{reload:!0}):(repository.persistedData.clearPersistedData(),$scope.goBack(destination,{guid:componentGuid,menuGuid:$scope.navigation.params.menuGuid}))},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.component.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.component.url,$scope.model).then(success).catch(error)},$scope.cancel=function(){$scope.goBack("component.list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.removeComponent=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-component-message","Komponenten vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-component-button-confirm","Ja, fjern komponenten"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.component.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-component-success","Komponenten ble fjernet!"),result,"success"),$scope.goBack("component.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.addEquipment=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:translationService.translate("web-compnentEquipment-title-add","Legg til anlegg"),columns:[{Title:translationService.translate("web-equipment-building-id","Byggnr."),Property:"Building.Id"},{Title:translationService.translate("web-equipment-building-description","Byggnavn"),Property:"Building.Description"},{Title:translationService.translate("web-equipment-id","Id"),Property:"Id"},{Title:translationService.translate("web-equipment-description","Beskrivelse"),Property:"Description"}],url:repository.apiData.equipment.url,sorting:{Id:"asc"},filter:{FilterModel:{Condition:"and",Rules:[{Property:"IsTemplate",Operator:"=",Value:!1},{Property:"ComponentXEquipments.GuidComponent",Operator:"<>",Value:$scope.model.Guid,CollectionOperator:"all"}]}}}}}}).result.then(function(equipmentGuids){var model=[];equipmentGuids.forEach(function(guid){model.push({GuidEquipment:guid,GuidComponent:$scope.model.Guid})}),repository.createMultiple(repository.apiData.componentEquipment.url,model).then(function(result){repository.growl(translationService.translate("component-equipment-add-success","Anlegg har blitt lagt til"),"success"),$scope.equipmentTable.reload()},function(error){repository.growl(error,"danger"),$scope.equipmentTable.reload()})},function(){})},$scope.removeEquipment=function(equipment){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-component-equipment-message","Anlegget vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-component-equipment-button-confirm","Ja, fjern anlegget"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.componentEquipment.url,equipment.Guid).then(function(result){swal(translationService.translate("web-swal-component-equipment-success","Anlegget ble fjernet!"),result,"success"),$scope.equipmentTable.reload()})})},$scope.updateEquipment=function(equipment){$modal.open({templateUrl:"app/component/views/editComponentEquipment.html",controller:"EditComponentEquipmentController",resolve:{params:function(){return{equipment:equipment}}}}).result.then(function(){$scope.equipmentTable.reload()},function(){})},$scope.addSupplier=function(){$modal.open({templateUrl:"app/component/views/componentSupplierModal.html",controller:"ComponentSupplierController",resolve:{params:function(){return{isUpdate:!1,guidComponent:$scope.model.Guid}}}}).result.then(function(){$scope.supplierTable.reload()},function(){})},$scope.updateSupplier=function(supplier){$modal.open({templateUrl:"app/component/views/componentSupplierModal.html",controller:"ComponentSupplierController",resolve:{params:function(){return{isUpdate:!0,supplier:supplier}}}}).result.then(function(){$scope.supplierTable.reload()},function(){})},$scope.removeSupplier=function(supplier){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-component-supplier-message","Leverandøren vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-component-supplier-button-confirm","Ja, fjern leverandøren"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.componentSupplier.url,supplier.Guid).then(function(result){swal(translationService.translate("web-swal-component-supplier-success","Leverandøren ble fjernet!"),result,"success"),$scope.supplierTable.reload()})})},$scope.addArea=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:translationService.translate("web-compnentEquipment-title-add-area","Legg til rom"),columns:[{Title:translationService.translate("web-area-id","Id"),Property:"Id"},{Title:translationService.translate("web-area-description","Beskrivelse"),Property:"Description"}],url:repository.apiData.area.url,sorting:{Id:"asc"},filter:{FilterModel:{Condition:"and",Rules:[{Property:"ComponentXAreas.GuidComponent",Operator:"<>",Value:$scope.model.Guid,CollectionOperator:"all"}]}}}}}}).result.then(function(areaGuids){var model=[];areaGuids.forEach(function(guid){model.push({GuidArea:guid,GuidComponent:$scope.model.Guid})}),repository.createMultiple(repository.apiData.componentArea.url,model).then(function(result){repository.growl(translationService.translate("web-component-addArea-success","Areal har blitt lagt til"),"success"),$scope.areaTable.reload()},function(error){repository.growl(error,"danger"),$scope.areaTable.reload()})},function(){})},$scope.removeArea=function(area){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-component-area-message","Rommet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-component-area-button-confirm","Ja, fjern rommet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.componentArea.url,area.Guid).then(function(result){swal(translationService.translate("web-swal-component-area-success","Rommet ble fjernet!"),result,"success"),$scope.areaTable.reload()})})},$scope.updateArea=function(area){$modal.open({templateUrl:"app/component/views/editComponentArea.html",controller:"EditComponentAreaController",resolve:{params:function(){return{componentArea:area}}}}).result.then(function(){$scope.areaTable.reload()},function(){})},$scope.uploadImage=function(images){if(!(images.length<1)){$modal.open({templateUrl:"app/common/views/imageUploadModal.html",controller:"ImageUploadModalController",size:"lg",resolve:{params:function(){return{image:images[0],areaType:"square"}}}}).result.then(function(croppedImage){function handleFileUpload(file,originalImage){var readCroppedImage=new Promise(function(resolve,reject){var reader=new FileReader;reader.onload=function(e){try{imageViewModel.ImageSrc=e.target.result.substr(e.target.result.indexOf("base64,")+"base64,".length),imageViewModel.Name=file.name,resolve()}catch(error){repository.growl(error),reject()}},reader.readAsDataURL(file)}),readOriginalImage=new Promise(function(resolve,reject){var reader=new FileReader;reader.onload=function(e){try{imageViewModel.OriginalImageSrc=e.target.result.substr(e.target.result.indexOf("base64,")+"base64,".length),resolve()}catch(error){repository.growl(error),reject()}},reader.readAsDataURL(originalImage)});Promise.allSettled([readCroppedImage,readOriginalImage]).then(uploadImages)}function uploadImages(){var files=[imageViewModel],shouldDeleteOldImage=!1;if($scope.model.GuidImage){shouldDeleteOldImage=!0;var oldGuid=$scope.model.GuidImage}repository.createMultiple(repository.apiData.image.url,files).then(function(result){$scope.model.GuidImage=result[0].Guid,repository.updateSingle(repository.apiData.component.url,$scope.model).then(function(result){shouldDeleteOldImage&&repository.deleteSingle(repository.apiData.image.url,oldGuid).then(function(result){})})},function(error){repository.growl(error)})}var imageViewModel={ImageSrc:null,Name:null,OriginalImageSrc:null};handleFileUpload(croppedImage,images[0])})}},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"componentCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("ComponentController",["$scope","Repository","$stateParams","$modal","ngTableParams","TranslationService","ListService","$localStorage",controller])}(),function(){function controller($scope,$modalInstance,params,repository,ngTableParams,$filter,translationService,listService){$scope.equipmentColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Building.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-description"),Property:"Building.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-equipment-id"),Property:"Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-equipment-description"),Property:"Description",PropertyType:"string"}],$scope.equipmentTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"}},{total:0,counts:[10,20,50],paginationMaxBlocks:5,getData:function($defer,params){$scope.isLoading=!0;var columns=[];$scope.equipmentColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.equipment.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List),$scope.isLoading=!1},function(error){repository.growl(error,"danger")})}}),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.selectedEquipments=[],$scope.saveEquipment=function(){if($scope.selectedEquipments.length){var model=[];$scope.selectedEquipments.forEach(function(guid){model.push({GuidEquipment:guid,GuidComponent:$scope.model.Guid})}),repository.createMultiple(repository.apiData.componentEquipment.url,model).then(function(result){repository.growl(translationService.translate("component-equipment-add-success","Anlegg har blitt lagt til"),"success"),$modalInstance.close("OK")},function(error){repository.growl(error,"danger")})}},$scope.addEquipment=function(guid){if(_.contains($scope.selectedEquipments,guid)){for(var i=0;i<$scope.selectedEquipments.length;i++)if($scope.selectedEquipments[i]===guid)return void $scope.selectedEquipments.splice(i,1)}else $scope.selectedEquipments.push(guid)},$scope.isEquipmentSelected=function(guid){return _.contains($scope.selectedEquipments,guid)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("ComponentEquipmentController",["$scope","$modalInstance","params","Repository","ngTableParams","$filter","TranslationService","ListService",controller])}(),function(){function controller($scope,repository,params,$modalInstance){if($scope.isUpdate=params.isUpdate,$scope.activateAutocomplete=!1,params.supplier){var columns=["Supplier.Id","Supplier.Description","Supplier.Guid"];repository.getSingle(repository.apiData.componentSupplier.url,params.supplier.Guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})}else $scope.model={GuidComponent:params.guidComponent,DeliveryTimePeriodUnit:"Undefined"},setTimeout(function(){$scope.activateAutocomplete=!0},250);$scope.saveAction=function(){$scope.isUpdate?repository.updateSingle(repository.apiData.componentSupplier.url,$scope.model).then(function(result){repository.growl("Leverandør oppdatert","success"),$modalInstance.close("ok")}).catch(function(error){repository.growl(error,"danger")}):repository.createSingle(repository.apiData.componentSupplier.url,$scope.model).then(function(result){repository.growl("Leverandør opprettet","success"),$modalInstance.close("ok")}).catch(function(error){repository.growl(error,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("ComponentSupplierController",["$scope","Repository","params","$modalInstance",controller])}(),function(){function controller($scope,repository,params,$modalInstance){$scope.model=angular.copy(params.componentArea), $scope.saveAction=function(){if(null===$scope.model.Quantity||void 0===$scope.model.Quantity)return void swal("Valideringsfeil","Antall må være et nummer","error");repository.updateSingle(repository.apiData.componentArea.url,$scope.model).then(function(result){repository.growl("Komponent på rom er oppdatert","success"),$modalInstance.close("ok")},function(error){repository.growl(error,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("EditComponentAreaController",["$scope","Repository","params","$modalInstance",controller])}(),function(){function controller($scope,repository,params,$modalInstance,$timeout){$scope.model=angular.copy(params.equipment),$scope.reload=!1,$timeout(function(){$scope.reload=!0},100),$scope.save=function(){$modalInstance.close()},$scope.saveAction=function(){repository.updateSingle(repository.apiData.componentEquipment.url,$scope.model).then(function(result){repository.growl("Anlegg oppdatert","success"),$modalInstance.close("ok")},function(error){repository.growl(error,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("EditComponentEquipmentController",["$scope","Repository","params","$modalInstance","$timeout",controller])}(),function(){function controller($scope,repository,modalParams,$modalInstance,translationService){$scope.model=angular.copy(modalParams.model),$scope.autoCompleteFilter=modalParams.autoCompleteFilter,modalParams.onChangeEvents&&Object.keys(modalParams.onChangeEvents).forEach(function(onChangeKey){$scope[onChangeKey]=function(entity){modalParams.onChangeEvents[onChangeKey]($scope.model,entity)}}),$scope.confirmChange=function(){var properties={GuidArea:$scope.model.GuidArea,GuidEquipment:$scope.model.GuidEquipment};repository.patch(repository.apiData.condition.url,$scope.model.Guid,properties).then(function(result){repository.growl(translationService.translate("web-condition-changeMaintenanceReferences-success","Vedlikeholdsobjekt er oppdatert"),"success"),$modalInstance.close()},function(error){repository.showError(error)})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("ConditionChangeMaintenanceReferencesModalController",["$scope","Repository","modalParams","$modalInstance","TranslationService",controller])}(),function(){function controller($scope,repository,modalParams,$modalInstance,ngTableParams,$rootScope,translationService,$window){var selectedGuids=modalParams.guids,conditionDate=modalParams.conditionDate,type=modalParams.type,guidConditionType=modalParams.guidConditionType,responses=[];$scope.currentTab="info",$scope.VersionComment="",$scope.isRunningAction=!1;var isToday=function(testDate){if(testDate&&""!==testDate){var d=new Date(testDate),today=new Date;return d.getDate()===today.getDate()&&d.getMonth()===today.getMonth()&&d.getFullYear()===today.getFullYear()}},shouldShowConfirmWithDate=function(){return!(1!==selectedGuids.length||!conditionDate||!type||isToday(conditionDate))&&("CurrentConditionInfo"===type||"CorrectiveAction"===type&&!!guidConditionType)};$scope.showConfirmWithConditionDateAsTodayButton=shouldShowConfirmWithDate(),$scope.confirmVersion=function(setConditionDateAsToday){$scope.isRunningAction=!0;var dto={Guids:selectedGuids,VersionComment:""!==$scope.VersionComment.trim()?$scope.VersionComment:null,ConditionDate:setConditionDateAsToday?(new Date).toISOString():null};repository.runAction(repository.apiData.condition.endpoint.confirmVersion,dto).then(function(result){$scope.isRunningAction=!1,result.AnyFailed?($scope.currentTab="errorMessages",responses=result.Items,$scope.errorMessageTable.reload()):$modalInstance.close()},function(error){$scope.isRunningAction=!1,repository.showError(error)})},$scope.errorMessageTable=new ngTableParams({page:1,count:10},{total:responses.length,counts:[5,10,20],getData:function($defer,params){$scope.errorMessageTable.settings().total=responses.length,$defer.resolve(responses.filter(function(i){return!i.IsSuccess}).slice((params.page()-1)*params.count(),params.page()*params.count()))}}),$scope.contextMenuOptions=function(item){var options=[];return options.push({html:' '+translationService.translate("web-condition-confirmVersion-viewCondition","Åpne tilstand/tiltak i nytt vindu")+"",click:function($itemScope,$event,modelValue,text,$li){$window.open($rootScope.navigation.href("condition.edit",{guid:item.Guid}),"_blank")}}),options},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("ConditionConfirmVersionModalController",["$scope","Repository","modalParams","$modalInstance","ngTableParams","$rootScope","TranslationService","$window",controller])}(),function(){function controller($scope,repository,$stateParams,$modalInstance,$localStorage,translationService,$modal,$rootScope,ngTableParams,listService,constants,$q,registeredFieldService,colorService){var isModal=$stateParams.isModal;$scope.isEdit=!!$stateParams.guid,$scope.viewMode=!(isModal||!$scope.isEdit),$scope.model={Guid:$stateParams.guid},isModal&&$stateParams.model&&($scope.model=$stateParams.model),$scope.modelIsLoaded=!1,$scope.reloadDocumentTable=!1,$scope.activateAutocomplete=!1,$scope.reload=!1,$scope.isDocumentsCollapsed=!0,$scope.useNewCorrectiveAction=$localStorage.generalOptions.UseNewCorrectiveAction,$scope.defaultDocumentCategory={Guid:repository.commonService.getFilterData().selectedDataOwner.GuidWoXEqDocumentCategory,Name:repository.commonService.getFilterData().selectedDataOwner.WoXEqDocumentCategory},$scope.year={range:function(){var range=[],startYear=$localStorage.generalOptions.YearRangeStart,year=(new Date).getFullYear();0===startYear&&(startYear=year-10);var endYear=$localStorage.generalOptions.YearRangeEnd;0===endYear&&(endYear=year+10);for(var i=startYear;i<=endYear;i++)range.push(i);return range}()},$scope.dropdown={ConditionType:{Description:"Ikke valgt",Guid:null},Consequence:{Id:"Ikke valgt",Guid:null},ConsequenceType:{Id:"Ikke valgt",Guid:null},ConditionTypes:[{Description:"Ikke valgt",Guid:null}],Consequences:[{Id:"Ikke valgt",Guid:null}],ConsequenceTypes:[{Id:"Ikke valgt",Guid:null}],EstimateDateYear:null},$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var updateAccess=function(){if($scope.isEdit){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Condition,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Condition,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Condition),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Condition)};if(updateAccess(),isModal&&!$scope.isEdit)switch($scope.canChangeMaintenanceObject={estate:!1,building:!1},$localStorage.generalOptions.InspectedEntityLocation){case constants.inspectedEntityLocation.anywhere:$scope.canChangeMaintenanceObject={estate:!0,building:!0};break;case constants.inspectedEntityLocation.estate:$scope.canChangeMaintenanceObject={estate:!$scope.model.GuidEstate,building:!0};break;case constants.inspectedEntityLocation.building:$scope.canChangeMaintenanceObject={estate:!$scope.model.GuidBuilding,building:!$scope.model.GuidBuilding}}isModal||$scope.isEdit?isModal&&($scope.activeTab={Condition:!0,CorrectiveAction:!1,Document:!1},$scope.selectTab=function(action){for(var key in $scope.activeTab)$scope.activeTab.hasOwnProperty(key)&&($scope.activeTab[key]=!1);$scope.activeTab[action]=!0}):($scope.steps=[{stepNumber:1,name:"chooseConditionType",title:translationService.translate("web-condition-section-title-type","Velg type")},{stepNumber:2,name:"basicInfo",title:translationService.translate("web-condition-section-title-basicInformation","Basisinformasjon")}],$scope.currentStep=$scope.steps[0].name,$scope.getCurrentStepNumber=function(){return _.find($scope.steps,{name:$scope.currentStep}).stepNumber},$scope.isStepDisabled=function(step){return _.find($scope.steps,{name:$scope.currentStep}).stepNumber<=step.stepNumber},$scope.isLastStep=function(){return $scope.currentStep===$scope.steps[$scope.steps.length-1].name},$scope.setConditionType=function(conditionType){$scope.model.Type=conditionType,$scope.currentStep="basicInfo","CurrentConditionInfo"===$scope.model.Type&&($scope.model.ConditionDate=(new Date).toISOString()),"CorrectiveAction"===$scope.model.Type&&$scope.setCorrectiveActionType()}),$scope.canCloseCorrectiveAction=function(condition,guidWorkOrder){return isModal?$stateParams.canCloseCorrectiveAction(condition):!$scope.model.EndDate&&$scope.model.GuidWorkOrder&&$scope.model.GuidWorkOrder===guidWorkOrder&&"CorrectiveAction"===$scope.model.Type},$scope.closeCorrectiveAction=function(condition){isModal?$stateParams.closeCorrectiveAction(condition).then(function(result){isModal&&$modalInstance.close("ok")}):swal({title:translationService.translate("web-condition-closeCorrectiveAction-swalTitle","Bekreft lukking av tiltak"),text:translationService.translate("web-condition-closeCorrectiveAction-swalMessage","Er du sikker på at du vil lukke tiltaket?"),type:"info",showCancelButton:!0,confirmButtonColor:"#2196f3",confirmButtonText:translationService.translate("web-condition-closeCorrectiveAction-swalConfirm","Ja, Lukk tiltaket!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.runAction(repository.apiData.condition.endpoint.close+$scope.model.Guid).then(function(result){swal(translationService.translate("web-condition-closeCorrectiveAction-swalSuccess","Tiltaket ble lukket!"),result.Id,"success"),$scope.goBack("condition.edit",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})},function(error){swal(translationService.translate("web-error","Feil"),error,"error")})})},$scope.autoCompleteFilter=function(filterName){var estateFieldRule=registeredFieldService.getLocalRegisteredField(repository.apiData.condition.prefix,"GuidEstate"),isEstateHidden=estateFieldRule&&estateFieldRule.Hidden;switch(filterName){case"estate":return{};case"building":return!isEstateHidden&&$scope.model.GuidEstate?{PropertyFilter:[{Property:"GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]}:{};case"area":return $scope.model.GuidBuilding?{PropertyFilter:[{Property:"GuidBuilding",Operator:"=",Value:$scope.model.GuidBuilding}]}:!isEstateHidden&&$scope.model.GuidEstate?{PropertyFilter:[{Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]}:{};case"equipment":var eqFilter={HasConditionControl:!0,PropertyFilter:[{Property:"IsTemplate",Operator:"=",Value:!1}]};return $scope.model.GuidBuilding?eqFilter.GuidBuilding=$scope.model.GuidBuilding:!isEstateHidden&&$scope.model.GuidEstate&&eqFilter.PropertyFilter.push({Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}),eqFilter;case"priority":return{PropertyFilter:[{Property:"EntityType",Operator:"=",Value:"Condition"}]};case"deviation":default:return{}}},$scope.setCorrectiveActionType=function(){$scope.model.Type="CorrectiveAction",$scope.dropdown.EstimateDateYear=(new Date).getFullYear(),$scope.model.EstimateDate=new Date($scope.dropdown.EstimateDateYear.toString()).toISOString(),$scope.model.Quantity=1,$scope.model.Unit="Stk",isModal&&($scope.selectTab("CorrectiveAction"),$scope.activeTabIndex=1)},$scope.cancelCorrectiveAction=function(){$scope.model.IsCancelled=!0,$scope.saveAction("condition.edit")};var refreshDropdownDataBinding=function(){if($scope.dropdown.ConditionTypes&&$scope.model.GuidConditionType){var conditionType=_.filter($scope.dropdown.ConditionTypes,{Guid:$scope.model.GuidConditionType});conditionType&&conditionType[0]&&($scope.dropdown.ConditionType=conditionType[0])}if($scope.dropdown.Consequences&&$scope.model.GuidConsequence){var consequence=_.filter($scope.dropdown.Consequences,{Guid:$scope.model.GuidConsequence});consequence&&consequence[0]&&($scope.dropdown.Consequence=consequence[0])}if($scope.dropdown.ConsequenceTypes&&$scope.model.GuidConsequenceType){var consequenceType=_.filter($scope.dropdown.ConsequenceTypes,{Guid:$scope.model.GuidConsequenceType});consequenceType&&consequenceType[0]&&($scope.dropdown.ConsequenceType=consequenceType[0])}$scope.model.EstimateDate&&($scope.dropdown.EstimateDateYear=new Date($scope.model.EstimateDate).getFullYear())};(function(){var conditionTypeColumns=["Id","Description","Value","LikertScale"];repository.GetPaginated(repository.apiData.conditionType.url,0,-1,{Id:"asc"},{},null,JSON.stringify(conditionTypeColumns)).then(function(result){if($scope.dropdown.ConditionTypes=[{Description:"Ikke valgt",Guid:null}].concat(result.List),$scope.model.GuidConditionType){var conditionType=_.filter($scope.dropdown.ConditionTypes,{Guid:$scope.model.GuidConditionType});conditionType&&conditionType[0]&&($scope.dropdown.ConditionType=conditionType[0])}});var consequenceColumns=["Id","Description","Value","LikertScale"];repository.GetPaginated(repository.apiData.consequence.url,0,-1,{Id:"asc"},{},null,JSON.stringify(consequenceColumns)).then(function(result){if($scope.dropdown.Consequences=[{Id:"Ikke valgt",Guid:null}].concat(result.List),$scope.model.GuidConsequence){var consequence=_.filter($scope.dropdown.Consequences,{Guid:$scope.model.GuidConsequence});consequence&&consequence[0]&&($scope.dropdown.Consequence=consequence[0])}});var consequenceTypeColumns=["Id","Description"];repository.GetPaginated(repository.apiData.consequenceType.url,0,-1,{Id:"asc"},{},null,JSON.stringify(consequenceTypeColumns)).then(function(result){if($scope.dropdown.ConsequenceTypes=[{Id:"Ikke valgt",Guid:null}].concat(result.List),$scope.model.GuidConsequenceType){var consequenceType=_.filter($scope.dropdown.ConsequenceTypes,{Guid:$scope.model.GuidConsequenceType});consequenceType&&consequenceType[0]&&($scope.dropdown.ConsequenceType=consequenceType[0])}})})(),$scope.versionTableColumns=[{Position:1,Title:translationService.translate("web-condition-versionTable-version","Nr"),Property:"Version",PropertyType:"number"},{Position:2,Title:translationService.translate("web-condition-versionTable-conditionType","Tilstand"),Property:"ConditionType.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-condition-versionTable-year","Tiltaksår"),Property:"Year",PropertyType:"string"},{Position:4,Title:translationService.translate("web-condition-versionTable-estimate","Overslag"),Property:"Estimate",PropertyType:"double"},{Position:5,Title:translationService.translate("web-condition-versionTable-confirmed","Bekreftet"),Property:"ConfirmedDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-condition-versionTable-status","Status"),Property:"Status",PropertyType:"enum.DeviationStatus"}],$scope.isVersionTableLoading=!1,$scope.confirmVersion=function(){$scope.useNewCorrectiveAction&&(formatModelBeforeSave($scope.model),repository.updateSingle(repository.apiData.condition.url,$scope.model).then(function(response){$modal.open({templateUrl:"app/condition/views/conditionConfirmVersionModal.html",controller:"ConditionConfirmVersionModalController",size:"md",resolve:{modalParams:function(){return{guids:[response.Guid],conditionDate:response.ConditionDate,type:response.Type,guidConditionType:response.GuidConditionType}}}}).result.then(function(){$scope.goBack("condition.edit",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})})},function(error){repository.showError(error)}))},$scope.goToVersion=function(guid){guid&&guid!==$scope.model.Guid&&window.open($rootScope.navigation.href("condition.edit",{guid:guid}),"_blank")};var getVersionTable=function(){!$scope.versionTable&&$scope.useNewCorrectiveAction&&($scope.versionTable=new ngTableParams({page:1,count:5,sorting:{Version:"desc"},filter:{GetAllVersions:!0,PropertyFilter:[{Property:"GuidMasterRecord",Operator:"=",Value:$scope.model.GuidMasterRecord}]}},{total:0,filterDelay:10,counts:[5,10,20],getData:function($defer,params){var columns=[];$scope.versionTableColumns.forEach(function(col){columns.push(col.Property)}),columns.push("VersionComment"),columns.push("UserConfirmedBy.RealName"),columns.push("IsCurrentVersion"),columns.push("ConditionDate"),columns.push("ConditionType.LikertScale"),$scope.isVersionTableLoading=!0,repository.GetPaginated(repository.apiData.condition.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.isVersionTableLoading=!1,$scope.versionTable.settings().total=result.TotalCount,$scope.versionTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger"),$scope.isVersionTableLoading=!1})}}))},columns=["Estate.Id","Estate.Description","Building.Id","Building.Description","Area.Id","Area.Description","Equipment.Id","Equipment.Description","Equipment.ConditionContextDescription","ConditionType.Id","ConditionType.Description","ConditionType.LikertScale","Consequence.Id","Consequence.Description","Consequence.LikertScale","ConsequenceType.Id","ConsequenceType.Description","ConstructionType.Id","Priority.Description","Priority.Color","UserCreatedBy.RealName","UserUpdatedBy.RealName","InspectionWorkOrder.Id","InspectionWorkOrder.Description","InspectionWorkOrder.DueDate","InspectionWorkOrder.GuidProject","InspectionWorkOrder.EndDate","InspectionWorkOrder.Status","InspectionWorkOrder.GuidPeriodicTask","InspectionWorkOrder.Project.Id","InspectionWorkOrder.Project.Description","CorrectiveWorkOrder.Id","CorrectiveWorkOrder.Description","CorrectiveWorkOrder.DueDate","CorrectiveWorkOrder.GuidProject","CorrectiveWorkOrder.EndDate","CorrectiveWorkOrder.Status","CorrectiveWorkOrder.GuidPeriodicTask","CorrectiveWorkOrder.Project.Id","CorrectiveWorkOrder.Project.Description"],getPresets=function(){if($scope.isEdit||isModal)return null;var model={};return applyFilterPropertiesToModel(model),delete model.Building,delete model.Estate,model},applyFilterPropertiesToModel=function(model){if(!isModal){var selectedBuilding=repository.commonService.getFilterData().selectedBuilding;selectedBuilding.Guid&&(model.GuidBuilding=selectedBuilding.Guid,model.Building={Guid:selectedBuilding.Guid,Caption:selectedBuilding.Name},selectedBuilding.Estate&&(model.GuidEstate=selectedBuilding.Estate.Guid,model.Estate={Guid:selectedBuilding.Estate.Guid,Caption:selectedBuilding.Estate.Caption}))}};(function(){var defer=$q.defer();if(!$scope.isEdit&&(isModal||!$stateParams.guidEntityToCopy))return applyFilterPropertiesToModel($scope.model),$.Deferred().resolve($scope.model).promise();var queryString=JSON.stringify(columns);!$scope.isEdit&&$stateParams.guidEntityToCopy&&(queryString+="&GuidCopyFrom="+$stateParams.guidEntityToCopy,$scope.currentStep="basicInfo");var presets=getPresets();return repository.getMainModel(repository.apiData.condition.url,$scope.isEdit?$stateParams.guid:"00000000-0000-0000-0000-000000000000",queryString,presets?JSON.stringify(presets):null).then(function(response){defer.resolve(response.Data)},function(error){repository.showError(error),defer.reject()}),defer.promise})().then(function(model){$scope.model=model,$scope.reloadDocumentTable=!0,$scope.reload=!0,updateAccess(),$scope.isEdit&&($scope.restrictEdit||($scope.restrictEdit=!$scope.model.IsCurrentVersion),isModal?$scope.selectTab("CorrectiveAction"===$scope.model.Type?"CorrectiveAction":"Condition"):("CurrentConditionInfo"===$scope.model.Type&&($scope.versionTableColumns=_.filter($scope.versionTableColumns,function(col){return"Year"!==col.Property&&"Estimate"!==col.Property})),getVersionTable())),refreshDropdownDataBinding(),$scope.model.Priority&&$scope.model.Priority.Color&&($scope.model.Priority.Color=colorService.convertToRainbow($scope.model.Priority.Color)),$scope.modelIsLoaded=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)});var formatModelBeforeSave=function(model){model.ConditionDate&&(model.ConditionDate=new Date(model.ConditionDate).toISOString()),model.DeadlineDate&&(model.DeadlineDate=new Date(model.DeadlineDate).toISOString()),model.GuidConditionType=$scope.dropdown.ConditionType.Guid,model.GuidConsequence=$scope.dropdown.Consequence.Guid,model.GuidConsequenceType=$scope.dropdown.ConsequenceType.Guid,model.GuidConditionType&&"Undefined"===model.Type&&(model.Type="Condition")},isValid=function(){return!(isModal&&"Condition"===$scope.model.Type&&!$scope.model.GuidConditionType)||(repository.growl(translationService.translate("web-condition-isValid-conditionMissingConditionType","Tilstand krever tilstandsgrad"),"danger"),!1)};$scope.saveAction=function(destination){if(formatModelBeforeSave($scope.model),isValid()){var success=function(result){if(repository.growl($scope.isEdit?translationService.translate("web-condition-update-success","Tiltak oppdatert"):translationService.translate("web-condition-create-success","Tiltak har blitt lagt til"),"success"),$scope.isEdit)return swal.close(),void(isModal?"close"===destination?$modalInstance.close("ok"):($scope.model=result,$scope.isEdit=!0,$scope.reloadDocumentTable=!0):(repository.commonService.setLastRegisterGuid(destination,$scope.model.Guid),$scope.goBack(destination,{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})));"exit"===destination?$scope.goBack("condition.list",{guid:result.Guid,menuGuid:$scope.navigation.params.menuGuid}):"close"===destination?$modalInstance.close("ok"):($scope.model=result,isModal?($scope.isEdit=!0,$scope.reloadDocumentTable=!0):$scope.goBack("condition.edit",{guid:result.Guid,menuGuid:$scope.navigation.params.menuGuid}))},error=function(error){repository.growl("string"==typeof error?error:error.Data.Message,"danger")};$scope.isEdit?repository.updateSingle(repository.apiData.condition.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.condition.url,$scope.model).then(success,error)}},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-condition-currentConditionInfo-message","Tilstandsinformasjon vil bli fjernet"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-condition-currentConditionInfo-button-confirm","Ja, fjern tilstandsinformasjon"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.condition.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-condition-currentConditionInfo-success","Tilstandsinformasjon ble fjernet!"),result,"success"),$scope.goBack("condition.list",{menuGuid:$scope.navigation.params.menuGuid})})})};var onEstateSelect=function(model,estate){if(!estate)return void(model.GuidEstate="");model.GuidEstate!==estate.Guid&&(model.GuidBuilding="",model.GuidEquipment="",model.GuidArea="",delete model.Building,delete model.Equipment,delete model.Area),model.GuidEstate=estate.Guid},onBuildingSelect=function(model,building){if(!building)return void(model.GuidBuilding="");model.GuidBuilding!==building.Guid&&(model.GuidEquipment="",model.GuidArea="",delete model.Equipment,delete model.Area),model.GuidBuilding=building.Guid,model.GuidEstate&&""!==model.GuidEstate||(model.GuidEstate=building.GuidEstate,model.Estate={Guid:building.Estate.Guid,Caption:building.Estate.Caption})},onAreaSelect=function(model,area){if(!area)return void(model.GuidArea="");model.GuidArea=area.Guid,model.GuidEstate&&""!==model.GuidEstate||(model.GuidEstate=area.Building.Estate.Guid,model.Estate={Guid:area.Building.Estate.Guid,Caption:area.Building.Estate.Caption}),model.GuidBuilding&&""!==model.GuidBuilding||(model.GuidBuilding=area.GuidBuilding,model.Building={Guid:area.Building.Guid,Caption:area.Building.Caption})},onEquipmentSelect=function(model,equipment){if(!equipment)return void(model.GuidEquipment="");model.GuidEquipment=equipment.Guid,model.Equipment=equipment,model.GuidEstate&&""!==model.GuidEstate||(model.GuidEstate=equipment.Building.Estate.Guid,model.Estate={Guid:equipment.Building.Estate.Guid,Caption:equipment.Building.Estate.Caption}),model.GuidBuilding&&""!==model.GuidBuilding||(model.GuidBuilding=equipment.GuidBuilding,model.Building={Guid:equipment.GuidBuilding,Caption:equipment.Building.Caption}),equipment.GuidArea&&(model.GuidArea=equipment.GuidArea,model.Area={Guid:equipment.GuidArea,Caption:equipment.Area.Caption})};$scope.onEstateSelect=function(estate){onEstateSelect($scope.model,estate)},$scope.onBuildingSelect=function(building){onBuildingSelect($scope.model,building)},$scope.onAreaSelect=function(area){onAreaSelect($scope.model,area)},$scope.onEquipmentSelect=function(equipment){onEquipmentSelect($scope.model,equipment)},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.calculateEstimate=function(){$scope.useNewCorrectiveAction&&($scope.model.Estimate=100*Math.round($scope.model.Quantity*$scope.model.UnitPrice/100),isNaN($scope.model.Estimate)&&($scope.model.Estimate=0))},$scope.onEstimateDateYearDropdownChange=function(){$scope.dropdown.EstimateDateYear?$scope.model.EstimateDate=new Date($scope.dropdown.EstimateDateYear.toString()).toISOString():$scope.model.EstimateDate=null},$scope.onGetValidityRules=function(originalValidityRules){var validityRules=_.clone(originalValidityRules);return"Condition"===validityRules.EntityType&&"ActionComment"===validityRules.DomainFieldName&&(validityRules.Mandatory|="CorrectiveAction"===$scope.model.Type),validityRules},$scope.changeMaintenanceObjects=function(){$modal.open({templateUrl:"app/condition/views/conditionChangeMaintenanceReferencesModal.html",controller:"ConditionChangeMaintenanceReferencesModalController",size:"lg",resolve:{modalParams:function(){return{model:$scope.model,autoCompleteFilter:$scope.autoCompleteFilter,onChangeEvents:{onAreaSelect:onAreaSelect,onEquipmentSelect:onEquipmentSelect}}}}}).result.then(function(){$scope.goBack("condition.edit",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})})},$scope.getPropertyValue=function(building,column){return listService.GetPropertyValue(building,column)};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.originContextMenu=function(){var options=[];return $scope.hasReadAccess("WorkOrder")&&$scope.model.GuidInspectionWorkOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:$scope.model.GuidInspectionWorkOrder}),translationService.translate("web-condition-originContextMenu-viewInspectionWorkOrder","Gå til arbeidsordre"))),$scope.hasReadAccess("Project")&&$scope.model.GuidInspectionWorkOrder&&$scope.model.InspectionWorkOrder&&$scope.model.InspectionWorkOrder.GuidProject&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("project.edit",{guid:$scope.model.InspectionWorkOrder.GuidProject}),translationService.translate("web-condition-originContextMenu-viewInspectionProject","Gå til prosjekt"))),$scope.hasReadAccess("PeriodicTask")&&$scope.model.GuidInspectionWorkOrder&&$scope.model.InspectionWorkOrder&&$scope.model.InspectionWorkOrder.GuidPeriodicTask&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:$scope.model.InspectionWorkOrder.GuidPeriodicTask}),translationService.translate("web-condition-originContextMenu-viewInspectionPeriodicTask","Gå til periodisk rutine"))),0===options.length&&options.push({html:''+translationService.translate("web-condition-originContextMenu-empty","Ingen aksjoner tilgjengelig")+"",enabled:!1}),options},$scope.followUpContextMenu=function(){var options=[];if($scope.hasEditAccess("Condition")&&$scope.model.GuidCorrectiveWorkOrder&&$scope.model.CorrectiveWorkOrder&&!$scope.model.CorrectiveWorkOrder.EndDate&&$scope.canCloseCorrectiveAction($scope.model,$scope.model.GuidCorrectiveWorkOrder)&&options.push({html:' '+translationService.translate("web-condition-followUpContextMenu-closeCorrectiveActionFromCorrective","Lukk tiltak via")+" "+$scope.model.CorrectiveWorkOrder.Caption+"",click:function($itemScope,$event,modelValue,text,$li){$scope.closeCorrectiveAction()}}),$scope.hasEditAccess("Condition")&&!$scope.model.GuidCorrectiveWorkOrder&&$scope.model.GuidInspectionWorkOrder&&$scope.model.InspectionWorkOrder&&!$scope.model.InspectionWorkOrder.EndDate&&$scope.canCloseCorrectiveAction($scope.model,$scope.model.GuidInspectionWorkOrder)&&options.push({html:' '+translationService.translate("web-condition-followUpContextMenu-closeCorrectiveActionFromInspection","Lukk tiltak via")+" "+$scope.model.InspectionWorkOrder.Caption+"",click:function($itemScope,$event,modelValue,text,$li){$scope.closeCorrectiveAction()}}),$scope.hasEditAccess("Condition")&&$scope.model.IsCurrentVersion&&$scope.useNewCorrectiveAction){var text=translationService.translate("web-condition-followUpContextMenu-confirmVersion","Bekreft versjon");"CurrentConditionInfo"===$scope.model.Type&&(test=translationService.translate("web-condition-currentConditionInfo-followUpContextMenu-confirmVersion","Bekreft versjon")),options.push({html:' '+text+"",click:function($itemScope,$event,modelValue,text,$li){$scope.confirmVersion()}})}return $scope.hasReadAccess("WorkOrder")&&$scope.model.GuidCorrectiveWorkOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:$scope.model.GuidCorrectiveWorkOrder}),translationService.translate("web-condition-followUpContextMenu-viewCorrectiveWorkOrder","Gå til arbeidsordre"))),$scope.hasReadAccess("Project")&&$scope.model.GuidCorrectiveWorkOrder&&$scope.model.CorrectiveWorkOrder&&$scope.model.CorrectiveWorkOrder.GuidProject&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("project.edit",{guid:$scope.model.CorrectiveWorkOrder.GuidProject}),translationService.translate("web-condition-followUpContextMenu-viewCorrectiveProject","Gå til prosjekt"))),$scope.hasReadAccess("PeriodicTask")&&$scope.model.GuidCorrectiveWorkOrder&&$scope.model.CorrectiveWorkOrder&&$scope.model.CorrectiveWorkOrder.GuidPeriodicTask&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:$scope.model.CorrectiveWorkOrder.GuidPeriodicTask}),translationService.translate("web-condition-followUpContextMenu-viewCorrectivePeriodicTask","Gå til periodisk rutine"))),$scope.hasEditAccess("Condition")&&"InWorks"===$scope.model.Status&&"CurrentConditionInfo"!==$scope.model.Type&&$scope.model.GuidCorrectiveWorkOrder&&!$scope.model.CorrectiveWorkOrder.EndDate&&options.push({ html:' '+translationService.translate("web-condition-followUpContextMenu-removeFromWorkOrder","Koble fra arbeidsordre")+"",click:function(){swal({title:translationService.translate("web-condition-followUpContextMenu-removeFromWorkOrder-swalTitle","Bekreft frakobling av tiltak"),text:translationService.translate("web-condition-followUpContextMenu-removeFromWorkOrder-swalMessage","Er du sikker på at du vil koble dette tiltaket ifra arbeidsordren?"),type:"info",showCancelButton:!0,confirmButtonColor:"#2196f3",confirmButtonText:translationService.translate("web-condition-followUpContextMenu-removeFromWorkOrder-swalConfirm","Ja, koble fra!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.model.GuidCorrectiveWorkOrder=null,$scope.saveAction("condition.edit")})}}),$scope.hasCreateAccess("WorkOrder")&&"Closed"!==$scope.model.Status&&"CurrentConditionInfo"!==$scope.model.Type&&!$scope.model.GuidCorrectiveWorkOrder&&options.push({html:' '+translationService.translate("web-condition-followUpContextMenu-createWorkOrder","Opprett ny arbeidsordre for gjennomføring av tiltak")+"",click:function(){var workOrder={guidSelections:[$scope.model.Guid],fromCondition:!0,fromDeviation:!1,defaultDescription:translationService.translate("correctiveAction-new-workOrder-defaultDescription","Gjennomføring av tiltak")};$scope.model.GuidEstate&&(workOrder.guidEstate=$scope.model.GuidEstate,$scope.model.Estate&&(workOrder.estate=$scope.model.Estate.Caption)),$scope.model.GuidBuilding&&(workOrder.guidBuilding=$scope.model.GuidBuilding,$scope.model.Building&&(workOrder.building=$scope.model.Building.Caption)),$scope.model.GuidEquipment&&(workOrder.guidEquipment=$scope.model.GuidEquipment,$scope.model.Equipment&&(workOrder.equipment=$scope.model.Equipment.Caption)),$scope.model.GuidArea&&(workOrder.guidArea=$scope.model.GuidArea,$scope.model.Area&&(workOrder.area=$scope.model.Area.Caption)),repository.persistedData.setPersistedData("workOrder.create",workOrder),$scope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})}}),$scope.hasReadAccess("WorkOrder")&&"Closed"!==$scope.model.Status&&"CurrentConditionInfo"!==$scope.model.Type&&$scope.hasEditAccess("Condition")&&!$scope.model.GuidCorrectiveWorkOrder&&options.push({html:' '+translationService.translate("web-condition-followUpContextMenu-addToExistingWo","Koble til eksisterende arbeidsordre")+"",click:function(){$modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:"Velg arbeidsordre tiltaket skal kobles til",url:repository.apiData.workOrder.url,sorting:{Id:"desc"},filter:{PropertyFilter:[{Property:"EndDate",Operator:"=",Value:null}]},columns:[{title:translationService.translate("web-workOrder-Id","Ao Nr"),property:"Id"},{title:translationService.translate("web-workOrder-Description","Beskrivelse"),property:"Description",PropertyType:"String"},{title:translationService.translate("web-workOrder-Building-Id","Bygg Id"),property:"Building.Id"},{title:translationService.translate("web-workOrder-Building-Description","Byggbeskrivelse"),property:"Building.Description",PropertyType:"String"}]}}}}).result.then(function(selectedEntity){$scope.model.GuidCorrectiveWorkOrder=selectedEntity.Guid,$scope.saveAction("condition.edit")})}}),$scope.hasEditAccess("Condition")&&"New"===$scope.model.Status&&"CorrectiveAction"===$scope.model.Type&&!$scope.model.IsCancelled&&options.push({html:' '+translationService.translate("web-condition-currentConditionInfo-followUpContextMenu-cancelCorrectiveAction","Kanseller")+"",click:function(){$scope.cancelCorrectiveAction()}}),$scope.hasEditAccess("Condition")&&"CurrentConditionInfo"===$scope.model.Type&&$scope.model.EndDate&&$scope.model.IsCurrentVersion&&options.push({html:' '+translationService.translate("web-condition-currentConditionInfo-followUpContextMenu-reOpenCurrentCondition","Reaktiver")+"",click:function(){$scope.model.EndDate=null,$scope.saveAction("condition.edit")}}),$scope.hasEditAccess("Condition")&&"CurrentConditionInfo"===$scope.model.Type&&!$scope.model.EndDate&&$scope.model.IsCurrentVersion&&options.push({html:' '+translationService.translate("web-condition-followUpContextMenu-deactivateCurrentCondition","Deaktiver")+"",click:function(){$scope.model.EndDate=(new Date).toISOString(),$scope.saveAction("condition.edit")}}),0===options.length&&options.push({html:''+translationService.translate("web-condition-followUpContextMenu-empty","Ingen aksjoner tilgjengelig")+"",enabled:!1}),options},$scope.$watch("dropdown.ConditionType.Guid",function(newValue,oldValue){newValue!==oldValue&&(newValue||($scope.model.ConditionDate=""),newValue&&!$scope.model.ConditionDate&&($scope.model.ConditionDate=moment().toDate()))}),$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.joinElements=function(){return Array.prototype.slice.call(arguments).filter(function(element){return null!==element&&void 0!==element}).join(" - ")}}angular.module("Plania").controller("ConditionController",["$scope","Repository","$stateParams","$modalInstance","$localStorage","TranslationService","$modal","$rootScope","ngTableParams","ListService","Constants","$q","RegisteredFieldService","ColorService",controller])}(),function(){function controller($scope,$modal,ngTableParams,repository,$rootScope,translationService,$localStorage,listService,constants,$q,commonService){var isSVV="SvvTunnel"===$localStorage.generalOptions.CustomerId||"Fylkeskommuner"===$localStorage.generalOptions.CustomerId;$scope.conditionsIsLoading=!0,$scope.search={};var contextId=$scope.parentEntity?$scope.parentEntity+"-Condition":null;$scope.hasEditAccess=$rootScope.hasEditAccess("Condition"),$scope.$watch("reload",function(newValue,oldValue){$scope.reload&&!0===$scope.reload&&($scope.conditionTable&&$scope.conditionTable.reload(),$scope.reload=!1)}),$scope.defaultListSetup={Id:"WorkOrderCondition",Sorting:{Id:"desc"},EntityType:repository.apiData.condition.prefix,ContextId:contextId,IsPublicView:!0,Columns:[{Position:1,Title:translationService.translate("web-condition-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-conditionType-id"),Property:"ConditionType.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-consequence-id"),Property:"Consequence.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-condition-conditiondate","Tilstandsdato"),Property:"ConditionDate",PropertyType:"date"},{Position:5,Title:translationService.translate("web-condition-actioncomment-measures","Tiltak"),Property:"ActionComment",PropertyType:"string"}]},$scope.menuOptions=function(condition){var options=[];return $scope.hasEditAccess&&options.push({html:' '+translationService.translate("web-workorder-condition-edit","Rediger tilstand")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.createOrUpdate(condition)}}),$scope.hasEditAccess&&$scope.hasAvailableDefaultCondition&&options.push({html:' '+translationService.translate("web-workorder-condition-approve","Godkjenn tilstand")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.approveCondition(condition)}}),$scope.hasEditAccess&&$scope.canCloseCorrectiveAction(condition)&&options.push({html:' '+translationService.translate("web-button-close-correctiveAction","Lukk tiltak")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.closeCorrectiveAction(condition)}}),$rootScope.hasDeleteAccess("Condition")&&options.push({enabled:!condition.ActionComment,hasTopDivider:!0,html:' '+translationService.translate("web-button-delete","Slett")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.remove(condition)}}),options};var originalListSetup=angular.copy($scope.defaultListSetup);$scope.columns=["Estate.Id","Estate.Description","Building.Id","Building.Description","Area.Id","Area.Description","Equipment.Id","Equipment.Description"];var hasAccessToCreateNewWebList=function(){return $scope.$root.userInfo.isSystemAdministrator&&repository.authService.hasCreateAccess(repository.commonService.prefix.WebListView,!1)},getModelForChange=function(){var modelCopy=_.cloneDeep($scope.defaultListSetup);modelCopy.WebColumnsToSynchronize=modelCopy.Columns,modelCopy.Columns=[],delete modelCopy.VisibleColumns;for(var i=0;i=0&&filter.Value&&"[object Date]"===Object.prototype.toString.call(filter.Value)&&(filter.Value=new Date(filter.Value).toISOString())};repository.GetPaginated(repository.apiData.webListView.url,0,10,{},{Prefix:repository.apiData.condition.prefix,ContextId:contextId}).then(function(result){var guidCurrentDataOwner=commonService.getFilterData().selectedDataOwner.Guid,webListCurrentDataOwner=_.find(result.List,function(x){return x.GuidDataOwner===guidCurrentDataOwner});webListCurrentDataOwner?$scope.defaultListSetup=webListCurrentDataOwner:hasAccessToCreateNewWebList()?repository.createSingle(repository.apiData.webListView.url,getModelForChange()).then(function(result){repository.getSingle(repository.apiData.webListView.url,result.Guid).then(function(result){$scope.defaultListSetup=result.Data})}):result.List.length&&($scope.defaultListSetup=result.List[0]),getTable()});var getTable=function(){$scope.conditionTable=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{}},{total:0,counts:[5,10,20],filterDelay:50,paginationMaxBlocks:$scope.useList?6:8,getData:function($defer,params){var filter=angular.copy(params.filter());filter.FilterModel={Condition:"and",Rules:[{Property:"Guid"+$scope.parentEntity,Operator:"=",Value:$scope.guid}]},"WorkOrder"===$scope.parentEntity&&(filter.FilterModel={Condition:"or",Rules:[{Property:"Guid"+$scope.parentEntity,Operator:"=",Value:$scope.guid},{Property:"GuidInspectionWorkOrder",Operator:"=",Value:$scope.guid}]}),$scope.conditionsIsLoading=!0;var columns=[];if($scope.columns.forEach(function(prop){columns.push(prop)}),$scope.defaultListSetup.Columns.forEach(function(col){columns.push(col.Property)}),columns.push("EndDate"),columns.push("Type"),columns.includes("ActionComment")||columns.push("ActionComment"),$scope.conditions)for(;$scope.conditions.length>0;)$scope.conditions.pop();repository.GetPaginated(repository.apiData.condition.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){if($scope.conditionTable.settings().total=result.TotalCount,$scope.conditionTable.settings().filterDelay=500,result.List.length>0){var conditionTypeColumns=["Id","IsApproved"];repository.GetPaginated(repository.apiData.conditionType.url,0,20,{Id:"asc"},{PropertyFilter:[{Property:"IsApproved",Operator:"=",Value:1}]},null,JSON.stringify(conditionTypeColumns)).then(function(result){1===result.TotalCount&&($scope.hasAvailableDefaultCondition=!0),result.TotalCount>1&&$localStorage.generalOptions.GuidCommonDataOwner&&_.some(result.List,{GuidDataOwner:$localStorage.generalOptions.GuidCommonDataOwner})&&($scope.hasAvailableDefaultCondition=!0)})}$defer.resolve(result.List),$scope.conditionsIsLoading=!1},function(error){$scope.conditionsIsLoading=!1,repository.growl(error,"danger")})}})};$scope.getLowestEntityCaption=function(deviation){return deviation.Equipment?$rootScope.getEntityCaption(deviation.Equipment):deviation.Area?$rootScope.getEntityCaption(deviation.Area):deviation.Building?$rootScope.getEntityCaption(deviation.Building):deviation.Estate?$rootScope.getEntityCaption(deviation.Estate):void 0},$scope.getEntityCaption=function(object){return $rootScope.getEntityCaption(object)},$scope.getEntityIcon=function(deviation){return deviation.Equipment?"fa-gear c-bluegray":deviation.Area?"fa-layer-group c-lightblue":deviation.Building?"fa-building-columns c-brown":deviation.Estate?"fa-city c-teal":void 0},$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.selectedConditions=[],$scope.conditionIsSelected=function(guid){return _.contains($scope.selectedConditions,guid)},$scope.addCondition=function(guid){if(_.contains($scope.selectedConditions,guid)){for(var i=0;i<$scope.selectedConditions.length;i++)if($scope.selectedConditions[i]===guid)return void $scope.selectedConditions.splice(i,1)}else $scope.selectedConditions.push(guid)},$scope.allRowsSelected=!1,$scope.selectAllRows=function(){$scope.allRowsSelected?($scope.conditionTable.data.forEach(function(row){var index=_.findIndex($scope.selectedConditions,function(o){return o===row.Guid});$scope.selectedConditions.splice(index,1)}),$scope.allRowsSelected=!1):($scope.conditionTable.data.forEach(function(row){_.contains($scope.selectedConditions,row.Guid)||$scope.selectedConditions.push(row.Guid)}),$scope.allRowsSelected=!0)},$scope.$watch("conditionTable.data",function(newValue,oldValue){if(newValue!==oldValue){if(0===newValue.length)return void($scope.allRowsSelected=!1);for(var i=0;i0?(swal(failed.length+" "+translationService.translate("web-condition-approveSelectedConditions-failed","ble ikke satt som standardtilstand"),_.uniq(_.map(failed,"Message")).join("\r\n"),"error"),$scope.selectedConditions=_.map(failed,"Guid")):(swal(translationService.translate("web-swal-conditions-approve-success","Tilstandene ble godkjent!"),"","success"),$scope.selectedConditions=[]),$scope.conditionTable.reload()})})},$scope.deleteSelectedConditions=function(){var deleteCondition=function(guid){var deferred=$q.defer(),condition=_.find($scope.conditionTable.data,{Guid:guid});return condition.ActionComment?$.Deferred().reject(condition).promise():(repository.deleteSingle(repository.apiData.condition.url,condition.Guid).then(function(){deferred.resolve(condition)},function(){deferred.reject(condition)}),deferred.promise)};swal({title:translationService.translate("web-swal-conditions-delete","Bekreft sletting av Tilstander"),text:translationService.translate("web-swal-conditions-delete-message","Er du sikker på at du vil slette alle tilstandene?"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-conditions-delete-confirm","Slett tilstandene"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null;var conditionsInPage=$scope.selectedConditions.filter(function(guid){return!!_.find($scope.conditionTable.data,{Guid:guid})});Promise.allSettled(conditionsInPage.map(function(guid){return deleteCondition(guid)})).then(function(promises){var failed=promises.filter(function(promise){return"rejected"===promise.status}).map(function(promise){return promise.reason});failed.length===promises.length?swal(translationService.translate("web-swal-conditions-delete-failed","Kunne ikke slette tilstandene"),translationService.translate("web-swal-conditions-delete-notDeleted","Ikke slettet:")+" "+_.map(failed,"Id"),"error"):failed.length>0?(swal(translationService.translate("web-swal-conditions-delete-partialSuccess","Kunne ikke slette alle tilstandene"),translationService.translate("web-swal-conditions-delete-notDeleted","Ikke slettet:")+" "+_.map(failed,"Id"),"info"),$scope.selectedConditions=_.map(failed,"Guid")):(swal(translationService.translate("web-swal-conditions-delete-success","Tilstandene ble slettet!"),"","success"),$scope.selectedConditions=[]),$scope.conditionTable.reload()})})},$scope.remove=function(condition){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-condition-message","Tilstanden vil bli permanent fjernet"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-condition-button-confirm","Ja, fjern tilstanden"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.deleteSingle(repository.apiData.condition.url,condition.Guid).then(function(result){swal(translationService.translate("web-swal-condition-success","Tilstanden ble fjernet"),result,"success"),$scope.conditionTable.reload()})})},$scope.editColumns=function(){$modal.open({templateUrl:"app/common/modal/views/editTableColumnsModal.html",controller:"EditTableColumnsModalController",resolve:{params:function(){return{defaultListSetup:originalListSetup,listSetup:$scope.defaultListSetup,entity:"Condition"}}}}).result.then(function(result){$scope.conditionTable.reload()},function(dismiss){})},$scope.$on($rootScope.events.newSelection,function(){$scope.conditionTable.reload()})}angular.module("Plania").directive("conditionDirective",function(){return{restrict:"E",scope:{isCollapsed:"=isCollapsed",reload:"=reload",conditions:"=conditions",estate:"=estate",building:"=building",area:"=area",equipment:"=equipment",parentEntity:"=parentEntity",guid:"=guid",restrictEdit:"=restrictEdit",useList:"=useList",inline:"=inline"},controller:["$scope","$modal","ngTableParams","Repository","$rootScope","TranslationService","$localStorage","ListService","Constants","$q","CommonService",controller],link:function(scope,element,attrs){},templateUrl:"app/condition/views/conditionDirective.html"}})}(),function(){function controller($scope,$modalInstance,params,repository,ngTableParams,translationService,registeredFieldService,listService,$localStorage){var isSVV="SvvTunnel"===$localStorage.generalOptions.CustomerId||"Fylkeskommuner"===$localStorage.generalOptions.CustomerId;registeredFieldService.getRegisteredField(repository.commonService.prefix.Condition).then(function(result){var equipmentMandatory=_.find(result,{DomainFieldName:"GuidEquipment"}).Mandatory,areaMandatory=_.find(result,{DomainFieldName:"GuidArea"}).Mandatory,buildingMandatory=_.find(result,{DomainFieldName:"GuidBuilding"}).Mandatory;$scope.selectedEntityType="Equipment",$scope.showSelection=!0,equipmentMandatory?($scope.showEquipment=!0,$scope.showArea=!1,$scope.showBuilding=!1,$scope.showEstate=!1,$scope.showSelection=!1):areaMandatory?($scope.showArea=!0,$scope.showEquipment=!1,$scope.showBuilding=!1,$scope.showEstate=!1,$scope.showSelection=!1,$scope.selectedEntityType="Area"):buildingMandatory?($scope.showBuilding=!0,$scope.showEquipment=!0,$scope.showArea=!0,$scope.showEstate=!1,$scope.selectedEntityType="Building"):($scope.showEstate=!0,$scope.showEquipment=!0,$scope.showBuilding=!0,$scope.showArea=!0)}),$scope.equipmentColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Building.Id",sortable:!0},{Position:2,Title:translationService.translate("web-building-description"),Property:"Building.Description"},{Position:3,Title:translationService.translate("web-equipment-id"),Property:"Id"},{Position:4,Title:translationService.translate("web-equipment-description"),Property:"Description"}],isSVV&&$scope.equipmentColumns.push({Position:5,Title:translationService.translate("web-equipment-text20-svv","Driftsmerking"),Property:"Text20"}),$scope.areaColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Building.Id",sortable:!0},{Position:2,Title:translationService.translate("web-building-description"),Property:"Building.Description"},{Position:3,Title:translationService.translate("web-area-id"),Property:"Id"},{Position:4,Title:translationService.translate("web-area-description"),Property:"Description"}],$scope.buildingColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Id",sortable:!0},{Position:2,Title:translationService.translate("web-building-description"),Property:"Description"}],$scope.estateColumns=[{Position:1,Title:translationService.translate("web-estate-id"),Property:"Id",sortable:!0},{Position:2,Title:translationService.translate("web-estate-description"),Property:"Description"}],$scope.columns=[];var getFilter=function(baseFilter){var filter={searchString:baseFilter.searchString,hasConditionControl:!0,PropertyFilter:[]};switch($scope.selectedEntityType){case"Estate":params.guidBuilding?filter.PropertyFilter.push({Property:"Buildings.Guid",Operator:"=",Value:params.guidBuilding}):params.guidEstate&&filter.PropertyFilter.push({Property:"Guid",Operator:"=",Value:params.guidEstate});break;case"Building":params.guidBuilding?filter.PropertyFilter.push({Property:"Guid",Operator:"=",Value:params.guidBuilding}):params.guidEstate&&filter.PropertyFilter.push({Property:"GuidEstate",Operator:"=",Value:params.guidEstate});break;case"Area":case"Equipment":params.guidBuilding?filter.PropertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:params.guidBuilding}):params.guidEstate&&filter.PropertyFilter.push({Property:"Building.GuidEstate",Operator:"=",Value:params.guidEstate})}return"Equipment"===$scope.selectedEntityType&&filter.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:!1}),filter};$scope.items=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:getFilter({})},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){$scope.columns=[];var filter=getFilter(params.filter()),url=repository.apiData.equipment.url,columnProperties=[];switch($scope.selectedEntityType){case"Estate":url=repository.apiData.estate.url,$scope.estateColumns.forEach(function(column){$scope.columns.push(column)});break;case"Building":url=repository.apiData.building.url,$scope.buildingColumns.forEach(function(column){$scope.columns.push(column)});break;case"Area":url=repository.apiData.area.url,$scope.areaColumns.forEach(function(column){$scope.columns.push(column)}),columnProperties.push("Building.Estate.Guid");break;case"Equipment":url=repository.apiData.equipment.url,$scope.equipmentColumns.forEach(function(column){$scope.columns.push(column)}),columnProperties.push("Building.Estate.Guid")}$scope.columns.forEach(function(col){columnProperties.push(col.Property)}),repository.GetPaginated(url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columnProperties)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.$watch("selectedEntityType",function(newValue,oldValue){newValue!==oldValue&&newValue&&$scope.items.reload()}),$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)},$scope.selectedEntities=[];var getEntityMapping=function(entity){var newEntity={GuidWorkOrder:params.guidWorkOrder,Type:"UnderInspection"};if(entity.Prefix)switch(entity.Prefix){case"Estate":newEntity.GuidEstate=entity.Guid;break;case"Building":newEntity.GuidBuilding=entity.Guid;break;case"Area":newEntity.GuidArea=entity.Guid;break;case"Equipment":newEntity.GuidEquipment=entity.Guid}else newEntity.GuidEquipment=entity.Guid;return entity.GuidEstate&&(newEntity.GuidEstate=entity.GuidEstate),entity.Building&&entity.Building.Estate&&(newEntity.GuidEstate=entity.Building.Estate.Guid),entity.GuidBuilding&&(newEntity.GuidBuilding=entity.GuidBuilding),entity.GuidArea&&(newEntity.GuidArea=entity.GuidArea),entity.GuidEquipment&&(newEntity.GuidEquipment=entity.GuidEquipment),newEntity};$scope.saveEntities=function(){var model=[];$scope.items.filter().type;$scope.selectedEntities.forEach(function(entity){model.push(getEntityMapping(entity))}),repository.createMultiple(repository.apiData.condition.url,model).then(function(result){repository.growl(translationService.translate("condition-addMultiple-success","Objektene har blitt lagt til"),"success"),$modalInstance.close("OK")},function(error){repository.growl(error,"danger")})},$scope.addEntity=function(entity){if(_.find($scope.selectedEntities,function(o){return entity.Guid===o.Guid})){for(var i=0;i<$scope.selectedEntities.length;i++)if($scope.selectedEntities[i].Guid===entity.Guid)return void $scope.selectedEntities.splice(i,1)}else $scope.selectedEntities.push(entity)},$scope.isEntitySelected=function(guid){return _.find($scope.selectedEntities,function(o){return guid===o.Guid})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CreateConditionForInspectionController",["$scope","$modalInstance","params","Repository","ngTableParams","TranslationService","RegisteredFieldService","ListService","$localStorage",controller])}(),function(){function controller($scope,repository,$stateParams,translationService){$scope.isUpdate="conditionType.edit"===$scope.navigation.current.name,$scope.model={Guid:$stateParams.guid,LikertScale:0};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.ConditionType,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ConditionType,checkOtherDO) }else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.ConditionType),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ConditionType)};$scope.isUpdate&&repository.getSingle(repository.apiData.conditionType.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess(),$scope.reload=!0},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-conditionType-success","Tilstandstypen ble oppdatert."):translationService.translate("create-conditionType-success","Tilstandstypen ble opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.conditionType.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.conditionType.url,$scope.model).then(success).catch(error)},$scope.remove=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-conditionType-message","Tilstandstypen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-conditionType-button-confirm","Ja, fjern tilstandstypen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.conditionType.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-conditionType-success","Tilstandstypen ble fjernet!"),result,"success"),$scope.goBack("conditionType.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.isNumber=function(value){return angular.isNumber(value)&&!isNaN(value)}}angular.module("Plania").controller("ConditionTypeController",["$scope","Repository","$stateParams","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService){$scope.isUpdate="consequence.edit"===$scope.navigation.current.name,$scope.model={Guid:$stateParams.guid,LikertScale:0};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Consequence,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Consequence,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Consequence),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Consequence)};$scope.isUpdate&&repository.getSingle(repository.apiData.consequence.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess(),$scope.reload=!0},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-consequence-success","Konsekvensgrad ble oppdatert."):translationService.translate("create-conditionType-success","Konsekvensgraden ble opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.consequence.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.consequence.url,$scope.model).then(success).catch(error)},$scope.remove=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-consequence-message","Konsekvensgraden vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-consequence-button-confirm","Ja, fjern konsekvensgraden!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.consequence.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-consequence-success","Konsekvensgraden ble fjernet!"),result,"success"),$scope.goBack("consequence.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.isNumber=function(value){return angular.isNumber(value)&&!isNaN(value)}}angular.module("Plania").controller("ConsequenceController",["$scope","Repository","$stateParams","TranslationService",controller])}(),function(){function controller($scope,$modalInstance,params,repository,translationService){$scope.isUpdate=params.guid,$scope.header=$scope.isUpdate?translationService.translate("contactPerson-title-edit","Rediger kontaktperson"):translationService.translate("contactPerson-title-create","Legg til kontaktperson"),$scope.model={},$scope.model.GuidSupplier=params.guidSupplier,$scope.model.GuidCustomer=params.guidCustomer,$scope.isUpdate&&repository.getSingle(repository.apiData.contactPerson.url,params.guid).then(function(response){var result=response.Data;$scope.model=result,$scope.model.PostalCode=result.PostalCode+"\n",$scope.reload=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)}),$scope.saveContactPerson=function(){$scope.isUpdate?repository.updateSingle(repository.apiData.contactPerson.url,$scope.model).then(function(result){repository.growl("Kontakt har blitt oppdatert","success"),$modalInstance.close()}):repository.createSingle(repository.apiData.contactPerson.url,$scope.model).then(function(result){repository.growl("Kontakt har blitt lagret","success"),$modalInstance.close()})},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.onPostCodeSelect=function(postalInfo){postalInfo?($scope.model.GuidPost=postalInfo.Guid,$scope.model.PostalCode=postalInfo.ZipCode,$scope.model.PostalArea=postalInfo.PostalArea,$scope.postalInfo=postalInfo):($scope.model.PostalCode="",$scope.model.PostalArea="",$scope.model.GuidPost="")}}angular.module("Plania").controller("ContactPersonController",["$scope","$modalInstance","params","Repository","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,ngTableParams,translationService,$localStorage,listService){$scope.isUpdate=RegExp("edit$").test($scope.navigation.current.name),$scope.showCustomer=!0,$scope.viewMode=!!$scope.isUpdate,$scope.model={Guid:$stateParams.guid},$scope.activateAutocomplete=!1,$scope.validCharacters="^(?!.*<[a-zA-ZæøåÆØÅ]+).*",$scope.isDocumentsCollapsed=!0,$scope.reloadDocumentTable=!1,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Contract,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Contract,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Contract),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Contract)};updateAccess();var contractColumns=["Invoicing.Id","Department.Id","Department.Description"];$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.contractItemColumns=[{Position:1,Title:translationService.translate("web-contractItem-Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-contractItem-Description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-contractItem-Quantity"),Property:"Quantity",PropertyType:"number"},{Position:4,Title:translationService.translate("web-contractItem-UnitPrice"),Property:"UnitPrice",PropertyType:"number"},{Position:4,Title:translationService.translate("web-contractItem-article-type"),Property:"Article.Type",PropertyType:"enum"}];var getCardTables=function(){$scope.contractItemTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{PropertyFilter:[{Property:"GuidContract",Operator:"=",Value:$scope.model.Guid}]}},{total:0,counts:[10,20,50],filterDelay:10,paginationMaxBlocks:6,getData:function($defer,params){var columns=[];$scope.contractItemColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.contractItem.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.contractItemTable.settings().total=result.TotalCount,$scope.contractItemTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})};if($scope.isUpdate)repository.getSingle(repository.apiData.contract.url,$stateParams.guid,JSON.stringify(contractColumns)).then(function(response){var responseData=response.Data;$scope.model=responseData,$scope.reloadDocumentTable=!0,updateAccess(),getCardTables(),$scope.reload=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")});else{if($stateParams.showPersistantData){var persistentData=repository.persistedData.getPersistedData("contract.create");persistentData&&($scope.model=persistentData.model||{})}$scope.model.RentalType=2,!$scope.model.GuidPaymentTerm&&$localStorage.generalOptions.GuidDefaultPaymentTerm&&($scope.model.GuidPaymentTerm=$localStorage.generalOptions.GuidDefaultPaymentTerm),!$scope.model.GuidInvoicing&&$localStorage.generalOptions.GuidDefaultInvoicing&&($scope.model.GuidInvoicing=$localStorage.generalOptions.GuidDefaultInvoicing),!$scope.model.GuidPaymentOrderForm&&$localStorage.generalOptions.GuidDefaultPaymentOrderForm&&($scope.model.GuidPaymentOrderForm=$localStorage.generalOptions.GuidDefaultPaymentOrderForm),setTimeout(function(){$scope.activateAutocomplete=!0},250)}$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?"Kontrakt ble oppdatert":"Kontrakt ble lagret","success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),"reinvoicingContract.create"===destination?$scope.navigation.go(destination,{reload:!0}):(repository.persistedData.clearPersistedData(),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid}))},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.contract.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.contract.url,$scope.model).then(success).catch(error)},$scope.cancel=function(){$scope.goBack("reinvoicingContract.list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.addContractItem=function(){$modal.open({templateUrl:"app/contract/views/contractItemModal.html",controller:"ContractItemModalController",size:"md",resolve:{params:function(){return{contractItem:{GuidContract:$scope.model.Guid,GuidDataOwner:repository.commonService.getFilterData().selectedDataOwner.Guid,Quantity:1}}}}}).result.then(function(){$scope.contractItemTable.reload()})},$scope.removeConctractItem=function(item){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-contract-contract-item-remove","Kontraktsobjektet vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-contract-contract-item-confirm","Ja, fjern kontraktsobjektet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.contractItem.url,item.Guid).then(function(result){swal("Suksess!",translationService.translate("web-swal-contract-contract-item-success","Kontraktsobjektet ble fjernet!"),"success"),$scope.contractItemTable.reload()})})},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"contractCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}},$scope.updateContractItem=function(guid){$modal.open({templateUrl:"app/contract/views/contractItemModal.html",controller:"ContractItemModalController",size:"md",resolve:{params:function(){return{Guid:guid}}}}).result.then(function(){$scope.contractItemTable.reload()})}}angular.module("Plania").controller("ContractController",["$scope","Repository","$stateParams","$modal","ngTableParams","TranslationService","$localStorage","ListService","$sce",controller])}(),function(){function controller($scope,$modalInstance,params,repository,translationService,ngTableParams,ListService){$scope.isUpdate=!!params.Guid,$scope.model={},$scope.modelDto={},$scope.activateAutocomplete=!1;var columns=[];(function(){return repository.getSingle(repository.apiData.contractItem.url,$scope.isUpdate?params.Guid:"00000000-0000-0000-0000-000000000000",JSON.stringify(columns))})().then(function(response){var contractItem=$scope.isUpdate?response.Data:params.contractItem;$scope.model=contractItem,$scope.fieldRules=response.FieldRules,$scope.reload=!0,$scope.activateAutocomplete=!0},function(error){repository.growl(error,"danger")}),$scope.onArticleSelect=function(article){$scope.model.Id=article.Id,$scope.model.Description=article.Description,$scope.model.GuidArticle=article.Guid,$scope.model.UnitPrice=article.UnitPrice,$scope.model.Unit=article.Unit,$scope.model.GuidDepartment=article.GuidDepartment,$scope.model.GuidAccount=article.GuidAccount,$scope.model.GuidAccounting0=article.GuidAccounting0,$scope.model.GuidAccounting1=article.GuidAccounting1,$scope.model.GuidAccounting2=article.GuidAccounting2,$scope.model.GuidAccounting3=article.GuidAccounting3,$scope.model.GuidAccounting4=article.GuidAccounting4},$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-contractItem-success","Kontrakt objekt har blitt oppdatert."):translationService.translate("create-contractItem-success","Kontrakt objekt har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;$modalInstance.close(),destination&&$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.contractItem.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.contractItem.url,$scope.model).then(success,error)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("ContractItemModalController",["$scope","$modalInstance","params","Repository","TranslationService","ngTableParams","ListService",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,ngTableParams,translationService,$localStorage,listService){$scope.isUpdate=RegExp("edit$").test($scope.navigation.current.name),$scope.showCustomer=!0,$scope.generalOptions=$localStorage.generalOptions,$scope.viewMode=!!$scope.isUpdate,$scope.model={Guid:$stateParams.guid},$scope.activateAutocomplete=!1,$scope.validCharacters="^(?!.*<[a-zA-ZæøåÆØÅ]+).*",$scope.isDynamicPropertiesCollapsed=!1,$scope.isDocumentsCollapsed=!0,$scope.reloadDocumentTable=!1,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Contract,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Contract,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Contract),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Contract)};updateAccess();var contractColumns=["Invoicing.Id","Department.Id","Department.Description","ContractCategory.Description","ContractAdjustment.ExplanatoryText","ContractAdjustment.PeriodicityNumber","ContractAdjustment.PeriodicityUnit","ContractAdjustment.AdjustmentDate","ContractAdjustment.Adjustment.Id","PaymentTerm.Id","PaymentOrderForm.Id","PeriodOfNotice.Id","Invoicing.Id","Customer.Description","Customer.Telephone","Customer.Email","Customer.PostalAddress","Customer.StreetAddress","Customer.PostalCode","Customer.PostalArea","Customer.Country","Customer.CellPhone","Area.Id","Area.Description","Area.Address","Area.Building.PostalCode","Area.Building.PostalArea","Area.Building.Country","Area.AreaCategory.Description"];if($scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.isUpdate)repository.getSingle(repository.apiData.contract.url,$stateParams.guid,JSON.stringify(contractColumns)).then(function(response){var responseData=response.Data;$scope.model=responseData,$scope.reloadDocumentTable=!0,updateAccess(),$scope.newDynamicProperty=$scope.model.DynamicProperty,$scope.reload=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")});else{if($stateParams.showPersistantData){var persistentData=repository.persistedData.getPersistedData("contract.create");persistentData&&($scope.model=persistentData.model||{}),$scope.model.RentalType=2}$scope.activateAutocomplete=!0,$scope.model.RentalType=2}$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?"Kontrakt ble oppdatert":"Kontrakt ble lagret","success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),"housingContract.create"===destination?$scope.navigation.go(destination,{reload:!0}):(repository.persistedData.clearPersistedData(),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid}))},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.contract.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.contract.url,$scope.model).then(success).catch(error)},$scope.onContractCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidContractCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidContractCategory=category.Guid},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"contractCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}},$scope.cancel=function(){$scope.goBack("housingContract.list",{menuGuid:$scope.navigation.params.menuGuid})}}angular.module("Plania").controller("HousingContractController",["$scope","Repository","$stateParams","$modal","ngTableParams","TranslationService","$localStorage","ListService","$sce",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,ngTableParams,translationService,listService){$scope.isUpdate="contractCategory.edit"===$scope.navigation.current.name,$scope.model={};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.ContractCategory,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ContractCategory,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.ContractContract),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ContractContract)};$scope.isUpdate&&repository.getSingle(repository.apiData.contractCategory.url,$stateParams.guid).then(function(response){$scope.model=response.Data,$scope.reload=!0,updateAccess()},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-contract-type-success","Kontrakt kategori har blitt oppdatert."):translationService.translate("create-contract-category-success","Kontrakt kategori har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.contractCategory.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.contractCategory.url,$scope.model).then(success,error)}}angular.module("Plania").controller("ContractCategoryController",["$scope","Repository","$stateParams","$modal","ngTableParams","TranslationService","ListService",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,ngTableParams,translationService,listService){$scope.isUpdate="contractType.edit"===$scope.navigation.current.name,$scope.model={};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.ContractType,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ContractType,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.ContractType),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ContractType)};$scope.isUpdate&&repository.getSingle(repository.apiData.contractType.url,$stateParams.guid).then(function(response){$scope.model=response.Data,$scope.reload=!0,updateAccess()},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-contract-type-success","Kontrrakt type har blitt oppdatert."):translationService.translate("create-contract-type-success","Kontrakt type har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.contractType.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.contractType.url,$scope.model).then(success,error)}}angular.module("Plania").controller("ContractTypeController",["$scope","Repository","$stateParams","$modal","ngTableParams","TranslationService","ListService",controller])}(),function(){function controller($scope,$modalInstance,params,repository,ngTableParams,translationService,listService,$q,$localStorage){var isSVV="SvvTunnel"===$localStorage.generalOptions.CustomerId||"Fylkeskommuner"===$localStorage.generalOptions.CustomerId;$scope.tabs=[{heading:translationService.translate("web-controlList-chooseControlList","Velg Kontrolliste"),step:1},{heading:translationService.translate("web-controlList-chooseObject","Velg Objekt"),step:2}],$scope.step=$scope.update?2:1,$scope.setCurrentStep=function(step){$(".tab-content").css("overflow","hidden"),setTimeout(function(){$(".tab-content").css("overflow","visible")},500),$scope.step=step},$scope.equipmentColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Building.Id",sortable:!0},{Position:2,Title:translationService.translate("web-building-description"),Property:"Building.Description"},{Position:3,Title:translationService.translate("web-equipment-id"),Property:"Id"},{Position:4,Title:translationService.translate("web-equipment-description"),Property:"Description"},{Position:5,Title:translationService.translate("web-equipment-equipmentcategory"),Property:"EquipmentCategory.Description"}],isSVV&&$scope.equipmentColumns.push({Position:6,Title:translationService.translate("web-equipment-text20-svv","Driftsmerking"),Property:"Text20"}),$scope.areaColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Building.Id",sortable:!0},{Position:2,Title:translationService.translate("web-building-description"),Property:"Building.Description"},{Position:3,Title:translationService.translate("web-area-id"),Property:"Id"},{Position:4,Title:translationService.translate("web-area-description"),Property:"Description"},{Position:5,Title:translationService.translate("web-area-areacategory"),Property:"AreaCategory.Description"},{Position:6,Title:translationService.translate("web-area-rentalStatus"),Property:"RentalStatus",PropertyType:"enum.AreaRentalStatus"}],$scope.controlListColumns=[{Position:1,Title:translationService.translate("web-controlList-id","Id"),Property:"Id"},{Position:2,Title:translationService.translate("web-controlList-name","Name"),Property:"Name"},{Position:3,Title:translationService.translate("web-controlList-description","Beskrivelse"),Property:"Description"}],$scope.columns=[],$scope.selectedEntities=[];var paramsFromWorkOrder=angular.copy(params),controlListFilter={VersionContext:"PublishedVersions",FilterModel:{Condition:"or",Rules:[{Property:"UseWithArea",Operator:"=",Value:!0},{Property:"UseWithWorkOrder",Operator:"=",Value:!0},{Property:"UseWithEquipment",Operator:"=",Value:!0}]}};$scope.controlListTable=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:controlListFilter},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){var columns=[];$scope.controlListColumns.forEach(function(column){columns.push(column.Property)}),columns.push("UseWithWorkOrder","UseWithArea","UseWithEquipment"),repository.GetPaginated(repository.apiData.controlList.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}});var getDefaultEntityType=function(selectedControlList,params){if(params.guidEquipment&&selectedControlList.UseWithEquipment)return"Equipment";if(params.guidArea&&selectedControlList.UseWithArea)return"Area";if(!selectedControlList.UseWithWorkOrder){if(selectedControlList.UseWithEquipment)return"Equipment";if(selectedControlList.UseWithArea)return"Area"}return"Workorder"};$scope.chooseControlList=function(item){$scope.isSaving||($scope.selectedControlList=item,$scope.selectedEntities=[],paramsFromWorkOrder=angular.copy(params),!item.UseWithWorkOrder||item.UseWithArea||item.UseWithEquipment?($scope.selectedEntityType=getDefaultEntityType(item,params),$scope.setCurrentStep(2)):$scope.save(!0))};var getFilter=function(baseFilter){var filter={searchString:baseFilter.searchString,PropertyFilter:[]};return params.guidBuilding?filter.PropertyFilter=[{Property:"GuidBuilding",Operator:"=",Value:params.guidBuilding}]:params.guidEstate&&(filter.PropertyFilter=[{Property:"Building.GuidEstate",Operator:"=",Value:params.guidEstate}]),"Equipment"===$scope.selectedEntityType&&filter.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:!1}),filter};$scope.items=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{}},{total:0,counts:[10,25,50,200],paginationMaxBlocks:5,getData:function($defer,params){if($scope.selectedEntityType){$scope.columns=[],$scope.includeGuid=null;var filter=getFilter(params.filter()),url=repository.apiData.equipment.url,columnProperties=[];switch($scope.selectedEntityType){case"Area":url=repository.apiData.area.url,$scope.areaColumns.forEach(function(column){$scope.columns.push(column)}),paramsFromWorkOrder.guidArea&&($scope.includeGuid=paramsFromWorkOrder.guidArea,paramsFromWorkOrder.guidArea=null);break;case"Equipment":url=repository.apiData.equipment.url,$scope.equipmentColumns.forEach(function(column){$scope.columns.push(column)}),paramsFromWorkOrder.guidEquipment&&($scope.includeGuid=paramsFromWorkOrder.guidEquipment,paramsFromWorkOrder.guidEquipment=null)}$scope.columns.forEach(function(col){columnProperties.push(col.Property)}),repository.GetPaginated(url,params.page()-1,params.count(),params.sorting(),filter,$scope.includeGuid,JSON.stringify(columnProperties)).then(function(result){if(params.total(result.TotalCount),$scope.includeGuid){$scope.selectedEntities=[];var selectionFromParams=_.find(result.List,function(o){return o.Guid===$scope.includeGuid});selectionFromParams&&$scope.selectedEntities.push(selectionFromParams)}$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}}),$scope.$watch("selectedEntityType",function(newValue,oldValue){newValue!==oldValue&&($scope.selectedEntities=[],newValue&&"Workorder"!==newValue&&$scope.items.reload())}),$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)};var getEntityMapping=function(entity){var newEntity={GuidWorkOrder:params.guidWorkOrder,GuidPeriodicTask:params.guidPeriodicTask,GuidControlList:$scope.selectedControlList.Guid};if(entity.Prefix)switch(entity.Prefix){case"Area":newEntity.GuidArea=entity.Guid;break;case"Equipment":newEntity.GuidEquipment=entity.Guid}return newEntity};$scope.addEntity=function(entity){if(_.find($scope.selectedEntities,function(o){return entity.Guid===o.Guid})){for(var i=0;i<$scope.selectedEntities.length;i++)if($scope.selectedEntities[i].Guid===entity.Guid)return void $scope.selectedEntities.splice(i,1)}else $scope.selectedEntities.push(entity)},$scope.save=function(savingDirectlyToWo){var model=[];if($scope.selectedEntities.length>0)$scope.selectedEntities.forEach(function(entity){model.push(getEntityMapping(entity))});else{if(!savingDirectlyToWo&&"Workorder"!==$scope.selectedEntityType)return void repository.growl(translationService.translate("controlList-addMultiple-noneselected","Velg en eller flere rader i listen"),"danger");model.push({GuidWorkOrder:params.guidWorkOrder,GuidPeriodicTask:params.guidPeriodicTask,GuidControlList:$scope.selectedControlList.Guid})}var promises=[];model.forEach(function(m){ promises.push(repository.createSingle(repository.apiData.controlListXEntity.url,m))}),$scope.isSaving=!0,$q.all(promises).then(function(){repository.growl(translationService.translate("controlList-addMultiple-success","Kontrollistene har blitt lagt til"),"success"),$scope.isSaving=!1,$modalInstance.close("OK")},function(error){$scope.isSaving=!1,repository.growl(error,"danger")})},$scope.isEntitySelected=function(guid){return _.find($scope.selectedEntities,function(o){return guid===o.Guid})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("AddControlListModalController",["$scope","$modalInstance","params","Repository","ngTableParams","TranslationService","ListService","$q","$localStorage",controller])}(),function(){function controller($scope,repository,params,modalInstance,translationService,$q,$modal,$filter,$anchorScroll,$location,focus,$window,$timeout,$localStorage,registeredFieldService,$rootScope,colorService,iconService){function isHidden(item){var itemRules=_.filter($scope.controlListRules,function(o){return o.GuidControlListItem===item.GuidControlListItem&&"Hide"===o.Action});return!(!itemRules||0===itemRules.length)&&evaluateItemRules(itemRules)}function evaluateItemRules(itemRules){var conditionResult=!1;return itemRules.forEach(function(itemRule){itemRule.Conditions.Filter.forEach(function(filter){var filterItem=_.find($scope.controlListItemAnswers,function(o){return o.GuidControlListItem.toLowerCase()===filter.GuidControlListItem.toLowerCase()});if(filterItem){evaluateCondition($scope.getValueFromItem(filterItem),filter.Operator,filter.Value,filterItem.ControlListItem.Type)&&(conditionResult=!0)}else shownError||(repository.growl("Feil i kontrolliste - et eller flere kontrollistepunkt kan ikke vises","danger"),shownError=!0)})}),conditionResult}var isSVV="SvvTunnel"===$localStorage.generalOptions.CustomerId||"Fylkeskommuner"===$localStorage.generalOptions.CustomerId;$scope.isBBY=$localStorage.generalOptions.IsBBY;var answerColumns=["Value","ValueInt","ValueDate","ValueBool","ValueString","ValueDouble","UserUpdatedBy.RealName","UpdatedDate","ControlListItem.Name","ControlListItem.Data","ControlListItem.IsMandatory","ControlListItem.Type","LinkedDeviations","LinkedRequests"];$scope.completedControlPoints=0,$scope.totalAvailableControlPoints=0,$scope.workOrder=params.workOrder,$scope.controlList=params.controlList,$scope.controlListXEntity=params.controlListXEntity,$scope.restrictEdit=params.restrictEdit,$scope.newDeviations=[],$scope.newRequests=[],$scope.lastUpdatedBy=null,$scope.lastUpdatedDate=null,$scope.isArray=angular.isArray,$scope.isNotExecutedTabVisible=!1,$scope.enableWebNavigation=$rootScope.userInfo.enableWebNavigation,$scope.equipmentNavigationState=repository.apiData.equipment.navigationState,$scope.housingNavigationState=repository.apiData.housing.navigationState,$scope.areaNavigationState=repository.apiData.area.navigationState,$scope.buildingNavigationState=repository.apiData.building.navigationState,$scope.forms={},$scope.activeTabs={controlListItems:!0,images:!1,notExecutedInfo:!1},$scope.isPreview=params.isPreview,$scope.iconColor=colorService.getContrastText($scope.controlList.Color),$scope.icon=iconService.getIcon($scope.controlList.Icon)||"fa-file",$scope.isNullOrEmpty=function(value){return _.isUndefined(value)||_.isNull(value)||""===value},$scope.getLowestEntityCaption=function(){if($scope.controlListXEntity.Equipment){var extraText="";return isSVV&&$scope.controlListXEntity.Equipment&&$scope.controlListXEntity.Equipment.Text20&&(extraText=" - "+$scope.controlListXEntity.Equipment.Text20),$scope.getEntityCaption($scope.controlListXEntity.Equipment)+extraText}return $scope.controlListXEntity.Area?$scope.getEntityCaption($scope.controlListXEntity.Area):$scope.controlListXEntity.Building?$scope.getEntityCaption($scope.controlListXEntity.Building):$scope.controlListXEntity.Estate?$scope.getEntityCaption($scope.controlListXEntity.Estate):translationService.translate("web-workorder")+" "+params.workOrderCaption},repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix.ControlListItemAnswer).then(function(result){$scope.controlListItemAnswerFieldRules=result,$scope.reload=!0}),$scope.isPreview?($scope.controlListRules=params.controlListRules,$scope.controlListItemAnswers=params.controlListItemAnswers,$scope.totalAvailableControlPoints=_.filter($scope.controlListItemAnswers,function(o){return"CheckBox"!==o.ControlListItem.Type&&"SectionHeader"!==o.ControlListItem.Type&&"Info"!==o.ControlListItem.Type}).length):(repository.GetPaginated(repository.apiData.controlListRule.url,0,1e3,{},{PropertyFilter:[{Property:"GuidControlList",Operator:"=",Value:$scope.controlList.Guid}]},"").then(function(response){$scope.controlListRules=response.List,$scope.controlListRules.forEach(function(item){item.Conditions&&(item.Conditions=JSON.parse(item.Conditions)),item.Parameters&&(item.Parameters=JSON.parse(item.Parameters))}),repository.GetPaginated(repository.apiData.controlListItemAnswer.url,0,1e3,{"ControlListItem.IndexPosition":"asc"},{PropertyFilter:[{Property:"GuidControlListXEntity",Operator:"=",Value:$scope.controlListXEntity.Guid}]},"",JSON.stringify(answerColumns)).then(function(response){$scope.totalAvailableControlPoints=_.filter(response.List,function(o){return"CheckBox"!==o.ControlListItem.Type&&"SectionHeader"!==o.ControlListItem.Type&&"Info"!==o.ControlListItem.Type}).length,$scope.controlListItemAnswers=response.List,$scope.controlListItemAnswers.forEach(function(item){item.ControlListItem.Data&&(item.ControlListItem.Data=JSON.parse(item.ControlListItem.Data))}),$scope.controlListItemAnswers.forEach(function(item){$scope.itemValueChanged(item),$scope.lastUpdatedDate?moment(item.UpdatedDate).isAfter(moment($scope.lastUpdatedDate))&&($scope.lastUpdatedBy=item.UserUpdatedBy?item.UserUpdatedBy.RealName:"Server",$scope.lastUpdatedDate=item.UpdatedDate):($scope.lastUpdatedBy=item.UserUpdatedBy?item.UserUpdatedBy.RealName:"Server",$scope.lastUpdatedDate=item.UpdatedDate)})})}),repository.GetPaginated(repository.apiData.imageXEntity.url,0,100,{},{PropertyFilter:[{Property:"GuidControlListXEntity",Operator:"=",Value:$scope.controlListXEntity.Guid}]},"",JSON.stringify(["IsDefault","Image.Guid","Image.Id","Image.Description","Image.FileName","ControlListItemAnswer.ControlListItem.Name"])).then(function(response){$scope.controlListImages=response.List,$scope.controlListImages.forEach(function(imgXEntity){imgXEntity.Image&&(imgXEntity.Image.IsDefault=imgXEntity.IsDefault),imgXEntity.timestamp=(new Date).toISOString()})})),$scope.hasCollapseRule=function(item){var result=!1,itemRules=_.filter($scope.controlListRules,{GuidControlListItem:item.GuidControlListItem});return!!itemRules&&(itemRules.forEach(function(itemRule){"Show"!==itemRule.Action&&"Hide"!==itemRule.Action||(result=!0)}),result)};var shownError=!1;$scope.isCollapsed=function(item){var itemRules=_.filter($scope.controlListRules,function(o){return o.GuidControlListItem===item.GuidControlListItem&&("Show"===o.Action||"Hide"===o.Action)});if(!itemRules||0===itemRules.length)return!1;var conditionResult=evaluateItemRules(itemRules);return"Show"===itemRules[itemRules.length-1].Action&&(conditionResult=!conditionResult),item.isCollapsed=conditionResult,$scope.totalAvailableControlPoints=_.filter($scope.controlListItemAnswers,function(item){return!item.isCollapsed&&"Info"!==item.ControlListItem.Type&&"CheckBox"!==item.ControlListItem.Type&&"SectionHeader"!==item.ControlListItem.Type}).length,conditionResult},$scope.getValueFromItem=function(itemAnswer){if(!itemAnswer)return null;switch(itemAnswer.ControlListItem.Type){case"Text":case"TextArea":case"Combo":case"Radio":return itemAnswer.ValueString;case"Numeric":return itemAnswer.ValueDouble;case"CheckBox":return itemAnswer.ValueBool;case"Date":return itemAnswer.ValueDate;case"Checklist":return itemAnswer.Value;default:return itemAnswer.ValueString}},$scope.showChecklistComment=function(item){return!(!item||!item.Value)&&item.Value.toLowerCase()===translationService.translate("web-controllist-answer-NotOk","Ikke Ok").toLowerCase()};var evaluateCondition=function(left,operator,right,type){if(void 0===left||null===left)return!1;if("Numeric"===type&&""===left&&"="!==operator&&"<>"!==operator)return!1;switch(operator){case"=":return"Date"===type?moment(left).isSame(right,"day"):"Numeric"===type?$scope.isNullOrEmpty(right)?$scope.isNullOrEmpty(left):left===right:left.toString().toLowerCase()===right.toString().toLowerCase();case"<>":return"Date"===type?!moment(left).isSame(right,"day"):"Numeric"===type?$scope.isNullOrEmpty(right)?!$scope.isNullOrEmpty(left):left!==right:left.toString().toLowerCase()!==right.toString().toLowerCase();case">":return"Date"===type?moment(left).isAfter(right,"day"):"Numeric"===type?left>right:left.toString().toLowerCase()>right.toString().toLowerCase();case"<":return"Date"===type?moment(left).isBefore(right,"day"):"Numeric"===type?left=":return"Date"===type?moment(left).isSameOrAfter(right,"day"):"Numeric"===type?left>=right:left.toString().toLowerCase()>=right.toString().toLowerCase();case"<=":return"Date"===type?moment(left).isSameOrBefore(right,"day"):"Numeric"===type?left<=right:left.toString().toLowerCase()<=right.toString().toLowerCase()}};$scope.$watch("controlListItemAnswers",function(newValue,oldValue){if(newValue!==oldValue){var counter=0;$scope.controlListItemAnswers.forEach(function(item){if(!item.isCollapsed&&"CheckBox"!==item.ControlListItem.Type){var value=$scope.getValueFromItem(item);"Numeric"===item.ControlListItem.Type?$scope.isNullOrEmpty(value)||counter++:value&&counter++}}),$scope.completedControlPoints=counter,updateProgress()}},!0);var updateProgress=function(){var max=$scope.totalAvailableControlPoints,type="",percentFill=$scope.completedControlPoints/max*100;percentFill<100?type="info":100===percentFill&&(type="success"),$scope.progressbarType=type};$scope.itemValueChanged=function(item){$scope.controlListXEntity.ClosedDate||$scope.restrictEdit||(item.hasAction=!1,checkDeviationAction(item),checkRequestAction(item))};var hasValue=function(itemAnswer){return!!itemAnswer.isCollapsed||!!$scope.getValueFromItem(itemAnswer)};$scope.hasMandatoryEmptyFields=function(sectionHeaderItem){if(!sectionHeaderItem||!sectionHeaderItem.isCollapsed)return!1;for(var thisSectionHeaderIndex=_.findIndex($scope.controlListItemAnswers,function(o){return o.Guid===sectionHeaderItem.Guid}),itemAnswers=[],i=thisSectionHeaderIndex+1;$scope.controlListItemAnswers.length>i;i++){if("SectionHeader"===$scope.controlListItemAnswers[i].ControlListItem.Type){i;break}"Info"!==$scope.controlListItemAnswers[i].ControlListItem.Type&&itemAnswers.push($scope.controlListItemAnswers[i])}if(0===itemAnswers.length)return!1;for(var result=!1,j=0;itemAnswers.length>j;j++)if(itemAnswers[j].ControlListItem.IsMandatory&&!hasValue(itemAnswers[j])){result=!0;break}return result},$scope.save=function(action){if(!$scope.isPreview){var itemAnswers=[];$scope.controlListItemAnswers.forEach(function(item){if(!item.isCollapsed){var postItem=angular.copy(item);delete postItem.ControlListItem,delete postItem.User,itemAnswers.push(postItem)}}),repository.updateMultiple(repository.apiData.controlListItemAnswer.urlUpdateMultiple,itemAnswers).then(function(result){$scope.forms.controlListForm.$setPristine(),"approve"===action?$scope.newDeviations.length>0?$scope.openControlListDeviationConfirmation($scope.newDeviations,!0):$scope.newRequests.length>0?$scope.openControlListRequestConfirmation($scope.newRequests,!0):approveControlListXEntity():"close"===action?modalInstance.close():"notExecuted"===action&&setNotExecuted()},function(error){swal("Error",error,"error")})}};var approveControlListXEntity=function(createdDeviations){if(!$scope.isPreview){var putData=angular.copy($scope.controlListXEntity);putData.ClosedDate=(new Date).toISOString(),putData.GuidUserClosedBy=$scope.userInfo.guidUser,putData.GuidReferenceDataNotExecuted=null,putData.NotExecutedComment=null,delete putData.ReferenceDataNotExecuted,repository.updateSingle(repository.apiData.controlListXEntity.url,putData).then(function(response){$scope.controlListXEntity=response,modalInstance.close(createdDeviations)},function(error){$scope.newDeviations=[],swal("Error",error,"error")})}},setRuleParameters=function(item,rule){rule&&rule.Guid&&(item.GuidRule=rule.Guid),rule&&rule.Parameters&&rule.Parameters.forEach(function(parameter){if(parameter.IsExpandable)if(parameter.GuidProperty)if("string"==typeof parameter.Value)switch(parameter.Value){case"@LoggedInPerson":var guidPerson=repository.authService.getUserData().guidPerson;if(!guidPerson)break;item[parameter.GuidProperty]=guidPerson;var nameOfPerson=[repository.authService.getUserData().personFirstName,repository.authService.getUserData().personLastName].filter(function(text){return null!==text&&void 0!==text&&""!==text}).join(" ");item[parameter.Property]={Guid:guidPerson,Caption:nameOfPerson}}else item[parameter.GuidProperty]=parameter.Value.Guid;else parameter.Value&&(item["Guid"+parameter.Property]=parameter.Value.Guid);else if($scope.isArray(parameter.Value)){var texts=[];parameter.Value.forEach(function(guid){if(guid&&isGuid(guid)){var answer=_.find($scope.controlListItemAnswers,{GuidControlListItem:guid.toLowerCase()}),answerValue=$scope.getValueFromItem(answer);"Date"===answer.ControlListItem.Type&&answerValue&&"string"==typeof answerValue&&(answerValue=$filter("date")(answerValue,"dd.MM.yyyy HH:mm:ss")),texts.push([answer.ControlListItem.Name,answerValue].filter(function(text){return void 0!==text&&null!==text}).join(" - "))}});var maxLength,resultingText=texts.join("\n");if("Deviation"===rule.Action||"ClosedDeviation"===rule.Action){var deviationActionCommentRule=registeredFieldService.getLocalRegisteredField(repository.apiData.deviation.prefix,"ActionComment");deviationActionCommentRule&&(maxLength=deviationActionCommentRule.MaxLength||1024)}if(maxLength&&resultingText.length>maxLength){var breakStringText="-- Tekst avbrutt --";resultingText=resultingText.substring(0,maxLength),resultingText=resultingText.substring(0,resultingText.length-breakStringText.length)+breakStringText}item[parameter.Property]=resultingText}else if(isGuid(parameter.Value)){var answer=_.find($scope.controlListItemAnswers,{GuidControlListItem:parameter.Value.toLowerCase()});item[parameter.Property]=$scope.getValueFromItem(answer)}else item[parameter.Property]=parameter.Value})},setEntityConnection=function(item){!item.Equipment&&$scope.controlListXEntity.Equipment&&(item.Equipment=$scope.controlListXEntity.Equipment,$scope.controlListXEntity.Equipment.Building&&(item.Building=$scope.controlListXEntity.Equipment.Building,item.GuidBuilding=$scope.controlListXEntity.Equipment.Building.Guid,$scope.controlListXEntity.Equipment.Building.Estate&&(item.Estate=$scope.controlListXEntity.Equipment.Building.Estate,item.GuidEstate=$scope.controlListXEntity.Equipment.Building.Estate.Guid))),!item.Area&&$scope.controlListXEntity.Area&&(item.Area=$scope.controlListXEntity.Area,$scope.controlListXEntity.Area.Building&&(item.Building=$scope.controlListXEntity.Area.Building,item.GuidBuilding=$scope.controlListXEntity.Area.Building.Guid,$scope.controlListXEntity.Area.Building.Estate&&(item.Estate=$scope.controlListXEntity.Area.Building.Estate,item.GuidEstate=$scope.controlListXEntity.Area.Building.Estate.Guid))),item.GuidEstate||item.GuidBuilding||item.GuidEquipment||item.GuidArea||($scope.workOrder.Estate&&(item.Estate=$scope.workOrder.Estate,item.GuidEstate=$scope.workOrder.GuidEstate),$scope.workOrder.Building&&(item.Building=$scope.workOrder.Building,item.GuidBuilding=$scope.workOrder.GuidBuilding),$scope.workOrder.Equipment&&(item.Equipment=$scope.workOrder.Equipment,item.GuidEquipment=$scope.workOrder.GuidEquipment),$scope.workOrder.Area&&(item.Area=$scope.workOrder.Area,item.GuidArea=$scope.workOrder.GuidArea))},isGuid=function(stringToTest){return!!stringToTest&&/^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$/gi.test(stringToTest)};$scope.reopen=function(){$scope.isPreview||($scope.controlListXEntity.ClosedDate=null,$scope.controlListXEntity.GuidUserClosedBy=null,$scope.controlListXEntity.GuidReferenceDataNotExecuted=null,$scope.controlListXEntity.NotExecutedComment=null,delete $scope.controlListXEntity.ReferenceDataNotExecuted,repository.updateSingle(repository.apiData.controlListXEntity.url,$scope.controlListXEntity).then(function(response){$scope.controlListXEntity.Status=response.Status,$scope.isNotExecutedTabVisible=!1,$scope.activeTabs.notExecutedInfo=!1,$scope.activeTabs.controlListItems=!0},function(error){swal("Error",error,"error")}))},$scope.showNotExecutedTab=function(){$scope.isNotExecutedTabVisible=!0,$scope.activeTabs.notExecutedInfo=!0};var setNotExecuted=function(){if(!$scope.isPreview&&$scope.controlListXEntity.ControlList.GuidReferenceTypeNotExecuted&&!$scope.isSaving){if(!$scope.controlListXEntity.GuidReferenceDataNotExecuted)return void swal({title:translationService.translate("web-swal-controlListXEntity-missingReferenceData-title","Må velge en årsak"),text:translationService.translate("web-swal-controlListXEntity-missingReferenceData-text","Årsak må bli valg for å sette en kontrolliste til ikke utført."),type:"warning",showCancelButton:!1,confirmButtonColor:"#ff9800",confirmButtonText:translationService.translate("web-swal-controlListXEntity-missingReferenceData-okButton","Ok"),closeOnConfirm:!0});var putData=angular.copy($scope.controlListXEntity);putData.ClosedDate=(new Date).toISOString(),putData.GuidUserClosedBy=$scope.userInfo.guidUser,$scope.isSaving=!0,repository.updateSingle(repository.apiData.controlListXEntity.url,putData).then(function(response){$scope.controlListXEntity=response,$scope.isSaving=!1,modalInstance.close()},function(error){$scope.isSaving=!1,swal("Error",error,"error")})}};$scope.getReferenceDataColumns=function(){return[{Title:translationService.translate("web-controlListXEntity-referenceData-indexPosition","Indeks"),Property:"IndexPosition"},{Title:translationService.translate("web-controlListXEntity-referenceData-id","Id"),Property:"Id"},{Title:translationService.translate("web-controlListXEntity-referenceData-description","Beskrivelse"),Property:"Description"}]},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"referenceData":return filter.FilterModel={Condition:"and",Rules:[{Property:"GuidReferenceType",Operator:"=",Value:$scope.controlListXEntity.ControlList.GuidReferenceTypeNotExecuted},{Condition:"or",Rules:[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null}]}]},filter}},$scope.photoColumnSize=6,$scope.photoColumn="col-md-"+$scope.photoColumnSize,$scope.photoOptions=[{value:4,column:3},{value:6,column:2},{value:12,column:1}],$scope.showImages=function(){return!!$scope.hasModule("ControlList")&&$scope.controlList.UseImage},$scope.photoGrid=function(size){$scope.photoColumn="col-md-"+size,$scope.photoColumnSize=size},$scope.addImage=function(item){$modal.open({templateUrl:"app/document/views/createImageModal.html",controller:"CreateDocumentXEntityController",size:"lg",resolve:{params:function(){return{guidControlListItemAnswer:item?item.Guid:null,guidControlListXEntity:$scope.controlListXEntity.Guid,controlListItemAnswers:$scope.controlListItemAnswers}}}}).result.then(function(images){images&&images.forEach(function(image){var newImage={GuidImage:image.Guid,IsDefault:image.IsDefault,Image:{Guid:image.Guid,Description:image.Description,IsDefault:image.IsDefault}};image.GuidControlListItemAnswer&&(newImage.GuidControlListItemAnswer=image.GuidControlListItemAnswer,newImage.ControlListItemAnswer=_.find($scope.controlListItemAnswers,{Guid:image.GuidControlListItemAnswer})),image.GuidControlListXEntity&&(newImage.GuidControlListXEntity=image.GuidControlListXEntity),$scope.controlListImages.push(newImage),repository.growl("Bilde lagt til kontrolliste","success")})},function(msg){})};var onChange=function(image){$scope.controlListImages.forEach(function(imgXEntity){image.IsDefault&&imgXEntity.GuidImage!==image.Guid&&(imgXEntity.IsDefault=!1,imgXEntity.Image&&(imgXEntity.Image.IsDefault=!1)),imgXEntity.GuidImage===image.Guid&&(imgXEntity.IsDefault=image.IsDefault,imgXEntity.IsAttachment=image.IsAttachment,imgXEntity.Image&&(imgXEntity.Image.IsDefault=image.IsDefault,imgXEntity.Image.IsAttachment=image.IsAttachment))}),$scope.controlListImages=_.sortBy($scope.controlListImages,function(img){return!img.IsDefault})};$scope.editImage=function(imageXref,$index){$modal.open({templateUrl:"app/document/views/editImageModal.html",controller:"EditImageController",size:"lg",resolve:{params:function(){return{image:imageXref.Image,guidEntity:imageXref.GuidControlListItemAnswer||imageXref.GuidControlListXEntity,deleteAccess:$scope.hasDeleteAccess("ImageXEntity")&&!$scope.controlListXEntity.ClosedDate,onChange:onChange}}}}).result.then(function(result){"Deleted"===result?$scope.controlListImages.splice($index,1):(planiaUtils.copyProperties(result,imageXref.Image),$scope.controlListImages.splice($index,1),imageXref.timestamp=(new Date).toISOString(),$scope.controlListImages.splice($index,0,imageXref))})};var currentFocusedItem;$scope.goToNextEmptyItem=function(){var newHash,nextElement,emptyElements=_.filter($scope.controlListItemAnswers,function(o){var value=$scope.getValueFromItem(o);return"Numeric"===o.ControlListItem.Type?$scope.isNullOrEmpty(value):!value&&"Info"!==o.ControlListItem.Type&&"SectionHeader"!==o.ControlListItem.Type});if(emptyElements.length<1)return void(currentFocusedItem=null);var emptyNotHiddenElements=[];if(_.forEach(emptyElements,function(emptyElem){isHidden(emptyElem)||emptyNotHiddenElements.push(emptyElem)}),currentFocusedItem&&1!==emptyNotHiddenElements.length){var currentElementIndex=_.findIndex(emptyNotHiddenElements,function(o){return o.Guid===currentFocusedItem.Guid});nextElement=currentElementIndex+1===emptyNotHiddenElements.length?emptyNotHiddenElements[0]:emptyNotHiddenElements[currentElementIndex+1]}else nextElement=emptyNotHiddenElements[0];nextElement&&(currentFocusedItem=nextElement,newHash=nextElement.Guid,$location.hash(newHash),$anchorScroll(),focus(newHash))},$scope.cancel=function(reason){$scope.forms.controlListForm.$dirty&&!$scope.isPreview?swal({title:translationService.translate("web-swal-error-unsavedChanges","Du har endringer som ikke er lagret!"),text:translationService.translate("web-swal-closeWithoutsaving","Ønsker du å lukke uten å lagre?"),type:"warning",showCancelButton:!0,confirmButtonColor:"#ff9800",confirmButtonText:translationService.translate("web-button-closewithoutsaving","Lukk uten å lagre"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){modalInstance.dismiss(!0)}):modalInstance.dismiss(!1)},$scope.printControlList=function(printImages){if(!$scope.isPreview){$localStorage.reportParams=JSON.stringify({Guid:$scope.controlListXEntity.Guid,PrintImages:printImages});var urlFriendlyControlListName=$scope.controlList.Name?$scope.controlList.Name.replace(/[^a-zA-Z0-9]+/g,""):"",url=$scope.navigation.href("report.print",{reportName:"Plania.API.Reports.ControlListPrint, Plania.API="+urlFriendlyControlListName});$timeout(function(){$window.open(url,"_blank")},100)}};var checkDeviationAction=function(item){if(!(item.LinkedDeviations&&item.LinkedDeviations.length>0)){if($scope.isCollapsed(item)){return _.filter($scope.controlListRules,function(o){return o.GuidControlListItem===item.GuidControlListItem&&("Deviation"===o.Action||"ClosedDeviation"===o.Action)}).forEach(function(rule){rule&&_.remove($scope.newDeviations,function(o){return o.GuidRule===rule.Guid})}),void("Checklist"===item.ControlListItem.Type&&_.remove($scope.newDeviations,function(o){return void 0===o.GuidRule&&o.GuidControlListItemAnswer===item.Guid}))}if($scope.modifyDeviation(item),"Checklist"===item.ControlListItem.Type)if(item.Value&&item.Value.toLowerCase()===translationService.translate("web-controllist-answer-NotOk","Ikke Ok").toLowerCase()){var deviationInfo={deviationType:item.ControlListItem.Data.DeviationType,guidDeviationType:item.ControlListItem.Data.GuidDeviationType,actionComment:item.ValueString};$scope.newDeviations.push(addNewDeviation(item,null,deviationInfo)),item.hasAction=!0}else _.remove($scope.newDeviations,function(o){return void 0===o.GuidRule&&o.GuidControlListItemAnswer===item.Guid})}};$scope.modifyDeviation=function(item){if(!(item.LinkedDeviations&&item.LinkedDeviations.length>0)){_.filter($scope.controlListRules,function(o){return o.GuidControlListItem===item.GuidControlListItem&&("Deviation"===o.Action||"ClosedDeviation"===o.Action)}).forEach(function(rule){if(rule){var conditionResult;if(rule.Conditions.Filter.forEach(function(filter){var filterItem=_.find($scope.controlListItemAnswers,function(o){return o.GuidControlListItem.toLowerCase()===filter.GuidControlListItem.toLowerCase()});conditionResult=evaluateCondition($scope.getValueFromItem(filterItem),filter.Operator,filter.Value,filterItem.ControlListItem.Type)}),!0===conditionResult){var existingDeviation=_.findIndex($scope.newDeviations,function(o){return o.GuidRule===rule.Guid});-1!==existingDeviation?$scope.newDeviations[existingDeviation]=addNewDeviation(item,rule):$scope.newDeviations.push(addNewDeviation(item,rule)),item.hasAction=!0}else _.remove($scope.newDeviations,function(o){return o.GuidRule===rule.Guid})}})}};var addNewDeviation=function(item,rule,deviationInfo){var deviation={IsMandatory:!rule||rule.IsMandatory,Status:0,GuidControlListItemAnswer:item.Guid,GuidWorkOrder:$scope.controlListXEntity.GuidWorkOrder,GuidArea:$scope.controlListXEntity.GuidArea,GuidEquipment:$scope.controlListXEntity.GuidEquipment,Remarks:item.ControlListItem.Name+" - "+("Date"===item.ControlListItem.Type?$filter("date")($scope.getValueFromItem(item),"dd.MM.yyyy"):$scope.getValueFromItem(item))};return deviationInfo&&(deviation.DeviationType=deviationInfo.deviationType?{Caption:deviationInfo.deviationType}:null,deviation.GuidDeviationType=deviationInfo.guidDeviationType,deviation.ActionComment=deviationInfo.actionComment),rule&&"ClosedDeviation"===rule.Action&&(deviation.CloseOnCreation=!0,deviation.canCloseOnCreation=!0),setRuleParameters(deviation,rule),setEntityConnection(deviation),deviation};$scope.openDeviation=function(deviation){$modal.open({templateUrl:"app/deviation/views/editDeviationModal.html",controller:"DeviationController",resolve:{$stateParams:function(){return{guid:deviation.Guid,isModal:!0,parentEntity:$scope.workOrder}}}}).result.then(function(){},function(){})},$scope.openControlListDeviationConfirmation=function(deviations,approve){approve||$scope.save(),deviations.forEach(function(deviation){var item=_.find($scope.controlListItemAnswers,{Guid:deviation.GuidControlListItemAnswer});$scope.modifyDeviation(item)}),deviations.forEach(function(deviation){var item=_.find($scope.controlListItemAnswers,{Guid:deviation.GuidControlListItemAnswer});"Checklist"===item.ControlListItem.Type&&(deviation.ActionComment=item.ValueString);var images=_.filter($scope.controlListImages,function(image){return image.GuidControlListItemAnswer===item.Guid});images.length>0&&(deviation.Images=images)}),$modal.open({templateUrl:"app/controlList/views/ControlListDeviationConfirmationModal.html",controller:"ControlListDeviationConfirmationController",size:"lg",resolve:{params:function(){return{inWorkOrder:!0,deviations:deviations,isPreview:$scope.isPreview}}}}).result.then(function(result){$scope.isPreview||(angular.copy(deviations).forEach(function(deviation){if(deviation.Id){var answer=_.find($scope.controlListItemAnswers,function(o){return o.Guid===deviation.GuidControlListItemAnswer});answer&&(answer.LinkedDeviations?answer.LinkedDeviations.push(deviation):answer.LinkedDeviations=[deviation],_.remove($scope.newDeviations,function(o){return o.GuidControlListItemAnswer===answer.Guid}),$scope.itemValueChanged(answer))}}),approve&&$scope.newRequests.length<1?approveControlListXEntity(!0):approve&&$scope.newRequests.length>0&&$scope.openControlListRequestConfirmation($scope.newRequests,approve))})};var checkRequestAction=function(item){if(!(item.LinkedRequests&&item.LinkedRequests.length>0)){if($scope.isCollapsed(item)){return void _.filter($scope.controlListRules,function(o){return o.GuidControlListItem===item.GuidControlListItem&&"Request"===o.Action}).forEach(function(rule){rule&&_.remove($scope.newRequests,function(o){return o.GuidRule===rule.Guid})})}$scope.modifyRequest(item)}},addNewRequest=function(item,rule){var request={IsMandatory:!!rule&&rule.IsMandatory,GuidControlListItemAnswer:item.Guid,GuidArea:$scope.controlListXEntity.GuidArea,GuidEquipment:$scope.controlListXEntity.GuidEquipment,ExplanatoryText:item.ControlListItem.Name+" - "+("Date"===item.ControlListItem.Type?$filter("date")($scope.getValueFromItem(item),"dd.MM.yyyy"):$scope.getValueFromItem(item))},userData=$localStorage.userData;return userData.guidPerson?request.ContactPerson=userData.personFirstName+" "+userData.personLastName:request.ContactPerson=userData.realName,userData.email&&(request.EmailAddress=userData.email),userData.phone&&(request.Telephone=userData.phone),setRuleParameters(request,rule),setEntityConnection(request),request};$scope.modifyRequest=function(item){if(!(item.LinkedRequests&&item.LinkedRequests.length>0)){_.filter($scope.controlListRules,function(o){return o.GuidControlListItem===item.GuidControlListItem&&"Request"===o.Action}).forEach(function(rule){if(rule){var conditionResult;if(rule.Conditions.Filter.forEach(function(filter){var filterItem=_.find($scope.controlListItemAnswers,function(o){return o.GuidControlListItem.toLowerCase()===filter.GuidControlListItem.toLowerCase()});conditionResult=evaluateCondition($scope.getValueFromItem(filterItem),filter.Operator,filter.Value,filterItem.ControlListItem.Type)}),!0===conditionResult){var existingRequest=_.findIndex($scope.newRequests,function(o){return o.GuidRule===rule.Guid});-1!==existingRequest?$scope.newRequests[existingRequest]=addNewRequest(item,rule):$scope.newRequests.push(addNewRequest(item,rule)),item.hasAction=!0}else _.remove($scope.newRequests,function(o){return o.GuidRule===rule.Guid})}})}},$scope.openControlListRequestConfirmation=function(requests,approve){approve||$scope.save(),requests.forEach(function(request){var item=_.find($scope.controlListItemAnswers,{Guid:request.GuidControlListItemAnswer});$scope.modifyRequest(item)}),requests.forEach(function(request){var item=_.find($scope.controlListItemAnswers,{Guid:request.GuidControlListItemAnswer}),images=_.filter($scope.controlListImages,function(image){return image.GuidControlListItemAnswer===item.Guid});images.length>0&&(request.Images=images)}),$modal.open({templateUrl:"app/controlList/views/controlListRequestConfirmationModal.html",controller:"ControlListRequestConfirmationController",size:"lg",resolve:{params:function(){return{inWorkOrder:!0,requests:requests,isPreview:$scope.isPreview}}}}).result.then(function(result){$scope.isPreview||(approve&&approveControlListXEntity(!0),angular.copy(requests).forEach(function(request){if(request.Id){var answer=_.find($scope.controlListItemAnswers,function(o){return o.Guid===request.GuidControlListItemAnswer});answer&&(answer.LinkedRequests?answer.LinkedRequests.push(request):answer.LinkedRequests=[request],_.remove($scope.newRequests,function(o){return o.GuidControlListItemAnswer===answer.Guid}),$scope.itemValueChanged(answer))}}))})};var preview=function(printChoice){$scope.forms.controlListForm.$dirty&&!$scope.isPreview?swal({title:translationService.translate("web-swal-error-unsavedChanges","Du har endringer som ikke er lagret!"), text:translationService.translate("web-swal-previewWithoutsaving","Ønsker du å forhåndsvise uten å lagre?"),type:"warning",showCancelButton:!0,confirmButtonColor:"#ff9800",confirmButtonText:translationService.translate("web-button-previewwithoutsaving","Forhåndsvis uten å lagre"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){$scope.printControlList(printChoice)}):$scope.printControlList(printChoice)};$scope.printControlListContextMenu=function(){var options=[],noImagesText=$scope.controlListXEntity.ClosedDate?translationService.translate("web-controlListCompletion-printControlList-noImages","Print kontrolliste uten bilder"):translationService.translate("web-controlListCompletion-previewControlList-noImages","Forhåndsvis kontrolliste uten bilder"),inLineText=$scope.controlListXEntity.ClosedDate?translationService.translate("web-controlListCompletion-printControlList-withImagesInLine","Print kontrolliste med bilder på linje"):translationService.translate("web-controlListCompletion-previewControlList-withImagesInLine","Forhåndsvis kontrolliste med bilder på linje"),attachmentText=$scope.controlListXEntity.ClosedDate?translationService.translate("web-controlListCompletion-printControlList-withImagesAsAttachment","Print kontrolliste med bilder på slutten"):translationService.translate("web-controlListCompletion-previewControlList-withImagesAsAttachment","Forhåndsvis kontrolliste med bilder på slutten");return options.push({html:' '+noImagesText+"",click:function($itemScope,$event,modelValue,text,$li){preview("None")}}),options.push({html:' '+inLineText+"",click:function($itemScope,$event,modelValue,text,$li){preview("InLine")}}),options.push({html:' '+attachmentText+"",click:function($itemScope,$event,modelValue,text,$li){preview("Attachment")}}),options}}angular.module("Plania").controller("ControlListCompletionModalController",["$scope","Repository","params","$modalInstance","TranslationService","$q","$modal","$filter","$anchorScroll","$location","focus","$window","$timeout","$localStorage","RegisteredFieldService","$rootScope","ColorService","IconService",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,translationService,$location,$timeout,colorService){$scope.isUpdate="controlList.edit"===$scope.navigation.current.name,$scope.model={Guid:$stateParams.guid},$scope.activateAutocomplete=!1,$scope.selectedFormItem=null,$scope.copyOfSelectedItem={},$scope.conditionColumns=[],$scope.previewControlListXEntityObject=null;var availableHashLocations=["#info","#connections","#history","#answers","#setup"],updateLocation=function(){var hash=window.location.hash;hash&&availableHashLocations.includes(hash)?($('#controlListTabs a[data-target="'+hash+'"]').tab("show"),$scope.currentTab=hash.substr(1)):($('#controlListTabs a[data-target="#info"]').tab("show"),$scope.currentTab="info")};$scope.$on("$locationChangeSuccess",function(event,newUrl,oldUrl){updateLocation()}),$scope.setTab=function(tab){$location.hash(tab).replace()},$scope.isUpdate&&$stateParams.tab?($scope.setTab($stateParams.tab),updateLocation()):updateLocation();var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.ControlList,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ControlList,checkOtherDO),"Draft"!==$scope.model.VersionStatus&&($scope.restrictEdit=!0,$scope.restrictDelete=!0)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.ControlList),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ControlList)};updateAccess();var columns=["ReferenceTypeNotExecuted.Id","ReferenceTypeNotExecuted.Description"],parseControlListItems=function(){$scope.model.ControlListItems?$scope.model.ControlListItems.forEach(function(item){item.Data&&(item.Data=JSON.parse(item.Data))}):$scope.model.ControlListItems=[]},parseControlListRules=function(){$scope.model.ControlListRules?$scope.model.ControlListRules.forEach(function(item){item.Conditions&&(item.Conditions=JSON.parse(item.Conditions)),item.Parameters&&(item.Parameters=JSON.parse(item.Parameters))}):$scope.model.ControlListRules=[]},parseConditions=function(){$scope.model.Conditions&&($scope.conditionColumns=JSON.parse($scope.model.Conditions))};(function(){return repository.getMainModel(repository.apiData.controlList.url,$scope.isUpdate?$stateParams.guid:"00000000-0000-0000-0000-000000000000",JSON.stringify(columns)+($stateParams.guidEntityToCopy?"&GuidCopyFrom="+$stateParams.guidEntityToCopy:""))})().then(function(response){var controlList=response.Data;$scope.model=controlList,$scope.model.Color&&($scope.model.Color=colorService.convertToRainbow($scope.model.Color)),$scope.reload=!0,$scope.isUpdate&&(parseControlListItems(),parseControlListRules(),parseConditions()),$scope.model.canSetNotExecuted=!!$scope.model.GuidReferenceTypeNotExecuted,updateAccess(),$timeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){"Draft"===$scope.model.VersionStatus&&$scope.saveCurrentItem(function(){var modelCopy=angular.copy($scope.model);$scope.conditionColumns&&$scope.conditionColumns.length>0?modelCopy.Conditions=angular.toJson($scope.conditionColumns):modelCopy.Conditions=void 0,delete modelCopy.ControlListItems,delete modelCopy.ControlListRules;var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-controlList-success","Kontrollisten ble oppdatert"):translationService.translate("create-controlList-success","Kontrollisten ble opprettet"),"success"),repository.commonService.setLastRegisterGuid(destination,result.Guid);var hash=window.location.hash;hash&&(hash=hash.substr(1)),$scope.goBack(destination,{guid:result.Guid,menuGuid:$scope.navigation.params.menuGuid,tab:hash})},error=function(error){repository.growl(error,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.controlList.url,modelCopy).then(success).catch(error):repository.createSingle(repository.apiData.controlList.url,modelCopy).then(success).catch(error)})},$scope.delete=function(){"Draft"===$scope.model.VersionStatus&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-controlList-message","Kontrollisten vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-controlList-button-confirm","Ja, fjern kontrollisten"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.deleteSingle(repository.apiData.controlList.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-controlList-success","Kontrollisten ble fjernet!"),result,"success"),$scope.goBack("controlList.list",{menuGuid:$scope.navigation.params.menuGuid})},function(error){var swalMessage=error.Message;error.IsDeactivateable&&(swalMessage+="

    Vil du deaktivere kontrollisten?"),swal({title:translationService.translate("web-swal-controlList-delete-error-title","Kunne ikke slette kontrollisten!"),text:swalMessage,type:"error",html:!0,showCancelButton:!0,confirmButtonText:error.IsDeactivateable?"Deaktiver":"Ok",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.IsDeactivated=!0,$scope.model.Name="#"+$scope.model.Name,$scope.update("controlList.list"))})})})},$scope.openPreview=function(usePreviousEntity){function openPreview(){var tempControlListItemAnswers=[];$scope.model.ControlListItems.forEach(function(item){tempControlListItemAnswers.push({Guid:planiaUtils.randomString(16),User:{RealName:$scope.userInfo.realName},UpdatedDate:(new Date).toISOString(),GuidControlListItem:item.Guid,ControlListItem:item,LinkedDeviations:[],LinkedRequests:[]})});var workOrder=$scope.previewControlListXEntityObject.WorkOrder;workOrder||(workOrder={Caption:"Forhåndsvisning"}),$modal.open({templateUrl:"app/controlList/views/controlListCompletionModal.html",size:"xl",controller:"ControlListCompletionModalController",resolve:{params:function(){return{controlList:$scope.model,controlListXEntity:$scope.previewControlListXEntityObject,controlListRules:$scope.model.ControlListRules,controlListItemAnswers:tempControlListItemAnswers,workOrder:workOrder,workOrderCaption:workOrder.Caption,isPreview:!0}}}})}usePreviousEntity&&$scope.previewControlListXEntityObject?openPreview():$modal.open({templateUrl:"app/controlList/views/controlListPreviewEntitySelectionModal.html",size:"md",controller:"ControlListPreviewEntitySelectionModalController",resolve:{params:function(){return{controlList:$scope.model}}}}).result.then(function(result){$scope.previewControlListXEntityObject={GuidControlList:$scope.model.Guid,Status:"New"},result.workOrder&&($scope.previewControlListXEntityObject.GuidWorkOrder=result.workOrder.Guid,$scope.previewControlListXEntityObject.WorkOrder=result.workOrder),result.equipment&&($scope.previewControlListXEntityObject.GuidEquipment=result.equipment.Guid,$scope.previewControlListXEntityObject.Equipment=result.equipment),result.area&&($scope.previewControlListXEntityObject.GuidArea=result.area.Guid,$scope.previewControlListXEntityObject.Area=result.area),openPreview()},function(){})},$scope.saveCurrentItem=function(thenFunction){if("Draft"===$scope.model.VersionStatus){if(!$scope.selectedFormItem||angular.equals($scope.selectedFormItem,$scope.copyOfSelectedItem))return void(thenFunction&&thenFunction());var objectToSave=angular.copy($scope.selectedFormItem);objectToSave.Data&&(objectToSave.Data=JSON.stringify(objectToSave.Data)),objectToSave.ControlListLogItem&&objectToSave.ControlListLogItem.Id&&(objectToSave.ControlListLogItem.Id=objectToSave.ControlListLogItem.Id.trim()),repository.updateSingle(repository.apiData.controlListItem.url,objectToSave).then(function(result){thenFunction&&thenFunction()}).catch(function(error){repository.growl(error,"danger")})}},$scope.copyControlList=function(){$modal.open({templateUrl:"app/controlList/views/controlListCopyModal.html",controller:"ControlListCopyController",resolve:{params:function(){return{model:angular.copy($scope.model)}}}}).result.then(function(result){result.GuidCopyFrom=$scope.model.Guid,repository.createSingle(repository.apiData.controlList.url,result).then(function(response){$scope.navigation.go("controlList.edit",{guid:response.Guid})},function(error){repository.growl(error,"danger")})})},$scope.takeDraft=function(){"Published"===$scope.model.VersionStatus&&$modal.open({templateUrl:"app/controlList/views/controlListCreateDraftModal.html",size:"md",controller:"ControlListCreateDraftModalController",resolve:{params:function(){return{guids:[$scope.model.Guid]}}}}).result.then(function(){$scope.goBack("controlList.edit",{guid:$scope.model.Guid})},function(){})},$scope.publishDraft=function(){"Draft"===$scope.model.VersionStatus&&$modal.open({templateUrl:"app/controlList/views/controlListPublishModal.html",size:"md",controller:"ControlListPublishModalController",resolve:{params:function(){return{model:angular.copy($scope.model)}}}}).result.then(function(){$scope.goBack("controlList.edit",{guid:$scope.model.Guid})},function(){})},$scope.revertDraft=function(){"Draft"===$scope.model.VersionStatus&&swal({title:translationService.translate("web-controlList-revertDraft-title","Forkast alle endringer i utkastet?"),text:translationService.translate("web-controlList-revertDraft-text","Alle endringer for gjeldende utkast vil forsvinne med ingen muligheter å gjennopprette."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-controlList-revertDraft-confirm","Ja"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.runAction(repository.apiData.controlList.endpoint.revertDraft+$scope.model.Guid).then(function(response){repository.growl(translationService.translate("web-controlList-revertDraft-success","Utkastet er reversert til sist publisert"),"success"),swal.close(),$scope.goBack("controlList.edit",{guid:$scope.model.Guid})},function(error){repository.showError(error),swal.close()})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("ControlListController",["$scope","Repository","$stateParams","$modal","TranslationService","$location","$timeout","ColorService",controller])}(),function(){function controller($scope,$modalInstance,params){$scope.model={Color:params.model.Color,Icon:params.model.Icon,IsMandatory:params.model.IsMandatory,UseImage:params.model.UseImage,UseWithArea:params.model.UseWithArea,UseWithEquipment:params.model.UseWithEquipment,UseWithWorkOrder:params.model.UseWithWorkOrder,GuidReferenceTypeNotExecuted:params.model.GuidReferenceTypeNotExecuted,Conditions:params.model.Conditions},$scope.ok=function(){$modalInstance.close($scope.model)},$scope.cancel=function(){$modalInstance.dismiss("cancel")}}angular.module("Plania").controller("ControlListCopyController",["$scope","$modalInstance","params",controller])}(),function(){function controller($scope,$modalInstance,repository,params){$scope.VersionComment="",$scope.isRunningAction=!1,$scope.guids=params.guids;var firstGuid=$scope.guids[0];$scope.createDraft=function(){$scope.isRunningAction=!0;var dto={VersionComment:null};""!==$scope.VersionComment.trim()&&(dto.VersionComment=$scope.VersionComment),repository.runAction(repository.apiData.controlList.endpoint.takeDraft+firstGuid,dto,null,!0).then(function(response){$scope.isRunningAction=!1,$modalInstance.close()},function(error){$scope.isRunningAction=!1,repository.showError(error)})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("ControlListCreateDraftModalController",["$scope","$modalInstance","Repository","params",controller])}(),function(){function controller($scope,repository,params,registeredFieldService,modalInstance,translationService,$localStorage){$scope.deviations=params.deviations,$scope.selectedDeviation=$scope.deviations[0],$scope.selectedDeviationIndex=0,$scope.inWorkOrder=params.inWorkOrder,$scope.reload=!1,$scope.viewMode=!1,$scope.activateAutocomplete=!0,$scope.isEdit=!1,$scope.parentEntity="WorkOrder",$scope.isPreview=params.isPreview,$scope.isModal=!0,$scope.extendedDeviationControl=$localStorage.generalOptions.ExtendedDeviationControl,$scope.deviations.forEach(function(deviation){if(deviation.GuidEquipment&&!deviation.GuidBuilding){var equipmentColumns=["Building.Id","Building.Description","Building.Estate.Id","Building.Estate.Description","Building.Estate.Guid"];repository.getSingle(repository.apiData.equipment.url,deviation.GuidEquipment,JSON.stringify(equipmentColumns)).then(function(response){var equipment=response.Data;deviation.GuidBuilding=equipment.GuidBuilding,deviation.Building=equipment.Building,deviation.GuidEstate=equipment.Building.Estate.Guid,deviation.Estate=equipment.Building.Estate},function(error){})}}),$scope.deviationCauses=[],function(){var filter={FilterModel:{Condition:"and",Rules:[{Property:"ReferenceType.Context",Operator:"=",Value:"DeviationCause"}]}};repository.GetPaginated(repository.apiData.referenceData.url,0,-1,{IndexPosition:"asc"},filter).then(function(response){$scope.deviationCauses=response.List.map(function(data){return data.Caption})})}(),$scope.processingSectionVisibility=!0,registeredFieldService.getRegisteredField(repository.commonService.prefix.Deviation).then(function(registeredFields){var fields=["GuidPriority","PriorityComment","DeadlineDate"];$scope.extendedDeviationControl&&fields.push("GuidResponsiblePerson","CausalAnalysis","RiskOfRepetition","GuidClassificationReference");var visibility={};fields.forEach(function(field){var rule=_.filter(registeredFields,{DomainFieldName:field})[0];visibility[field]=!!rule&&!!rule.Mandatory}),Object.values(visibility).every(function(value){return!1===value})?$scope.processingSectionVisibility=!1:$scope.processingSectionVisibility=visibility}),$scope.removeDeviation=function(index){$scope.deviations.splice(index,1),$scope.deviations.length>0?$scope.selectDeviation($scope.deviations[0]):$scope.deviations.length<1&&($scope.selectedDeviation=null)},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"building":return $scope.selectedDeviation.GuidEstate&&(filter.PropertyFilter=[{Property:"GuidEstate",Operator:"=",Value:$scope.selectedDeviation.GuidEstate}]),filter;case"area":return filter={GuidBuilding:$scope.selectedDeviation.GuidBuilding?$scope.selectedDeviation.GuidBuilding:null},$scope.selectedDeviation.GuidEstate&&(filter.PropertyFilter=[{Property:"Building.GuidEstate",Operator:"=",Value:$scope.selectedDeviation.GuidEstate}]),filter;case"equipment":if(filter={GuidBuilding:$scope.selectedDeviation.GuidBuilding,hasConditionControl:!0,PropertyFilter:[]},$scope.selectedDeviation.GuidEstate&&!$scope.selectedDeviation.GuidBuilding&&(filter.PropertyFilter=[{Property:"Building.GuidEstate",Operator:"=",Value:$scope.selectedDeviation.GuidEstate}]),$localStorage.generalOptions.FilterDeviationByEqPrefix&&$scope.selectedDeviation.GuidDeviationType){var id=$scope.selectedDeviation.DeviationType.Caption.substr(0,3).trim();filter.PropertyFilter.push({Property:"Id",Operator:"StartsWith",Value:id})}return filter.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:!1}),filter;case"deviationType":return $localStorage.generalOptions.FilterDeviationByEqPrefix&&$scope.selectedDeviation.GuidEquipment?{PropertyFilter:[{Property:"Id",Operator:"StartsWith",Value:$scope.selectedDeviation.Equipment.Caption.substr(0,3).trim()}]}:{};case"deviationClassification":return filter.FilterModel={Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null}]},{Property:"ReferenceType.Context",Operator:"=",Value:"DeviationClassification"}]},filter;default:return{}}},$scope.selectDeviation=function(deviation,index){deviation.hasBeenViewed=!0,$scope.selectedDeviation=deviation,$scope.selectedDeviationIndex=index},$scope.selectNextDeviation=function(){var currentDeviationIndex=$scope.selectedDeviationIndex;currentDeviationIndex+1===$scope.deviations.length?$scope.selectDeviation($scope.deviations[0],0):$scope.selectDeviation($scope.deviations[currentDeviationIndex+1],currentDeviationIndex+1)},$scope.hasMissingProperties=function(deviation){var mandatoryFieldRules=_.filter($scope.fieldRules,{Mandatory:!0});return _.some(mandatoryFieldRules,function(fieldRule){return!("StatusComment"===fieldRule.DomainFieldName&&!deviation.CloseOnCreation||"ID"===fieldRule.FieldName.toUpperCase()||deviation[fieldRule.DomainFieldName])})},$scope.onEstateSelect=function(estate){if(!estate)return $scope.selectedDeviation.GuidEstate="",void($scope.selectedDeviation.Estate="");$scope.selectedDeviation.GuidEstate!==estate.Guid&&($scope.selectedDeviation.GuidBuilding="",$scope.selectedDeviation.Building=null,$scope.selectedDeviation.GuidEquipment="",$scope.selectedDeviation.Equipment=null,$scope.selectedDeviation.GuidArea="",$scope.selectedDeviation.Area=null),$scope.selectedDeviation.GuidEstate=estate.Guid,$scope.selectedDeviation.Estate=estate},$scope.onBuildingSelect=function(building){if(!building)return $scope.selectedDeviation.GuidBuilding="",void($scope.selectedDeviation.Building=null);$scope.selectedDeviation.GuidBuilding!==building.Guid&&($scope.selectedDeviation.GuidEquipment="",$scope.selectedDeviation.Equipment=null,$scope.selectedDeviation.GuidArea="",$scope.selectedDeviation.Area=null),$scope.selectedDeviation.GuidBuilding=building.Guid,$scope.selectedDeviation.Building=building,$scope.selectedDeviation.GuidEstate&&""!==$scope.selectedDeviation.GuidEstate||($scope.selectedDeviation.GuidEstate=building.GuidEstate,$scope.selectedDeviation.Estate=building.Estate)},$scope.onAreaSelect=function(area){if(!area)return $scope.selectedDeviation.GuidArea="",void($scope.selectedDeviation.Area=null);$scope.selectedDeviation.GuidArea=area.Guid,$scope.selectedDeviation.Area=area,$scope.selectedDeviation.GuidBuilding&&""!==$scope.selectedDeviation.GuidBuilding||($scope.selectedDeviation.GuidBuilding=area.GuidBuilding,$scope.selectedDeviation.Building=area.Building),$scope.selectedDeviation.GuidEstate&&""!==$scope.selectedDeviation.GuidEstate||($scope.selectedDeviation.GuidEstate=area.Building.Estate.Guid,$scope.selectedDeviation.Estate=area.Building.Estate)},$scope.onEquipmentSelect=function(equipment){if(!equipment)return $scope.selectedDeviation.GuidEquipment="",void($scope.selectedDeviation.Equipment=null);$scope.selectedDeviation.GuidEquipment=equipment.Guid,$scope.selectedDeviation.Equipment=equipment,$scope.selectedDeviation.GuidEstate&&""!==$scope.selectedDeviation.GuidEstate||($scope.selectedDeviation.GuidEstate=equipment.Building.Estate.Guid,$scope.selectedDeviation.Estate=equipment.Building.Estate),$scope.selectedDeviation.GuidBuilding&&""!==$scope.selectedDeviation.GuidBuilding||($scope.selectedDeviation.GuidBuilding=equipment.GuidBuilding,$scope.selectedDeviation.Building=equipment.Building),equipment.GuidArea&&($scope.selectedDeviation.GuidArea=equipment.GuidArea,$scope.selectedDeviation.Area=equipment.Area)},$scope.onDeviationTypeSelect=function(deviationType){if(!deviationType)return $scope.selectedDeviation.GuidDeviationType="",void($scope.selectedDeviation.DeviationType=null);$scope.selectedDeviation.GuidDeviationType=deviationType.Guid,$scope.selectedDeviation.DeviationType=deviationType},$scope.createDeviations=function(destination){if($scope.deviations.length>0&&!$scope.isPreview){var deviations=[];$scope.deviations.forEach(function(deviation){deviations.push(getDeviationInfo(deviation))}),repository.createMultiple(repository.apiData.deviation.url,deviations,"returnAll=true").then(function(response){for(var hasError=!1,i=response.length-1;i>=0;i--)response[i].IsSuccess?$scope.deviations.splice(i,1):(hasError=!0,repository.growl(response[i].Message,"danger"));hasError||(repository.growl(translationService.translate("web-deviations-create-success","Avvikene ble opprettet"),"success"),modalInstance.close({destination:destination,guid:params.workOrder?params.workOrder.Guid:null}))})}else modalInstance.close({destination:destination,guid:params.workOrder?params.workOrder.Guid:null})};var getDeviationInfo=function(deviation){var postItem=angular.copy(deviation),postImages=[];return deviation.Images&&deviation.Images.length>0&&deviation.Images.forEach(function(image){var postImage=angular.copy(image);delete postImage.Guid,delete postImage.GuidControlListItemAnswer,delete postImage.ControlListItemAnswer,delete postImage.GuidControlListXEntity,delete postImage.ControlListXEntity,postImages.push(postImage)}),postItem.ImageXEntitiesToCreate=postImages,delete postItem.DeviationType,delete postItem.Estate,delete postItem.Building,delete postItem.Equipment,delete postItem.Area,delete postItem.Images,delete postItem.IsMandatory,postItem};$scope.cancel=function(){modalInstance.dismiss("cancel")},repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix.Deviation).then(function(result){$scope.fieldRules=result,$scope.reload=!0})}angular.module("Plania").controller("ControlListDeviationConfirmationController",["$scope","Repository","params","RegisteredFieldService","$modalInstance","TranslationService","$localStorage",controller])}(),function(){function controller($scope,$modal,ngTableParams,repository,$rootScope,translationService,iconService,$localStorage,signalR,$timeout,colorService){$scope.controlListsIsLoading=!1,$scope.addingControlListSignalR=!1,$scope.search={},$scope.isSVV="SvvTunnel"===$localStorage.generalOptions.CustomerId||"Fylkeskommuner"===$localStorage.generalOptions.CustomerId,$scope.isBBY=$localStorage.generalOptions.IsBBY,$scope.customization=$rootScope.customization,$scope.iconMap=iconService.GetIconMap(),$scope.getIcon=iconService.getIcon,$scope.accessCreateControlListXEntity=function(){return $rootScope.hasEditAccess("ControlListXEntity")&&$rootScope.hasReadAccess("ControlList")&&("WorkOrder"===$scope.parentEntity||"PeriodicTask"===$scope.parentEntity)},$scope.hasReadAccess=$rootScope.hasReadAccess("ControlListXEntity"),$scope.$watch("reload",function(newValue,oldValue){$scope.reload&&!0===$scope.reload&&($scope.controlListTable.reload(),$scope.reload=!1)}),$scope.columns=[{Position:1,Title:translationService.translate("web-area-id"),Property:"Area.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-area-description"),Property:"Area.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-equipment-id"),Property:"Equipment.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-equipment-description"),Property:"Equipment.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-controllist-ismandatory"),Property:"ControlList.IsMandatory",PropertyType:"bool"},{Position:6,Title:translationService.translate("web-controllist-id"),Property:"ControlList.Id",PropertyType:"string"},{Position:7,Title:translationService.translate("web-controllist-description"),Property:"ControlList.Description",PropertyType:"string"},{Position:8,Title:translationService.translate("web-controllist-name"),Property:"ControlList.Name",PropertyType:"string"},{Position:9,Title:translationService.translate("web-controllist-icon"),Property:"ControlList.Icon",PropertyType:"string"},{Position:10,Title:translationService.translate("web-controllist-Color"),Property:"ControlList.Color",PropertyType:"string"}],$scope.getLowestEntityCaption=function(controlList){if(controlList.Equipment){var extraText="";return $scope.isSVV&&controlList.Equipment&&controlList.Equipment.Text20&&(extraText=" - "+controlList.Equipment.Text20),$rootScope.getEntityCaption(controlList.Equipment)+extraText}return controlList.Area?$localStorage.generalOptions.IsBBY?$rootScope.getEntityCaption(controlList.Area)+" - "+controlList.Area.Text01:$rootScope.getEntityCaption(controlList.Area):controlList.Building?$rootScope.getEntityCaption(controlList.Building):controlList.Estate?$rootScope.getEntityCaption(controlList.Estate):void 0},$scope.getEntityIcon=function(controlList){return controlList.Equipment?"fa-gear c-bluegray":controlList.Area?"fa-layer-group c-lightblue":controlList.Building?"fa-building-columns c-brown":controlList.Estate?"fa-city c-teal":void 0};var sorting={ClosedDate:"asc","Area.Id":"asc","Equipment.Id":"asc",CreationDate:"desc"};$scope.filterTypes=[{value:"all",name:translationService.translate("web-controlListXEntity-filterType-all","Alle"),fullName:translationService.translate("web-controlListXEntity-filterType-all-fullName","Vis alle kontrollister")},{value:"new",name:translationService.translate("web-controlListXEntity-filterType-new","Nye"),fullName:translationService.translate("web-controlListXEntity-filterType-new-fullName","Vis nye kontrollister")},{value:"active",name:translationService.translate("web-controlListXEntity-filterType-active","Aktive"),fullName:translationService.translate("web-controlListXEntity-filterType-active-fullName","Vis aktive kontrollister")},{value:"inworks",name:translationService.translate("web-controlListXEntity-filterType-inworks","Pågående"),fullName:translationService.translate("web-controlListXEntity-filterType-inworks-fullName","Vis pågående kontrollister")},{value:"completed",name:translationService.translate("web-controlListXEntity-filterType-completed","Fullførte"),fullName:translationService.translate("web-controlListXEntity-filterType-completed-fullName","Vis fullførte kontrollister")}],$scope.selectedFilter=_.find($scope.filterTypes,{value:"PeriodicTask"===$scope.parentEntity||"WorkOrder"===$scope.parentEntity?"all":"active"}),$scope.setFilter=function(filterType){$scope.selectedFilter=_.find($scope.filterTypes,{value:filterType}),$scope.controlListTable.reload()},$scope.controlListTable=new ngTableParams({page:1,count:5,sorting:sorting,filter:{}},{total:0,counts:[5,10,20],filterDelay:50,paginationMaxBlocks:6,getData:function($defer,params){if($scope.guid&&$scope.parentEntity){$scope.controlListsIsLoading=!0;var columns=[];$scope.columns.forEach(function(col){columns.push(col.Property)}),columns.push("ControlList.Guid"),columns.push("ControlList.UseImage"),columns.push("CreationDate"),columns.push("Status"),columns.push("ClosedDate"),columns.push("NotExecutedComment"),columns.push("ReferenceDataNotExecuted.Id"),columns.push("ReferenceDataNotExecuted.Description"),columns.push("ControlList.VersionStatus"),columns.push("ControlList.GuidReferenceTypeNotExecuted"),columns.push("UserClosedBy.RealName"),columns.push("UserUpdatedBy.RealName"),columns.push("WorkOrder.Id","WorkOrder.Description","WorkOrder.Building.Id","WorkOrder.Building.Description","WorkOrder.Building.Guid"),columns.push("Equipment.Building.Id","Equipment.Building.Description","Equipment.Building.Guid","Equipment.Manufacturer","Equipment.Location"),columns.push("Equipment.Building.Estate.Id","Equipment.Building.Estate.Description","Equipment.Building.Estate.Guid"),columns.push("Area.IsHousing"),columns.push("Area.Building.Id","Area.Building.Description","Area.Building.Guid"),columns.push("Area.Building.Estate.Id","Area.Building.Estate.Description","Area.Building.Estate.Guid"),$scope.isBBY=$localStorage.generalOptions.IsBBY,$scope.isBBY&&(columns.push("Area.Text01","Area.AreaCategory.Description"),columns.push("Equipment.Area.Id","Equipment.Area.Text01")),$scope.isSVV&&columns.push("Equipment.Text20"),"UnoX"===$localStorage.generalOptions.CustomerId&&columns.push("Equipment.AlternateId"),"Area"!==$scope.parentEntity&&"Equipment"!==$scope.parentEntity||columns.push("WorkOrder.EndDate","WorkOrder.Stage");var filter={searchString:params.filter().searchString,FilterModel:{Condition:"and",Rules:[{Property:"Guid"+$scope.parentEntity,Operator:"=",Value:$scope.guid}]},ExcludeSelectionFilter:!0};"Area"!==$scope.parentEntity&&"Equipment"!==$scope.parentEntity||filter.FilterModel.Rules.push({Property:"GuidWorkOrder",Operator:"<>",Value:null});var sorting={};switch($scope.selectedFilter.value){case"new":filter.FilterModel.Rules.push({Property:"Status",Operator:"=",Value:"0"});break;case"active":filter.FilterModel.Rules.push({Property:"Status",Operator:"in",Value:"0,1"}),sorting={Status:"desc"};break;case"inworks":filter.FilterModel.Rules.push({Property:"Status",Operator:"in",Value:"1"});break;case"completed":filter.FilterModel.Rules.push({Property:"Status",Operator:"=",Value:"2"})}Object.keys(params.sorting()).forEach(function(key){sorting[key]=params.sorting()[key]}),repository.GetPaginated(repository.apiData.controlListXEntity.url,params.page()-1,params.count(),sorting,filter,null,JSON.stringify(columns)).then(function(result){if($scope.controlListTable.settings().total=result.TotalCount,$scope.controlListTable.settings().filterDelay=500,$scope.controlListsIsLoading=!1,$scope.controlLists||($scope.controlLists=[]), $scope.controlLists)for(;$scope.controlLists.length>0;)$scope.controlLists.pop();result.List.forEach(function(controlList){controlList.ControlList&&controlList.ControlList.Color&&(controlList.ControlList.Color=colorService.convertToRainbow(controlList.ControlList.Color)),$scope.controlLists.push(controlList)}),$defer.resolve(result.List)},function(error){$scope.controlListsIsLoading=!1,repository.showError(error)})}}}),$scope.create=function(){$modal.open({templateUrl:"app/controlList/views/addControlListModal.html",controller:"AddControlListModalController",size:"xl",resolve:{params:function(){return{guidWorkOrder:"WorkOrder"===$scope.parentEntity?$scope.guid:null,guidPeriodicTask:"PeriodicTask"===$scope.parentEntity?$scope.guid:null,guidBuilding:$scope.parentModel.GuidBuilding,guidEstate:$scope.parentModel.GuidEstate,guidEquipment:$scope.parentModel.GuidEquipment,guidArea:$scope.parentModel.GuidArea}}}}).result.then(function(response){$scope.controlListTable.reload()},function(){$scope.controlListTable.reload()})},$scope.openControlList=function(controlListXEntity){$modal.open({templateUrl:"app/controlList/views/controlListCompletionModal.html",size:"xl",controller:"ControlListCompletionModalController",resolve:{params:function(){return{controlList:controlListXEntity.ControlList,controlListXEntity:controlListXEntity,workOrderCaption:$scope.parentModel.Caption,workOrder:$scope.parentModel,restrictEdit:!!(controlListXEntity.WorkOrder&&controlListXEntity.WorkOrder.EndDate||$scope.parentModel.EndDate||"PeriodicTask"===$scope.parentEntity||$scope.restrictEdit)}}}}).result.then(function(result){$scope.controlListTable.reload(),$scope.reloadDeviations=!0},function(reloadLists){$scope.controlListTable.reload(),$scope.reloadDeviations=!0})},$scope.remove=function(item){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-controlList-message","Kontrollisten vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-controlList-button-confirm","Ja, fjern kontrollisten!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.deleteSingle(repository.apiData.controlListXEntity.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-controlList-success","Kontrollisten ble fjernet!"),result,"success"),$scope.controlListTable.reload()},function(error){swal("Error",error,"error")})})},"WorkOrder"===$scope.parentEntity&&$scope.guid&&($scope.signalRData={},$scope.showAddingControlListWorkOrderMessage=!1,signalR.on("addingControlListsToWorkOrder"+$scope.guid,function(progress){progress.Current++,progress.Total++,!$scope.showAddingControlListWorkOrderMessage&&progress.Started&&($scope.showAddingControlListWorkOrderMessage=!0),$scope.showAddingControlListWorkOrderMessage&&progress.Finished&&$timeout(function(){$scope.showAddingControlListWorkOrderMessage=!1},5e3),$scope.addControlListToWorkOrderData=progress,progress.Finished&&$timeout(function(){$scope.controlListTable.reload()},250)}),$scope.$on("$destroy",function(){signalR.off("addingControlListsToWorkOrder"+$scope.guid)})),$scope.$on($rootScope.events.newSelection,function(){$scope.controlListTable.reload()})}angular.module("Plania").directive("controlLists",function(){return{restrict:"E",scope:{isCollapsed:"=isCollapsed",reload:"=reload",reloadDeviations:"=reloadDeviations",controlLists:"=controlLists",disableActions:"=disableActions",parentEntity:"=parentEntity",parentModel:"=parentModel",guid:"=guid",restrictEdit:"=restrictEdit"},controller:["$scope","$modal","ngTableParams","Repository","$rootScope","TranslationService","IconService","$localStorage","SignalR","$timeout","ColorService",controller],link:function(scope,element,attrs){},templateUrl:"app/controlList/views/controlListDirective.html"}})}(),function(){function controlListItemSelectionModalController($scope,$modalInstance,params,translationService){$scope.filter={};var isNullOrEmpty=function(value){return _.isUndefined(value)||_.isNull(value)||""===value};$scope.filterGroup=function(group){if(isNullOrEmpty($scope.filter.searchString))return!0;var lowerCaseSearch=$scope.filter.searchString.toLowerCase();return _.some(group.items,function(item){var name=item.Name;return name||(name=""),name=name.toLowerCase(),name.includes(lowerCaseSearch)})},$scope.groups=function(){var groups=[{items:[]}];return params.controlListItems.forEach(function(item){item.typename=translationService.translate("web-enum-controllistitemtype-"+item.Type,item.Type),"SectionHeader"===item.Type?groups.push({guid:item.Guid,name:item.Name?item.Name:"",items:[]}):"Info"!==item.Type&&groups[groups.length-1].items.push(item)}),groups.length>1&&!groups[0].name&&(groups[0].name=translationService.translate("web-controlListItemSelectionModal-ungrouped-name","Ugruppert")),0===groups[0].items.length&&groups.shift(),groups}(),$scope.selectItem=function(item){$modalInstance.close(item)},$scope.cancel=function(){$modalInstance.dismiss("cancel")}}angular.module("Plania").controller("ControlListItemSelectionModalController",["$scope","$modalInstance","params","TranslationService",controlListItemSelectionModalController])}(),function(){function controller($scope,repository,$stateParams,translationService){$scope.isUpdate="controlListLogItem.edit"===$scope.navigation.current.name||$stateParams.isModal&&$stateParams.isUpdate,$scope.activateAutocomplete=!1,$scope.isModal=$stateParams.isModal,$scope.model={};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.HourType,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.HourType,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.HourType),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.HourType)};$scope.isUpdate?repository.getSingle(repository.apiData.controlListLogItem.url,$stateParams.guid,null).then(function(response){$scope.model=response.Data,updateAccess(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}):$scope.activateAutocomplete=!0,$scope.cancel=function(){$stateParams.cancelModal()},$scope.closeModal=function(){$stateParams.closeModal()},$scope.update=function(destination){var success=function(result){if(repository.growl($scope.isUpdate?translationService.translate("update-controlListLogItem-success","Loggepunktet har blitt oppdatert."):translationService.translate("create-hour-type-success","Loggepunktet har blitt opprettet."),"success"),$scope.isModal)$scope.closeModal();else{var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})}},error=function(error){repository.growl("string"==typeof error?error:error.Data.Message,"danger")};($scope.isUpdate?repository.updateSingle:repository.createSingle)(repository.apiData.controlListLogItem.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-controlListLogItem-delete-message","Loggepunktet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-controlListLogItem-delete-button-confirm","Ja, fjern loggepunktet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.controlListLogItem.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-controlListLogItem-delete-success","Loggepunktet ble fjernet!"),result,"success"),repository.growl(translationService.translate("web-controlListLogItem-removed","Loggepunktet er fjernet"),"success"),$scope.isModal?$modalStack.dismissAll():$scope.goBack("controlListLogItem.list",{menuGuid:$scope.navigation.params.menuGuid})})})}}angular.module("Plania").controller("ControlListLogItemController",["$scope","Repository","$stateParams","TranslationService",controller])}(),function(){function controller($scope,$modalInstance,modalParams,repository,ngTableParams,translationService,listService,$q,enumService){$scope.modalParams=modalParams,$scope.selectedItems=[],$scope.selectedEntityType=modalParams.canConnect.UseWithWorkOrder?"WorkOrder":modalParams.canConnect.UseWithEquipment?"Equipment":modalParams.canConnect.UseWithArea?"Area":null,$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.setColumnsByEntityType=function(){switch($scope.columns=[{Position:1,Title:translationService.translate("web-periodicTask-Id","Periodisk Nr."),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-periodicTask-Description","Periodisk Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-periodicTask-Building-Id","Bygg Id"),Property:"Building.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-periodicTask-Building-Description","Byggningsbeskrivelse"),Property:"Building.Description",PropertyType:"string"}],$scope.selectedEntityType){case"Equipment":$scope.columns.push({Position:5,Title:translationService.translate("web-periodicTask-Equipment-Id","Anlegg Id"),Property:"Equipment.Id",PropertyType:"string"}),$scope.columns.push({Position:6,Title:translationService.translate("web-periodicTask-Equipment-Description","Anleggsnavn"),Property:"Equipment.Description",PropertyType:"string"}),$scope.columns.push({Position:7,Title:translationService.translate("web-periodicTask-EquipmentCategory-Description","Anlegg Type"),Property:"Equipment.EquipmentCategory.Description",PropertyType:"string"}),$scope.columns.push({Position:8,Title:translationService.translate("web-periodicTask-resourceGroup-id","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"string"});break;case"Area":$scope.columns.push({Position:5,Title:translationService.translate("web-periodicTask-Area-Id","Rom Id"),Property:"Area.Id",PropertyType:"string"}),$scope.columns.push({Position:6,Title:translationService.translate("web-periodicTask-Area-Description","Rom beskrivelse"),Property:"Area.Description",PropertyType:"string"}),$scope.columns.push({Position:7,Title:translationService.translate("web-periodicTask-AreaCategory-Description","Rom type"),Property:"Area.AreaCategory.Description",PropertyType:"string"}),$scope.columns.push({Position:8,Title:translationService.translate("web-periodicTask-resourceGroup-id","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"string"});break;case"WorkOrder":$scope.columns.push({Position:5,Title:translationService.translate("web-periodicTask-Equipment-Id","Anlegg Id"),Property:"Equipment.Id",PropertyType:"string"}),$scope.columns.push({Position:6,Title:translationService.translate("web-periodicTask-Equipment-Description","Anleggsnavn"),Property:"Equipment.Description",PropertyType:"string"}),$scope.columns.push({Position:7,Title:translationService.translate("web-periodicTask-Area-Id","Rom Id"),Property:"Area.Id",PropertyType:"string"}),$scope.columns.push({Position:8,Title:translationService.translate("web-periodicTask-resourceGroup-id","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"string"})}},$scope.itemTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{PropertyFilter:[{Property:"IsTemplate",Operator:"=",Value:"0"}]}},{total:0,counts:[10,25,50,100,250,500],paginationMaxBlocks:8,getData:function($defer,params){var filter=angular.copy(params.filter());switch($scope.setColumnsByEntityType(),filter.GuidConnectedControlList=modalParams.guid,$scope.selectedEntityType){case"WorkOrder":filter.FilterEquipment=!1,filter.FilterArea=!1;break;case"Equipment":filter.FilterEquipment=!0,filter.FilterArea=!1;break;case"Area":filter.FilterEquipment=!1,filter.FilterArea=!0}var columns=_.map($scope.columns,"Property");repository.GetPaginated(repository.apiData.periodicTask.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.addSelectedItem=function(object){if($scope.isItemSelected(object)){for(var i=0;i<$scope.selectedItems.length;i++)if($scope.selectedItems[i].Guid===object.Guid)return void $scope.selectedItems.splice(i,1)}else $scope.selectedItems.push(object)},$scope.isItemSelected=function(object){return _.find($scope.selectedItems,function(o){return o.Guid===object.Guid})};var getEntityMapping=function(entity){var newEntity={GuidPeriodicTask:entity.Guid,GuidControlList:modalParams.guid};switch($scope.selectedEntityType){case"Equipment":newEntity.GuidEquipment=entity.GuidEquipment;break;case"Area":newEntity.GuidArea=entity.GuidArea}return newEntity};$scope.save=function(){if($scope.selectedEntityType&&$scope.selectedItems.length>0){var model=[];$scope.selectedItems.forEach(function(item){model.push(getEntityMapping(item))}),repository.createMultiple(repository.apiData.controlListXEntity.url,model).then(function(){repository.growl(translationService.translate("web-controlList-addMultiple-success","Kontrollistene har blitt lagt til"),"success"),$modalInstance.close("OK")},function(error){repository.growl(error,"danger")})}},$scope.$watch("selectedEntityType",function(newValue,oldValue){newValue!==oldValue&&newValue&&($scope.itemTable.reload(),$scope.selectedItems=[])})}angular.module("Plania").controller("ControlListPeriodicTaskModalController",["$scope","$modalInstance","modalParams","Repository","ngTableParams","TranslationService","ListService","$q","EnumService",controller])}(),function(){function controller($scope,repository,params,listService,translationService,ngTableParams,$localStorage,modalInstance){var isSVV="10088"===$localStorage.generalOptions.CustomerId||"12258"===$localStorage.generalOptions.CustomerId;$scope.selectedControlList=params.controlList,$scope.selectedControlList.UseWithEquipment?$scope.selectedEntityType="Equipment":$scope.selectedControlList.UseWithArea?$scope.selectedEntityType="Area":$scope.selectedControlList.UseWithWorkOrder&&($scope.selectedEntityType="WorkOrder"),$scope.equipmentColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Building.Id",sortable:!0},{Position:2,Title:translationService.translate("web-building-description"),Property:"Building.Description"},{Position:3,Title:translationService.translate("web-equipment-id"),Property:"Id"},{Position:4,Title:translationService.translate("web-equipment-description"),Property:"Description"}],isSVV&&$scope.equipmentColumns.push({Position:5,Title:translationService.translate("web-equipment-text20-svv","Driftsmerking"),Property:"Text20"}),$scope.areaColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Building.Id",sortable:!0},{Position:2,Title:translationService.translate("web-building-description"),Property:"Building.Description"},{Position:3,Title:translationService.translate("web-area-id"),Property:"Id"},{Position:4,Title:translationService.translate("web-area-description"),Property:"Description"}],$scope.workOrderColumns=[{Position:1,Title:translationService.translate("web-workOrder-building-id"),Property:"Building.Id",sortable:!0},{Position:2,Title:translationService.translate("web-workOrder-building-description"),Property:"Building.Description"},{Position:3,Title:translationService.translate("web-workOrder-id"),Property:"Id"},{Position:4,Title:translationService.translate("web-workOrder-description"),Property:"Description"}],$scope.selectedEntityType&&($scope.items=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){$scope.columns=[];var url=repository.apiData.equipment.url,columnProperties=[];switch($scope.selectedEntityType){case"Area":url=repository.apiData.area.url,$scope.areaColumns.forEach(function(column){$scope.columns.push(column)}),columnProperties.push("Id"),columnProperties.push("Description"),columnProperties.push("IsHousing"),columnProperties.push("Building.Id"),columnProperties.push("Building.Description"),columnProperties.push("Building.Guid"),columnProperties.push("Building.Estate.Id"),columnProperties.push("Building.Estate.Description"),columnProperties.push("Building.Estate.Guid"),$localStorage.generalOptions.IsBBY&&(columnProperties.push("Text01"),columnProperties.push("AreaCategory.Description"));break;case"Equipment":url=repository.apiData.equipment.url,$scope.equipmentColumns.forEach(function(column){$scope.columns.push(column)}),columnProperties.push("Id"),columnProperties.push("Description"),columnProperties.push("Manufacturer"),columnProperties.push("Location"),columnProperties.push("Building.Id"),columnProperties.push("Building.Description"),columnProperties.push("Building.Guid"),columnProperties.push("Building.Estate.Id"),columnProperties.push("Building.Estate.Description"),columnProperties.push("Building.Estate.Guid"),$scope.isSVV&&columnProperties.push("Text20");break;case"WorkOrder":url=repository.apiData.workOrder.url,$scope.workOrderColumns.forEach(function(column){$scope.columns.push(column)})}$scope.columns.forEach(function(col){columnProperties.push(col.Property)}),repository.GetPaginated(url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columnProperties)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})),$scope.$watch("selectedEntityType",function(newValue,oldValue){newValue!==oldValue&&newValue&&$scope.items.reload()}),$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)},$scope.selectEntity=function(entity){var returnObject={};"WorkOrder"===entity.Prefix?returnObject.workOrder=entity:"Area"===entity.Prefix?returnObject.area=entity:"Equipment"===entity.Prefix&&(returnObject.equipment=entity),modalInstance.close(returnObject)},$scope.cancel=function(){modalInstance.dismiss("cancel")}}angular.module("Plania").controller("ControlListPreviewEntitySelectionModalController",["$scope","Repository","params","ListService","TranslationService","ngTableParams","$localStorage","$modalInstance",controller])}(),function(){function controller($scope,$modalInstance,repository,translationService,params){var model=params.model;$scope.rules={replaceNewControlListsOnWorkOrder:!0},$scope.countRelations=null,repository.getSingleWithNoParameter(repository.apiData.controlList.endpoint.countRelations+model.Guid).then(function(response){$scope.countRelations=response},function(error){$scope.countRelations={},repository.showError(error)}),$scope.isRunningAction=!1,$scope.publish=function(){$scope.isRunningAction=!0,repository.runAction(repository.apiData.controlList.endpoint.publish+model.Guid,model,"replaceNewControlListsOnWorkOrder="+$scope.rules.replaceNewControlListsOnWorkOrder,!0).then(function(response){repository.growl(translationService.translate("web-controlList-publishDraft-success","Utkastet er publisert"),"success"),$scope.isRunningAction=!1,$modalInstance.close()},function(error){$scope.isRunningAction=!1,repository.showError(error)})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("ControlListPublishModalController",["$scope","$modalInstance","Repository","TranslationService","params",controller])}(),function(){function controller($scope,repository,params,enumService,modalInstance,translationService,$q,registeredFieldService,$timeout){$scope.requests=params.requests,$scope.inWorkOrder=params.inWorkOrder,$scope.reload=!1,$scope.viewMode=!1,$scope.activateAutocomplete=!0,$scope.isEdit=!1,$scope.selectedRequest=null,$scope.parentEntity="WorkOrder",$scope.isPreview=params.isPreview;var userData=repository.authService.getUserData();$scope.mandatoryFieldRules=[];var registeredFieldsPromise=registeredFieldService.getRegisteredField(repository.commonService.prefix.Request);registeredFieldsPromise.then(function(result){$scope.mandatoryFieldRules=_.filter(result,{Mandatory:!0})}),$scope.hasMissingProperties=function(request){return!!$scope.mandatoryFieldRules&&_.some($scope.mandatoryFieldRules,function(fieldRule){return"ID"!==fieldRule.FieldName.toUpperCase()&&!request[fieldRule.DomainFieldName]})},$scope.isMandatoryOrPrefill=function(domainFieldName){return!!domainFieldName&&(!!_.some($scope.requests,function(request){return request[domainFieldName]})||_.some($scope.mandatoryFieldRules,function(rule){return rule.DomainFieldName===domainFieldName}))},$scope.requests.forEach(function(request){registeredFieldsPromise.then(function(){if(request.GuidEquipment&&!request.GuidBuilding){var equipmentColumns=["Building.Id","Building.Description"];repository.getSingle(repository.apiData.equipment.url,request.GuidEquipment,JSON.stringify(equipmentColumns)).then(function(response){var equipment=response.Data;request.GuidBuilding=equipment.GuidBuilding,request.Building=equipment.Building.Caption},function(error){})}request.EmailAddress=userData.email,request.Telephone=userData.phone,request.ContactPerson=userData.guidPerson?userData.personFirstName+" "+userData.personLastName:userData.realName,userData.guidDepartment&&(request.GuidDepartment=userData.guidDepartment,request.Department={Guid:userData.guidDepartment,Name:userData.userDepartment,Caption:userData.userDepartment},$scope.department=request.Department.Caption)})}),$scope.removeRequest=function(index){$scope.requests.splice(index,1),$scope.requests.length>0?$scope.selectRequest($scope.requests[0]):$scope.requests.length<1&&($scope.selectedRequest=null)},$scope.autoCompleteFilter=function(filterName){switch(filterName){case"equipment":return{GuidBuilding:$scope.selectedRequest.GuidBuilding,IsApparatus:!1,PropertyFilter:[{Property:"IsTemplate",Operator:"=",Value:!1}]};case"area":return{GuidBuilding:$scope.selectedRequest.GuidBuilding,GuidDrawing:$scope.selectedRequest.GuidDrawing};case"drawing":return{GuidBuilding:$scope.selectedRequest.GuidBuilding};case"person":return{};case"responsiblePerson":return{GuidBuildingResponsible:$scope.selectedRequest.GuidBuilding};case"department":return{};case"priority":return $scope.selectedRequest.IsBBYLimited?{PropertyFilter:[{Property:"Description",Operator:"contains",Value:"VH"},{Property:"EntityType",Operator:"=",Value:6}]}:{PropertyFilter:[{Property:"EntityType",Operator:"=",Value:6}]};case"cause":return $scope.selectedRequest.IsBBYLimited?{PropertyFilter:[{Property:"Id",Operator:"StartsWith",Value:"VH"}]}:{};case"resourceGroup":return{PropertyFilter:[{Property:"DoesMaintenanceTasks",Operator:"=",Value:"true"}]};case"activityCategory":return{PropertyFilter:[{Property:"UseInRequest",Operator:"=",Value:"true"},{Property:"IsAbstract",Operator:"=",Value:"0"}]}}},$scope.selectRequest=function(request){$scope.activateAutocomplete=!1,request.hasBeenViewed=!0,$scope.selectedRequest=request,$scope.selectedRequest.GuidBuilding||($scope.selectedRequest.Building=null),$scope.selectedRequest.GuidEquipment||($scope.selectedRequest.Equipment=null),$scope.selectedRequest.GuidArea||($scope.selectedRequest.Area=null),$scope.selectedRequest.GuidResponsiblePerson||($scope.selectedRequest.ResponsiblePerson=null),$scope.selectedRequest.GuidBuilding&&$scope.selectedRequest.Building&&!$scope.selectedRequest.Building.Caption&&($scope.selectedRequest.Building.Caption=$scope.selectedRequest.Building.Id+" - "+$scope.selectedRequest.Estate.Description),$scope.selectedRequest.GuidEquipment&&$scope.selectedRequest.Equipment&&!$scope.selectedRequest.Equipment.Caption&&($scope.selectedRequest.Equipment.Caption=$scope.selectedRequest.Equipment.Id+" - "+$scope.selectedRequest.Equipment.Description),$scope.selectedRequest.GuidArea&&$scope.selectedRequest.Area&&!$scope.selectedRequest.Area.Caption&&($scope.selectedRequest.Area.Caption=$scope.selectedRequest.Area.Id+" - "+$scope.selectedRequest.Area.Description),$scope.selectedRequest.GuidResponsiblePerson&&$scope.selectedRequest.Person1&&($scope.selectedRequest.ResponsiblePerson={Guid:$scope.selectedRequest.GuidResponsiblePerson,Caption:$scope.selectedRequest.Person1.Caption}),$timeout(function(){$scope.activateAutocomplete=!0},350)},$scope.selectNextRequest=function(){var currentRequestIndex=_.findIndex($scope.requests,function(request){return request===$scope.selectedRequest});currentRequestIndex+1===$scope.requests.length?$scope.selectRequest($scope.requests[0]):$scope.selectRequest($scope.requests[currentRequestIndex+1])},$scope.onBuildingSelect=function(building){if(!building)return void($scope.selectedRequest.GuidBuilding="");$scope.selectedRequest.GuidBuilding!==building.Guid&&($scope.selectedRequest.GuidEquipment="",$scope.selectedRequest.Equipment=null,$scope.selectedRequest.GuidArea="",$scope.selectedRequest.Area=null),$scope.selectedRequest.GuidBuilding=building.Guid},$scope.onEquipmentSelect=function(equipment){if(!equipment)return void($scope.selectedRequest.GuidEquipment="");$scope.selectedRequest.GuidEquipment=equipment.Guid,$scope.selectedRequest.GuidBuilding&&""!==$scope.selectedRequest.GuidBuilding||($scope.selectedRequest.GuidBuilding=equipment.GuidBuilding,$scope.selectedRequest.Building=equipment.Building),equipment.GuidArea&&($scope.selectedRequest.GuidArea=equipment.GuidArea,$scope.selectedRequest.Area=equipment.Area)},$scope.onAreaSelect=function(area){if(!area)return $scope.selectedRequest.GuidArea="",void($scope.selectedRequest.Area=null);$scope.selectedRequest.GuidArea=area.Guid,$scope.selectedRequest.GuidBuilding&&""!==$scope.selectedRequest.GuidBuilding||($scope.selectedRequest.GuidBuilding=area.GuidBuilding,$scope.selectedRequest.Building=area.Building)},$scope.onPrioritySelect=function(priority){priority&&($scope.selectedRequest.GuidPriority=priority.Guid,priority.HasDeadline?($scope.selectedRequest.DueDate=enumService.getTimeUnitDate(new Date,priority.DeadlinePeriodUnit,priority.DeadlinePeriodNumber),$scope.restrictDueDate=!0):$scope.restrictDueDate=!1)},$scope.onResponsiblePersonSelect=function(person){if(!person)return $scope.selectedRequest.GuidResponsiblePerson="",void($scope.selectedRequest.ResponsiblePerson=null);$scope.selectedRequest.GuidResponsiblePerson=person.Guid},$scope.createRequests=function(destination){if($scope.requests.length>0&&!$scope.isPreview){var requests=[];$scope.requests.forEach(function(request){request.Guid||requests.push(getRequestInfo(request))}),repository.createMultiple(repository.apiData.request.url,requests,"returnAll=true").then(function(response){for(var hasError=!1,i=response.length-1;i>=0;i--)response[i].IsSuccess?$scope.requests.splice(i,1):(hasError=!0,repository.growl(response[i].Message,"danger"));hasError||(repository.growl(translationService.translate("web-request-create-success","Meldingene ble opprettet"),"success"),modalInstance.close({destination:destination,guid:params.workOrder?params.workOrder.Guid:null}))})}else modalInstance.close({destination:destination,guid:params.workOrder?params.workOrder.Guid:null})};var getRequestInfo=function(request){var postItem=angular.copy(request),postImages=[];return request.Images&&request.Images.length>0&&request.Images.forEach(function(image){var postImage=angular.copy(image);delete postImage.Guid,delete postImage.GuidControlListItemAnswer,delete postImage.ControlListItemAnswer,delete postImage.GuidControlListXEntity,delete postImage.ControlListXEntity,postImages.push(postImage)}),postItem.ImageXEntitiesToCreate=postImages,postItem.RegisteredDate=(new Date).toISOString(),delete postItem.Building,delete postItem.Equipment,delete postItem.Area,delete postItem.Images,delete postItem.IsMandatory,postItem};$scope.cancel=function(){modalInstance.dismiss("cancel")}}angular.module("Plania").controller("ControlListRequestConfirmationController",["$scope","Repository","params","EnumService","$modalInstance","TranslationService","$q","RegisteredFieldService","$timeout",controller])}(),angular.module("Plania").directive("controlListSection",["$timeout",function($timeout){return{restrict:"A",scope:{isCollapsed:"=isCollapsed"},link:function(scope,element,attrs){$timeout(function(){var nextHeaderId,foundCurrent,thisId=element.parent()[0].id,headerElements=$(".control-list-item .control-list-section-header").closest(".control-list-item");headerElements.each(function(index){if(!nextHeaderId)return thisId===headerElements[index].id?void(foundCurrent=!0):void(foundCurrent&&(nextHeaderId=headerElements[index].id))});var controlListItems=$("#"+thisId).nextUntil("#"+nextHeaderId);controlListItems.wrapAll("
    "),$("#"+thisId+" .control-list-section-header > h2").click(function(){var icon=$("#"+thisId).find("a > i.fa");icon.hasClass("fa-chevron-up")?(icon.removeClass("fa-chevron-up"),icon.addClass("fa-chevron-down")):(icon.addClass("fa-chevron-up"),icon.removeClass("fa-chevron-down"));var mandatoryIndicator=$("#"+thisId).find(".mandatory-fields-indicator"),description=$("#"+thisId).find("small");"none"===description.css("display")?(description.css("display","block"),mandatoryIndicator.css("display","none")):($timeout(function(){description.css("display","none")},200),mandatoryIndicator.css("display","inline-block"));var maxHeight=0;controlListItems.each(function(index){maxHeight+=$(controlListItems[index]).height()+30});var section=$("#"+thisId).next(".control-list-section");section.hasClass("section-hidden")?(scope.isCollapsed=!1,section.removeClass("section-hidden"),section.css("max-height",maxHeight),$timeout(function(){section.css("max-height","none")},200)):(scope.isCollapsed=!0,section.addClass("section-hidden"),section.css("max-height",maxHeight),$timeout(function(){section.css("max-height",0)},1))})})}}}]),function(){function controller($scope,repository,ngTableParams,translationService,$modal){var guidArea=null;$scope.init=function(params){guidArea=params.guidArea,getData()};var columns=["Status","WorkOrder.Id","WorkOrder.Description","WorkOrder.EndDate","WorkOrder.DueDate","Area.Id","Area.Description","Area.Building.Id","Area.Building.Description","Area.Building.Guid","Area.Building.Estate.Id","Area.Building.Estate.Description","Area.Building.Estate.Guid","ControlList.Id","ControlList.Description","ControlList.Name","ControlList.Guid","ControlList.Color","ControlList.Icon","ClosedDate","UserClosedBy.RealName"],getData=function(){$scope.controlListTable=new ngTableParams({page:1,count:10,sorting:{"WorkOrder.DueDate":"desc"},filter:{FilterModel:{Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"WorkOrder.StartDate",Operator:"<=",Value:moment().endOf("day").toISOString()},{Property:"WorkOrder.StartDate",Operator:"=",Value:""}]},{Property:"GuidArea",Operator:"=",Value:guidArea},{Property:"GuidWorkOrder",Operator:"<>",Value:null},{Property:"WorkOrder.EndDate",Operator:"=",Value:""}]}}},{total:0,counts:[10,20],getData:function($defer,params){repository.GetPaginated(repository.apiData.controlListXEntity.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})};$scope.openControlList=function(controlListXEntity){$modal.open({ templateUrl:"app/controlList/views/controlListCompletionModal.html",size:"xl",controller:"ControlListCompletionModalController",resolve:{params:function(){return{controlList:controlListXEntity.ControlList,controlListXEntity:controlListXEntity,workOrder:controlListXEntity.WorkOrder,workOrderCaption:controlListXEntity.WorkOrder.Caption}}}}).result.then(function(result){$scope.controlListTable.reload()},function(){$scope.controlListTable.reload()})}}angular.module("Plania").controller("ControlListSelectionController",["$scope","Repository","ngTableParams","TranslationService","$modal",controller])}(),function(){function controller($scope,translationService,$rootScope,$timeout,$modal){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.hasPageLoaded="answers"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"answers"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)});$scope.dropdownFilters=[{value:"current",name:translationService.translate("web-controlList-answersTab-controlListItemAnswers-current","Gjeldende")},{value:"all",name:translationService.translate("web-controlList-answersTab-controlListItemAnswers-all","Alle")}],$scope.selectedDropdownFilter=$scope.dropdownFilters[0],$scope.applyDropdownFilter=function(dropdownFilter,filter){switch(dropdownFilter.value){case"current":filter.FilterModel.Rules.push({Property:"ControlListXEntity.GuidControlList",Operator:"=",Value:$scope.model.Guid});break;case"all":$scope.model.GuidMasterRecord?filter.FilterModel.Rules.push({Property:"ControlListXEntity.ControlList.GuidMasterRecord",Operator:"=",Value:$scope.model.GuidMasterRecord}):filter.FilterModel.Rules.push({Property:"ControlListXEntity.GuidControlList",Operator:"=",Value:$scope.model.Guid});break;default:filter.FilterModel.Rules.push({Property:"ControlListXEntity.GuidControlList",Operator:"=",Value:$scope.model.Guid})}},$scope.controlListItemAnswerFilter={FilterModel:{Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"ControlListXEntity.ControlList.GuidMasterRecord",Operator:"=",Value:$scope.model.Guid},{Property:"ControlListXEntity.ControlList.Guid",Operator:"=",Value:$scope.model.Guid}]}]}},$scope.controlListItemAnswerColumns=["ControlListXEntity.GuidWorkOrder","ControlListXEntity.WorkOrder.Id","ControlListXEntity.WorkOrder.Description","ControlListXEntity.GuidEquipment","ControlListXEntity.Equipment.Id","ControlListXEntity.Equipment.Description","ControlListXEntity.GuidPeriodicTask","ControlListXEntity.PeriodicTask.Id","ControlListXEntity.PeriodicTask.Description","ControlListXEntity.GuidArea","ControlListXEntity.Area.Id","ControlListXEntity.Area.Description","ControlListXEntity.Area.IsHousing"],$scope.controlListItemAnswerContext=planiaUtils.contextIds.controlListControlListItemAnswer,$scope.openControlList=function(controlListItemAnswer){var caption="";controlListItemAnswer.ControlListXEntity.WorkOrder?caption=controlListItemAnswer.ControlListXEntity.WorkOrder.Caption:controlListItemAnswer.ControlListXEntity.PeriodicTask&&(caption=controlListItemAnswer.ControlListXEntity.PeriodicTask.Caption),$modal.open({templateUrl:"app/controlList/views/controlListCompletionModal.html",size:"xl",controller:"ControlListCompletionModalController",resolve:{params:function(){return{workOrderCaption:caption,controlList:$scope.model,controlListXEntity:controlListItemAnswer.ControlListXEntity,restrictEdit:!0}}}})};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.controlListItemAnswersContextMenuOptions=function(item){var options=[];return options.push({html:' '+translationService.translate("web-controlList-answersTab-controlListXEntityContextMenuOptions-openControlList","Åpne kontrolliste")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.openControlList(item)}}),$scope.hasReadAccess("WorkOrder")&&item.ControlListXEntity.GuidWorkOrder&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.ControlListXEntity.GuidWorkOrder}),translationService.translate("web-controlList-answersTab-controlListItemAnswersContextMenuOptions-workOrder-view","Åpne arbeidsordre"))),$scope.hasReadAccess("PeriodicTask")&&item.ControlListXEntity.GuidPeriodicTask&&options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:item.ControlListXEntity.GuidPeriodicTask}),translationService.translate("web-controlList-answersTab-controlListItemAnswersContextMenuOptions-periodicTask-view","Åpne periodisk rutine"))),$scope.hasReadAccess("Area")&&item.ControlListXEntity.GuidArea&&(item.ControlListXEntity.Area.IsHousing?options.push(getMenuLink($rootScope.navigation.href("housing.edit",{guid:item.ControlListXEntity.GuidArea}),translationService.translate("web-controlList-answersTab-controlListItemAnswersContextMenuOptions-housing-view","Åpne bolig"))):options.push(getMenuLink($rootScope.navigation.href("area.edit",{guid:item.ControlListXEntity.GuidArea}),translationService.translate("web-controlList-answersTab-controlListItemAnswersContextMenuOptions-area-view","Åpne rom")))),$scope.hasReadAccess("Equipment")&&item.ControlListXEntity.GuidEquipment&&options.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:item.ControlListXEntity.GuidEquipment}),translationService.translate("web-controlList-answersTab-controlListItemAnswersContextMenuOptions-equipment-view","Åpne anlegg"))),options}}angular.module("Plania").directive("controlListAnswersDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate",activateAutocomplete:"=activateAutocomplete",currentTab:"=currentTab"},controller:["$scope","TranslationService","$rootScope","$timeout","$modal",controller],templateUrl:"app/controlList/views/editControlListViews/controlListAnswers.html"}})}(),function(){function controller($scope,ngTableParams,repository,translationService,$modal,$rootScope,listService,$timeout){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.rootScope=$rootScope,$scope.hasModule=$rootScope.hasModule,$scope.controlListXEntitySearch={focus:!1,toggle:!1},$scope.hasPageLoaded="connections"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"connections"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)});$scope.testingCondition=!1,$scope.controlListXEntityPeriodicTaskFilter={PropertyFilter:[{Property:"GuidPeriodicTask",Operator:"<>",Value:null},{Property:"GuidControlList",Operator:"=",Value:$scope.model.Guid},{Property:"PeriodicTask.IsDeactivated",Operator:"=",Value:!1}]},$scope.controlListXEntityActions=[];var setControlListXEntityActions=function(){$scope.controlListXEntityActions=[],$scope.hasCreateAccess("ControlListXEntity")&&"Published"===$scope.model.VersionStatus&&$scope.controlListXEntityActions.push({icon:"fa-plus",tooltip:translationService.translate("web-controlList-periodicTask-add","Legg til periodiske rutiner"),onClick:function(){$scope.openPeriodicModal()}})};setControlListXEntityActions(),$scope.controlListXEntityPeriodicTaskColumns=["PeriodicTask.GuidEstate","PeriodicTask.GuidBuilding","Area.IsHousing"],$scope.controlListXEntityPeriodicTaskOptions={reload:!1},$scope.controlListXEntityPeriodicTaskContext=planiaUtils.contextIds.controlListControlListXEntityPeriodicTask,$scope.$watch("model.VersionStatus",function(oldVal,newVal){oldVal!==newVal&&setControlListXEntityActions()}),$scope.openPeriodicModal=function(){if("Published"===$scope.model.VersionStatus)return $scope.model.UseWithArea||$scope.model.UseWithEquipment||$scope.model.UseWithWorkOrder?void $modal.open({templateUrl:"app/controlList/views/controlListPeriodicTaskModal.html",controller:"ControlListPeriodicTaskModalController",size:"xl",resolve:{modalParams:function(){return{guid:$scope.model.Guid,canConnect:{UseWithArea:$scope.model.UseWithArea,UseWithEquipment:$scope.model.UseWithEquipment,UseWithWorkOrder:$scope.model.UseWithWorkOrder}}}}}).result.then(function(){$scope.controlListXEntityPeriodicTaskOptions.reload=!$scope.controlListXEntityPeriodicTaskOptions.reload}):void repository.growl(translationService.translate("web-controlList-useWith-error","Kan ikke koble periodiske rutiner fordi kontrollisten er satt opp til å ikke kunne kobles opp til arbeidsordre, anlegg eller areal"),"danger")},$scope.removePeriodicTaskConnection=function(controlListXEntity){"Draft"===$scope.model.VersionStatus&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-controlListXEntity-message","Knytningen mellom kontrollisten og den periodiske rutinen vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-controlListXEntity-button-confirm","Ja, fjern knytning"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.deleteSingle(repository.apiData.controlListXEntity.url,controlListXEntity.Guid).then(function(result){swal(translationService.translate("web-swal-controlListXEntity-success","Knytningen ble fjernet!"),result,"success"),$scope.controlListXEntityPeriodicTaskOptions.reload=!$scope.controlListXEntityPeriodicTaskOptions.reload},function(error){swal("Error",error,"error")})})};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.controlListXEntityContextMenuOptions=function(item){var options=[];return item.GuidPeriodicTask&&$scope.hasReadAccess("PeriodicTask")&&(options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:item.GuidPeriodicTask}),translationService.translate("web-controlList-connectionsTab-controlListXEntityContextMenuOptions-periodicTask-view","Åpne periodisk rutine"))),item.PeriodicTask&&(item.PeriodicTask.GuidEstate&&$scope.hasReadAccess("Estate")&&options.push(getMenuLink($rootScope.navigation.href("estate.edit",{guid:item.PeriodicTask.GuidEstate}),translationService.translate("web-controlList-connectionsTab-controlListXEntityContextMenuOptions-estate-view","Åpne eiendom"))),item.PeriodicTask.GuidBuilding&&$scope.hasReadAccess("Building")&&options.push(getMenuLink($rootScope.navigation.href("building.edit",{guid:item.PeriodicTask.GuidBuilding}),translationService.translate("web-controlList-connectionsTab-controlListXEntityContextMenuOptions-building-view","Åpne bygg"))))),$scope.hasReadAccess("Area")&&item.GuidArea&&(item.Area.IsHousing?options.push(getMenuLink($rootScope.navigation.href("housing.edit",{guid:item.GuidArea}),translationService.translate("web-controlList-connectionsTab-controlListXEntityContextMenuOptions-housing-view","Åpne bolig"))):options.push(getMenuLink($rootScope.navigation.href("area.edit",{guid:item.GuidArea}),translationService.translate("web-controlList-connectionsTab-controlListXEntityContextMenuOptions-area-view","Åpne rom")))),$scope.hasReadAccess("Equipment")&&item.GuidEquipment&&options.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:item.GuidEquipment}),translationService.translate("web-controlList-connectionsTab-controlListXEntityContextMenuOptions-equipment-view","Åpne anlegg"))),$scope.hasDeleteAccess("ControlListXEntity")&&"Draft"===$scope.model.VersionStatus&&options.push({html:' '+translationService.translate("web-controlList-connectionsTab-controlListXEntityContextMenuOptions-removePeriodicTaskConnection","Fjern knytning")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.removePeriodicTaskConnection(item)}}),options},$scope.addNewColumn=function(){if("Draft"===$scope.model.VersionStatus){$modal.open({templateUrl:"app/common/views/addNewListColumnModal.html",controller:"AddNewListColumnController",resolve:{params:function(){return{prefix:repository.apiData.workOrder.prefix,showAdvancedMode:!0}}}}).result.then(function(selectedColumns){selectedColumns.forEach(function(column){column.Filter=[{Operator:"=",Property:column.Property}],$scope.conditionColumns.push(column)})})}},$scope.testConditions=function(){if("Draft"===$scope.model.VersionStatus&&$scope.conditionColumns&&0!==$scope.conditionColumns.length&&!$scope.testingCondition){var kpi={Prefix:repository.apiData.workOrder.prefix,FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,PropertyFilter:[],Properties:[{Property:"Guid",Function:"count"}]};$scope.conditionColumns.forEach(function(col){col.Filter&&kpi.PropertyFilter.push(angular.copy(col.Filter[0]))}),$scope.testingCondition=!0,repository.createSingle(repository.apiData.kpi.url,kpi).then(function(result){if(result&&result[0]&&result[0].Result&&result[0].Result[0]){var res=result[0].Result[0];repository.growl(res.Value+" "+translationService.translate("web-controlList-conditions-testConditions-result","arbeidsordre oppfylte betingelsene"),"info")}$scope.testingCondition=!1},function(error){repository.growl(error,"danger"),$scope.testingCondition=!1})}},$scope.$on($scope.rootScope.events.newSelection,function(){setControlListXEntityActions()})}angular.module("Plania").directive("controlListConnectionsDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate",activateAutocomplete:"=activateAutocomplete",currentTab:"=currentTab",conditionColumns:"=conditionColumns"},controller:["$scope","ngTableParams","Repository","TranslationService","$modal","$rootScope","ListService","$timeout",controller],templateUrl:"app/controlList/views/editControlListViews/controlListConnections.html"}})}(),function(){function controller($scope,ngTableParams,repository,translationService,$modal,$rootScope,listService,$timeout){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.controlListXEntitySearch={focus:!1,toggle:!1},$scope.hasPageLoaded="history"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"history"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)});$scope.dropdownFilters=[{value:"all",name:translationService.translate("web-controlList-historyTab-controlListXEntityTable-all","Alle")},{value:"new",name:translationService.translate("web-controlList-historyTab-controlListXEntityTable-new","Nye")},{value:"active",name:translationService.translate("web-controlList-historyTab-controlListXEntityTable-active","Aktive")},{value:"completed",name:translationService.translate("web-controlList-historyTab-controlListXEntityTable-completed","Fullførte")},{value:"notexecuted",name:translationService.translate("web-controlList-historyTab-controlListXEntityTable-notExecuted","Ikke utført")}],$scope.selectedDropdownFilter=$scope.dropdownFilters[0],$scope.applyDropdownFilter=function(dropdownFilter,filter){switch(dropdownFilter.value){case"all":break;case"new":filter.FilterModel.Rules.push({Property:"Status",Operator:"=",Value:"0"});break;case"active":filter.FilterModel.Rules.push({Property:"Status",Operator:"=",Value:"1"});break;case"completed":filter.FilterModel.Rules.push({Property:"Status",Operator:"=",Value:"2"});break;case"notexecuted":filter.FilterModel.Rules.push({Property:"Status",Operator:"=",Value:"3"})}},$scope.controlListXEntityFilter={FilterModel:{Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"ControlList.GuidMasterRecord",Operator:"=",Value:$scope.model.Guid},{Property:"ControlList.Guid",Operator:"=",Value:$scope.model.Guid}]}]}},$scope.controlListXEntityColumns=["WorkOrder.Id","WorkOrder.Description","Area.Id","Area.Description","Area.IsHousing","Equipment.Id","Equipment.Description"],$scope.controlListXEntityContext=planiaUtils.contextIds.controlListControlListXEntityHistory,$scope.openControlList=function(item){var caption="";item.WorkOrder?caption=item.WorkOrder.Caption:item.PeriodicTask&&(caption=item.PeriodicTask.Caption),$modal.open({templateUrl:"app/controlList/views/controlListCompletionModal.html",size:"xl",controller:"ControlListCompletionModalController",resolve:{params:function(){return{workOrderCaption:caption,controlList:$scope.model,controlListXEntity:item,restrictEdit:!0}}}})};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.controlListXEntityContextMenuOptions=function(item){var options=[];return options.push({html:' '+translationService.translate("web-controlList-historyTab-controlListXEntityContextMenuOptions-openControlList","Åpne kontrolliste")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.openControlList(item)}}),$scope.hasReadAccess("WorkOrder")&&item.GuidWorkOrder&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidWorkOrder}),translationService.translate("web-controlList-historyTab-controlListXEntityContextMenuOptions-workOrder-view","Åpne arbeidsordre"))),$scope.hasReadAccess("PeriodicTask")&&item.GuidPeriodicTask&&options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:item.GuidPeriodicTask}),translationService.translate("web-controlList-historyTab-controlListXEntityContextMenuOptions-periodicTask-view","Åpne periodisk rutine"))),$scope.hasReadAccess("Area")&&item.GuidArea&&(item.Area.IsHousing?options.push(getMenuLink($rootScope.navigation.href("housing.edit",{guid:item.GuidArea}),translationService.translate("web-controlList-historyTab-controlListXEntityContextMenuOptions-housing-view","Åpne bolig"))):options.push(getMenuLink($rootScope.navigation.href("area.edit",{guid:item.GuidArea}),translationService.translate("web-controlList-historyTab-controlListXEntityContextMenuOptions-area-view","Åpne rom")))),$scope.hasReadAccess("Equipment")&&item.GuidEquipment&&options.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:item.GuidEquipment}),translationService.translate("web-controlList-historyTab-controlListXEntityContextMenuOptions-equipment-view","Åpne anlegg"))),options}}angular.module("Plania").directive("controlListHistoryDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate",activateAutocomplete:"=activateAutocomplete",currentTab:"=currentTab"},controller:["$scope","ngTableParams","Repository","TranslationService","$modal","$rootScope","ListService","$timeout",controller],templateUrl:"app/controlList/views/editControlListViews/controlListHistory.html"}})}(),function(){function controller($scope,ngTableParams,repository,translationService,iconService,$modal,$rootScope,listService,$timeout,colorService){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasEditAccess=$rootScope.hasEditAccess,$scope.hasModule=$rootScope.hasModule,$scope.iconMap=iconService.GetIconMap(),$scope.getIcon=iconService.getIcon,$scope.viewMode=$scope.isUpdate,$scope.controlListRevisionTableSearch={focus:!1,toggle:!1},$scope.hasPageLoaded="info"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"info"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)});$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.openIconModal=function(){$modal.open({templateUrl:"app/common/modal/views/selectIconModal.html",controller:"SelectIconModalController"}).result.then(function(selectedIcon){$scope.model.Icon=selectedIcon})},$scope.canSetNotExecutedChanged=function(model){model.canSetNotExecuted||($scope.model.GuidReferenceTypeNotExecuted="",delete $scope.model.ReferenceTypeNotExecuted)},$scope.controlListRevisionColumns=[{Position:1,Title:translationService.translate("web-controlList-revisionTable-controlList-version","Versjon"),Property:"Version",PropertyType:"string"},{Position:2,Title:translationService.translate("web-controlList-revisionTable-controlList-versionStatus","Status"),Property:"VersionStatus",PropertyType:"enum.ControlListVersionStatus"},{Position:3,Title:translationService.translate("web-controlList-revisionTable-controlList-updatedDate","Oppdatert"),Property:"UpdatedDate",PropertyType:"date"},{Position:4,Title:translationService.translate("web-controlList-revisionTable-controlList-versionComment","Kommentar"),Property:"VersionComment",PropertyType:"string"}];var getRevisionTable=function(){if($scope.isUpdate)return $scope.controlListRevisionTable?void $scope.controlListRevisionTable.reload():void($scope.controlListRevisionTable=new ngTableParams({page:1,count:10,sorting:{Version:"desc"},filter:{VersionContext:"AllVersions",PropertyFilter:[{Property:"GuidMasterRecord",Operator:"=",Value:$scope.model.GuidMasterRecord}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];$scope.controlListRevisionColumns.forEach(function(col){col.Property&&columns.push(col.Property)}),repository.GetPaginated(repository.apiData.controlList.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.controlListRevisionTable.settings().total=result.TotalCount,$scope.controlListRevisionTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))};$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.isUpdate&&$scope.$watch("model.GuidMasterRecord",function(newVal){newVal&&getRevisionTable()}),$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"referenceType":return filter.PropertyFilter=[{Property:"Context",Operator:"=",Value:2}],filter}return filter};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.goToVersion=function(guid){guid&&guid!==$scope.model.Guid&&window.open($rootScope.navigation.href("controlList.edit",{guid:guid}),"_blank")},$scope.revisionTableContextMenu=function(item){var options=[];return item.Guid!==$scope.model.Guid&&options.push(getMenuLink($rootScope.navigation.href("controlList.edit",{guid:item.Guid}),translationService.translate("web-controlList-infoTab-revisionTableContextMenu-controlList-view","Åpne kontrolliste"))),options}}angular.module("Plania").directive("controlListInfoDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate",activateAutocomplete:"=activateAutocomplete",currentTab:"=currentTab"},controller:["$scope","ngTableParams","Repository","TranslationService","IconService","$modal","$rootScope","ListService","$timeout","ColorService",controller],templateUrl:"app/controlList/views/editControlListViews/controlListInfo.html"}})}(),function(){function controller($scope,repository,translationService,$modal,$rootScope,$q,scrollService){$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.conflictingIndexPosition={},$scope.isInvalidRule=function(rule){return!rule.IsValid};var scrollToItem=function(item){item&&scrollService.scrollToElement(item.IndexPosition)},defaultRadioOptions=[{Value:translationService.translate("web-controllist-answer-Yes","Ja")},{Value:translationService.translate("web-controllist-answer-No","Nei")},{Value:translationService.translate("web-controllist-answer-NotApplicable","Ikke aktuelt")}],defaultChecklistOptions=[{Value:translationService.translate("web-controllist-answer-Ok","Ok")},{Value:translationService.translate("web-controllist-answer-NotOk","Ikke Ok")},{Value:translationService.translate("web-controllist-answer-NotApplicable","Ikke aktuelt")}];$scope.fieldTypeItems=[],function(){var fieldTypeItems=[{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-SectionHeader","Seksjonstittel"),Type:"SectionHeader",icon:"font",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-Info","Beskrivelse"),Type:"Info",icon:"info",Data:{Description:"Informasjonstekst"},disabled:!$scope.hasModule("ControlList")}];$scope.hasModule("Deviation")&&fieldTypeItems.push({Guid:null,Name:translationService.translate("web-enum-controllistitemtype-Checklist","Sjekklistepunkt"),Type:"Checklist",icon:"list-ul",disabled:!1,IsMandatory:!$scope.hasModule("ControlList"),Data:{Options:defaultChecklistOptions}}),fieldTypeItems.push({Guid:null,Name:translationService.translate("web-enum-controllistitemtype-RadioButton","Radioknapper"),Type:"RadioButton",Data:{Options:defaultRadioOptions},icon:"dot-circle",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-Combo","Nedtrekksfelt"),Type:"Combo",Data:{Options:defaultRadioOptions},icon:"circle-chevron-down",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-Text","Kort svar"),Type:"Text",icon:"text",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-TextArea","Utfyllende svar"),Type:"TextArea",icon:"text",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-Numeric","Nummer"),Type:"Numeric",icon:"input-numeric",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-CheckBox","Sjekkboks"),Type:"CheckBox",icon:"square-check",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-Date","Dato"),Type:"Date",icon:"calendar",disabled:!$scope.hasModule("ControlList")}),$scope.fieldTypeItems=fieldTypeItems}(),$scope.setSelectedFormItem=function(item){$scope.saveCurrentItem(),$scope.selectedFormItem=item,$scope.reloadFormElements=!0,$scope.copyOfSelectedItem=angular.copy($scope.selectedFormItem)},$scope.setSelectedFormItemFromGuid=function(guidControlListItem){$scope.saveCurrentItem(),$scope.selectedFormItem=_.find($scope.model.ControlListItems,function(o){return o.Guid.toLowerCase()===guidControlListItem.toLowerCase()}),scrollToItem($scope.selectedFormItem),$scope.copyOfSelectedItem=angular.copy($scope.selectedFormItem)},$scope.isRelatedToSelectedItem=function(item){if(!$scope.selectedFormItem||item.Guid===$scope.selectedFormItem.Guid)return!1;var itemRules=_.filter($scope.model.ControlListRules,{GuidControlListItem:item.Guid}),selectedItemRules=_.filter($scope.model.ControlListRules,{GuidControlListItem:$scope.selectedFormItem.Guid});if(!selectedItemRules&&!itemRules)return!1;var result=!1;return itemRules.forEach(function(rule){_.filter(rule.Conditions.Filter,{GuidControlListItem:$scope.selectedFormItem.Guid}).length>0&&(result=!0)}),selectedItemRules.forEach(function(rule){_.filter(rule.Conditions.Filter,{GuidControlListItem:item.Guid}).length>0&&(result=!0)}),result},$scope.getControlListItem=function(guidControlListItem){if(guidControlListItem){var controlListItem=_.find($scope.model.ControlListItems,function(o){return!!o.Guid&&o.Guid.toLowerCase()===guidControlListItem.toLowerCase()});if(controlListItem)return controlListItem}},$scope.newControlListLogItemHandler={templateUrl:"app/controlList/views/editControlListLogItemModal.html"},$scope.treeOptions={accept:function(sourceNodeScope,destNodeScope,destIndex){return"Draft"===$scope.model.VersionStatus},dropped:function(event){if(!event.dest.nodesScope.$parent.nodropEnabled)if(event.source.cloneModel&&!event.source.cloneModel.Guid){$scope.setSelectedFormItem(event.source.cloneModel);var postData=angular.copy(event.source.cloneModel);postData.IndexPosition=event.dest.index,postData.GuidControlList=$scope.model.Guid,delete postData.icon,delete postData.Guid,postData.Data&&(postData.Data=JSON.stringify(postData.Data)),createControlListItem(postData).then(function(response){response.Data&&"string"==typeof response.Data&&(response.Data=JSON.parse(response.Data)),$scope.model.ControlListItems[event.dest.index]=response,$scope.selectedFormItem=$scope.model.ControlListItems[event.dest.index],repository.growl("Kontrollpunktet ble lagt til","success"),updateIndexPositions()},function(error){})}else{var draggedDown=event.source.index>event.dest.index;draggedDown?event.dest.index:event.source.index,draggedDown?event.source.index:event.dest.index,setTimeout(function(){updateIndexPositions()},0)}}};var createControlListItem=function(postData){if("Draft"===$scope.model.VersionStatus){var deferred=$q.defer();return repository.createSingle(repository.apiData.controlListItem.url,postData).then(function(response){deferred.resolve(response)},function(error){deferred.reject(error)}),deferred.promise}};$scope.addControlListItem=function(selectedType){if("Draft"===$scope.model.VersionStatus){var postData=angular.copy(selectedType);postData.IndexPosition=0===$scope.model.ControlListItems.length?0:$scope.model.ControlListItems[$scope.model.ControlListItems.length-1].IndexPosition+1,postData.GuidControlList=$scope.model.Guid,postData.isSaving=!0,$scope.model.ControlListItems.push(postData),delete postData.icon,delete postData.Guid,postData.Data&&(postData.Data=JSON.stringify(postData.Data)),createControlListItem(postData).then(function(response){response.Data&&"string"==typeof response.Data&&(response.Data=JSON.parse(response.Data));var index=_.findIndex($scope.model.ControlListItems,{IndexPosition:response.IndexPosition});response.isSaving=!1,$scope.model.ControlListItems[index]=response,$scope.setSelectedFormItem($scope.model.ControlListItems[index]),scrollToItem($scope.selectedFormItem)},function(error){swal("Error",error.Message,"error")})}},$scope.copyFormItem=function(item,index){if("Draft"===$scope.model.VersionStatus){var copiedItem=angular.copy(item);copiedItem.IndexPosition=item.IndexPosition+1,delete copiedItem.Guid, copiedItem.Data&&(copiedItem.Data=JSON.stringify(copiedItem.Data)),repository.createSingle(repository.apiData.controlListItem.url,copiedItem).then(function(response){response.Data&&"string"==typeof response.Data&&(response.Data=JSON.parse(response.Data)),$scope.model.ControlListItems.splice(index+1,0,response),$scope.selectedFormItem=$scope.model.ControlListItems[index+1],updateIndexPositions()},function(error){repository.showError(error)})}},$scope.removeFormItem=function(item){"Draft"===$scope.model.VersionStatus&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-controlListItem-message","Kontrollpunktet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-controlListItem-button-confirm","Ja, fjern kontrollpunktet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.controlListItem.url,item.Guid).then(function(response){swal.close(),repository.growl("Kontrollpunktet har blitt fjernet","success"),item===$scope.selectedFormItem&&($scope.selectedFormItem=null);var foundInFormItems=_.find($scope.model.ControlListItems,item);if(foundInFormItems){var index=_.findIndex($scope.model.ControlListItems,foundInFormItems);$scope.model.ControlListItems.splice(index,1),updateIndexPositions()}else $scope.model.ControlListItems.forEach(function(formItem){formItem.items&&_.find(formItem.items,item)&&formItem.items.splice(_.findIndex(formItem.items,item),1)});var affectedRules=_.filter($scope.model.ControlListRules,function(o){return o.GuidControlListItem===item.Guid});affectedRules.length>0&&affectedRules.forEach(function(rule){var index=_.findIndex($scope.model.ControlListRules,{Guid:rule.Guid});$scope.model.ControlListRules.splice(index,1)})},function(error){swal("Error",error.Message,"error")})})};var checkForConflictingIndexPositions=function(){var positions={},conflicts={};$scope.model.ControlListItems&&Array.isArray($scope.model.ControlListItems)&&$scope.model.ControlListItems.forEach(function(item){positions[item.IndexPosition]?(conflicts[item.IndexPosition]||(conflicts[item.IndexPosition]=[]),conflicts[item.IndexPosition].push(item.Guid)):positions[item.IndexPosition]=!0}),conflicts.length=Object.keys(conflicts).length,$scope.conflictingIndexPosition=conflicts},updateIndexPositions=function(){if("Draft"===$scope.model.VersionStatus){var objectsToUpdate=[];$scope.model.ControlListItems.forEach(function(item,index){item.IndexPosition!==index&&(item.IndexPosition=index,objectsToUpdate.push({Guid:item.Guid,IndexPosition:index}))}),repository.patch(repository.apiData.controlListItem.url,null,objectsToUpdate).then(function(){checkForConflictingIndexPositions()})}};$scope.addOption=function(index){"Draft"===$scope.model.VersionStatus&&$scope.selectedFormItem.Data.Options&&$scope.selectedFormItem.Data.Options.splice(index+1,0,{value:""})},$scope.removeOption=function(index){"Draft"===$scope.model.VersionStatus&&$scope.selectedFormItem.Data.Options&&(1===$scope.selectedFormItem.Data.Options.length?swal("Du kan ikke slette siste alternativ","","error"):$scope.selectedFormItem.Data.Options.splice(index,1))};var reloadControlListRules=function(){"Draft"===$scope.model.VersionStatus&&repository.GetPaginated(repository.apiData.controlListRule.url,0,-1,{},{PropertyFilter:[{Property:"GuidControlList",Operator:"=",Value:$scope.model.Guid}]},"").then(function(response){$scope.model.ControlListRules=response.List,$scope.model.ControlListRules.forEach(function(item){item.Conditions&&(item.Conditions=JSON.parse(item.Conditions)),item.Parameters&&(item.Parameters=JSON.parse(item.Parameters))})})};$scope.addRule=function(selectedFormItem){"Draft"===$scope.model.VersionStatus&&$modal.open({templateUrl:"app/controlList/views/ruleModal.html",size:"lg",controller:"RuleModalController",resolve:{params:function(){return{selectedFormItem:selectedFormItem,controlListItems:$scope.model.ControlListItems}}}}).result.then(function(newRule){newRule.GuidControlList=$scope.model.Guid,createNewRule(newRule)})},$scope.editRule=function(rule,selectedFormItem){"Draft"===$scope.model.VersionStatus&&$modal.open({templateUrl:"app/controlList/views/ruleModal.html",size:"lg",controller:"RuleModalController",resolve:{params:function(){return{selectedFormItem:selectedFormItem,controlListItems:$scope.model.ControlListItems,rule:rule}}}}).result.then(function(editedRule){var postData=angular.copy(editedRule);postData.Conditions=JSON.stringify(postData.Conditions),postData.Parameters=JSON.stringify(postData.Parameters),repository.updateSingle(repository.apiData.controlListRule.url,postData).then(function(response){response.Conditions&&(response.Conditions=JSON.parse(response.Conditions)),response.Parameters&&(response.Parameters=JSON.parse(response.Parameters)),editedRule=response,reloadControlListRules()},function(error){swal("Error",error.Message,"error")})})};var createNewRule=function(newRule){"Draft"===$scope.model.VersionStatus&&("object"==typeof newRule.Conditions&&(newRule.Conditions=angular.toJson(newRule.Conditions)),"object"==typeof newRule.Parameters&&(newRule.Parameters=angular.toJson(newRule.Parameters)),repository.createSingle(repository.apiData.controlListRule.url,newRule).then(function(response){$scope.model.ControlListRules||($scope.model.ControlListRules=[]),"string"==typeof response.Conditions&&(response.Conditions=JSON.parse(response.Conditions)),"string"==typeof response.Parameters&&(response.Parameters=JSON.parse(response.Parameters)),$scope.model.ControlListRules.push(response)},function(error){swal("Error",error,"error")}))};$scope.removeRule=function(rule,index){"Draft"===$scope.model.VersionStatus&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-controlListRule-message","Regelen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-controlListRule-button-confirm","Ja, fjern regelen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){repository.deleteSingle(repository.apiData.controlListRule.url,rule.Guid).then(function(result){repository.growl(translationService.translate("web-swal-controlListRule-success","Regelen ble fjernet!"),"success"),index||(index=_.findIndex($scope.model.ControlListRules,{Guid:rule.Guid})),$scope.model.ControlListRules.splice(index,1)},function(error){swal("Error",error.Message,"error")})})},$scope.controlListRuleContextMenuOptions=function(item,index){var options=[];return options.push({html:' '+translationService.translate("web-controlList-setupTab-controlListRuleContextMenuOptions-editRule","Rediger regel")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.editRule(item)}}),options.push({html:' '+translationService.translate("web-controlList-setupTab-controlListRuleContextMenuOptions-removeRule","Slett regel")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.removeRule(item,index)}}),options},$scope.$watch("selectedFormItem",function(newVal,oldVal){newVal!==oldVal&&($scope.activateAutocomplete=!1,setTimeout(function(){$scope.activateAutocomplete=!0},250))}),$scope.$watchCollection("model.ControlListItems",function(newVal,oldVal){newVal!==oldVal&&newVal&&($scope.checkListItems=_.filter(newVal,function(item){return"Checklist"===item.Type}))}),$scope.$watchCollection("model.ControlListItems",function(newVal){checkForConflictingIndexPositions()})}angular.module("Plania").directive("controlListSetupDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",restrictDelete:"=restrictDelete",reload:"=reload",isUpdate:"=isUpdate",activateAutocomplete:"=activateAutocomplete",currentTab:"=currentTab",selectedFormItem:"=selectedFormItem",copyOfSelectedItem:"=copyOfSelectedItem",saveCurrentItem:"=saveCurrentItem"},controller:["$scope","Repository","TranslationService","$modal","$rootScope","$q","ScrollService",controller],templateUrl:"app/controlList/views/editControlListViews/controlListSetup.html"}})}(),function(){function controller($scope,$modalInstance,repository,params,translationService,$modal){function removeAutocompleteLabelValues(){$scope.rule.Parameters.forEach(function(parameter){parameter.IsExpandable&¶meter.Value&&delete parameter.Value.Label,parameter.data&&delete parameter.data})}function removeEmptyParameterValueFields(){$scope.rule.Parameters.forEach(function(parameter){parameter.Value&&$scope.isArray(parameter.Value)&&(parameter.Value=_.filter(parameter.Value,function(val){return!!val}))})}$scope.activateAutocomplete=!1,$scope.isArray=angular.isArray,$scope.controlListItems=params.controlListItems,$scope.selectedFormItem=params.selectedFormItem,$scope.prefillKeywords=repository.prefillKeyWords,$scope.operators=["=","<>",">","<",">=","<="],$scope.parameterColumns=[],$scope.groupedControlListItems=[],$scope.availableActions=[{Value:"Show",icon:"eye"},{Value:"Hide",icon:"eye-slash"}],repository.moduleService.hasModule(repository.moduleService.moduleFlags.Deviation)&&($scope.availableActions.push({Value:"Deviation",icon:"octagon-exclamation"}),$scope.availableActions.push({Value:"ClosedDeviation",icon:"octagon-exclamation"})),repository.moduleService.hasModule(repository.moduleService.moduleFlags.Activity)&&$scope.availableActions.push({Value:"Request",icon:"envelope"});var currentSection=null;params.controlListItems.forEach(function(controlListItem){"SectionHeader"===controlListItem.Type?currentSection=controlListItem.Name:"Info"!==controlListItem.Type&&(currentSection&&(controlListItem.Section=currentSection),$scope.groupedControlListItems.push(controlListItem))});var parseConditions=function(condition){return condition&&condition.Filter&&_.each(condition.Filter,function(filter){filter.GuidControlListItem=filter.GuidControlListItem.toLowerCase()}),condition};params.rule?($scope.rule=angular.copy(params.rule),$scope.rule.Conditions=parseConditions($scope.rule.Conditions),$scope.selectedAction=$scope.rule.Action,removeAutocompleteLabelValues()):$scope.rule={GuidControlListItem:$scope.selectedFormItem?$scope.selectedFormItem.Guid:null,Action:null,Conditions:{Filter:[{Operator:"="}]},IsMandatory:!1,Parameters:[]},setTimeout(function(){$scope.activateAutocomplete=!0},250),$scope.selectAction=function(action){if(action.Value!==$scope.selectedAction){switch($scope.selectedAction=action.Value,$scope.selectedAction){case"Request":$scope.parameterColumns=requestColumns;break;case"Deviation":case"ClosedDeviation":$scope.parameterColumns=deviationColumns}$scope.rule={GuidControlListItem:$scope.selectedFormItem?$scope.selectedFormItem.Guid:null,Action:action.Value,Conditions:{Filter:[{GuidControlListItem:"Deviation"!==$scope.selectedAction&&"Request"!==$scope.selectedAction&&"ClosedDeviation"!==$scope.selectedAction||!$scope.selectedFormItem?null:$scope.selectedFormItem.Guid,Operator:"="}]},IsMandatory:!1,Parameters:[]}}},$scope.changedGuidControlListItem=function(){if(!$scope.selectedFormItem&&("Deviation"===$scope.selectedAction||"Request"===$scope.selectedAction||"ClosedDeviation"===$scope.selectedAction)){$scope.rule&&$scope.rule.Conditions&&$scope.rule.Conditions&&$scope.rule.Conditions.Filter&&$scope.rule.Conditions.Filter[0]&&$scope.rule.Conditions.Filter[0].GuidControlListItem&&($scope.rule.GuidControlListItem=$scope.rule.Conditions.Filter[0].GuidControlListItem)}};var deviationColumns,requestColumns,locale=translationService.getLocale();repository.getWithUrlParameter(repository.apiData.webColumns.url,"domainModel=Deviation_RuleSelection&locale="+locale).then(function(result){deviationColumns=result,"Deviation"!==$scope.rule.Action&&"ClosedDeviation"!==$scope.rule.Action||($scope.parameterColumns=deviationColumns)}),repository.getWithUrlParameter(repository.apiData.webColumns.url,"domainModel=Request_RuleSelection&locale="+locale).then(function(result){requestColumns=result,"Request"===$scope.rule.Action&&($scope.parameterColumns=requestColumns)}),$scope.changedParameter=function(parameter){parameter.Value=null;var parameterColumn=_.find($scope.parameterColumns,function(o){return o.Property===parameter.Property});parameter.PropertyType=parameterColumn.PropertyType,parameter.IsExpandable=parameterColumn.IsExpandable,"bool"===parameter.PropertyType&&(parameter.Value=!0),parameterColumn.GuidProperty&&(parameter.GuidProperty=parameterColumn.GuidProperty)},$scope.changedAutoCompleteValue=function(value){value||(value={})},$scope.getTypeOf=function(value){return null===value&&(value={}),typeof value},$scope.getPrefillOptionsForAutocomplete=function(parameter){if(!parameter||!parameter.PropertyType)return[];switch(parameter.PropertyType.toLowerCase()){case"person":return repository.prefillKeyWords.filter(function(keyword){return"@LoggedInPerson"===keyword})}return[]},$scope.getItemFromGuid=function(guid){if(guid){return _.find($scope.controlListItems,{Guid:guid.toLowerCase()})}},$scope.isGuid=function(stringToTest){return!!stringToTest&&/^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$/gi.test(stringToTest)},$scope.showParameterTextInput=function(parameter){return!($scope.isArray(parameter.Value)&&0!==parameter.Value.length||$scope.isGuid(parameter.Value))},$scope.addParameterValue=function(parameter){$scope.isArray(parameter.Value)&¶meter.Value[parameter.Value.length-1]&¶meter.Value.push("")},$scope.removeParameterValue=function(parameter,index){$scope.isArray(parameter.Value)?(parameter.Value.splice(index,1),0===parameter.Value.length&&(parameter.Value=null)):parameter.Value=null},$scope.onPrefillControlListItemClick=function(parameter,item,index){("Deviation"===$scope.rule.Action||"ClosedDeviation"===$scope.rule.Action)&&"ActionComment"===parameter.Property||"Request"===$scope.rule.Action&&"ExplanatoryText"===parameter.Property?(parameter.Value?!$scope.isArray(parameter.Value)&&$scope.isGuid(parameter.Value)?parameter.Value=[parameter.Value]:$scope.isArray(parameter.Value)||(parameter.Value=[]):parameter.Value=[],void 0!==index&&null!==index||(index=0),parameter.Value[index]=item.Guid):parameter.Value=item.Guid},$scope.openControlListItemSelectionModal=function(parameter,index){$modal.open({templateUrl:"app/controlList/views/controlListItemSelectionModal.html",controller:"ControlListItemSelectionModalController",resolve:{params:function(){return{controlListItems:params.controlListItems}}}}).result.then(function(item){$scope.onPrefillControlListItemClick(parameter,item,index)})},$scope.ok=function(){removeAutocompleteLabelValues(),removeEmptyParameterValueFields(),$modalInstance.close($scope.rule)},$scope.cancel=function(){$modalInstance.dismiss("cancel")},$scope.autoCompleteFilter=function(filterName){switch(filterName){case"priority":if("Deviation"===$scope.selectedAction||"ClosedDeviation"===$scope.selectedAction)return{PropertyFilter:[{Property:"EntityType",Operator:"=",Value:"Deviation"}]}}return{}}}angular.module("Plania").controller("RuleModalController",["$scope","$modalInstance","Repository","params","TranslationService","$modal",controller])}(),function(){function controller($scope,repository,$q,$stateParams,translationService,$modal,$localStorage,accountingService,registeredFieldService){$scope.isUpdate="cost.edit"===$scope.navigation.current.name,$scope.model={Amount:"0"},$scope.selectedSubEntity=null,$scope.modelDto={},$scope.activateAutocomplete=!1,$scope.viewMode=!!$scope.isUpdate,$scope.prefix=repository.commonService.prefix.Cost,$scope.isDocumentsCollapsed=!0,$scope.reloadDocumentTable=!1,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var updateAccess=function(){if($scope.isUpdate){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictSave=!repository.authService.hasEditAccess(repository.commonService.prefix.Cost,checkOtherDo),$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Cost,checkOtherDo),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Cost,checkOtherDo)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Cost)};updateAccess(),$scope.getValidityRules=function(fieldName){if(!$scope.baseFieldrules)return null;var fieldrule=_.filter($scope.baseFieldrules,{DomainFieldName:fieldName})[0];return accountingService.onGetValidityRules($scope.modelDto.dataOwner,fieldrule)},$scope.clearSubEntitySelection=function(){$scope.model.GuidEquipment="",$scope.equipment="",$scope.model.GuidArea="",$scope.area="",$scope.model.GuidProject="",$scope.project=""};var setSubEntityVisibility=function(fieldRules){if(fieldRules){$scope.subEntityVisibility={showEquipment:!_.filter(fieldRules,{DomainFieldName:"GuidEquipment"})[0].Hidden,showArea:!_.filter(fieldRules,{DomainFieldName:"GuidArea"})[0].Hidden,showProject:!_.filter(fieldRules,{DomainFieldName:"GuidProject"})[0].Hidden};var countHiddenFields=0;$scope.subEntityVisibility.showEquipment||countHiddenFields++,$scope.subEntityVisibility.showArea||countHiddenFields++,$scope.subEntityVisibility.showProject||countHiddenFields++,$scope.subEntityVisibility.hidden=2===countHiddenFields||3===countHiddenFields,$scope.subEntityVisibility.showEquipment?$scope.selectedSubEntity="Equipment":$scope.subEntityVisibility.showArea?$scope.selectedSubEntity="Area":$scope.subEntityVisibility.showProject&&($scope.selectedSubEntity="Project")}},setParent=function(parentPropertyName,parent){parent?($scope.model[parentPropertyName]=parent||null,$scope.model["Guid"+parentPropertyName]=parent?parent.Guid:null,$scope.modelDto[_.camelCase(parentPropertyName)+"Caption"]=parent?getAutocompleteString(parent):null):(delete $scope.model[parentPropertyName],delete $scope.model["Guid"+parentPropertyName],$scope.modelDto&&delete $scope.modelDto[_.camelCase(parentPropertyName)+"Caption"])},synchronizeParents=function(){for(var propertyName in $scope.model)if(propertyName.startsWith("Guid")){var parentPropertyName=_.capitalize(propertyName.substring(4)),parent=$scope.model[parentPropertyName];parent&&setParent(parentPropertyName,parent)}},setProperties=function(){$scope.modelDto={dataOwner:$scope.model.DataOwner},synchronizeParents()},columns=["Building.Id","Building.Description","Equipment.Id","Equipment.Description","Area.Id","Area.Description","Project.Id","Project.Decription","Supplier.Id","Supplier.Description","Consumable.Id","Consumable.Description","Account.Id","Account.Description","CostCenter.Id","CostCenter.Description","WorkOrder.Id","WorkOrder.Description","PurchaseOrder.Id","PurchaseOrder.Description","PurchaseOrderItem.Id","PurchaseOrderItem.Description","Accounting0.Id","Accounting0.Description","Accounting1.Id","Accounting1.Description","Accounting2.Id","Accounting2.Description","Accounting3.Id","Accounting3.Description","Accounting4.Id","Accounting4.Description","Department.Id","Department.Description","DataOwner.DepartmentCost","DataOwner.LastDimensionCost","DataOwner.Dimension1","DataOwner.Dimension2","DataOwner.Dimension3","DataOwner.Dimension4","DataOwner.Dimension5"],getPresets=function(){if($scope.isUpdate)return null;var presets=null,setParameter=function(name,value){return!!value&&(presets||(presets={}),presets[name]=value,!0)};if($localStorage.userData.userAccount&&setParameter("GuidAccount",$localStorage.userData.guidAccount),$stateParams.showPersistantData){var persistedData=repository.persistedData.getPersistedData("cost.create");persistedData?(setParameter("GuidProject",persistedData.GuidProject),setParameter("GuidPurchaseOrder",persistedData.GuidPurchaseOrder),setParameter("GuidPurchaseOrderItem",persistedData.GuidPurchaseOrderItem),setParameter("GuidWorkOrder",persistedData.GuidWorkOrder)):setParameter("GuidDepartment",$localStorage.userData.guidDepartment)}return presets},onGet=function(response){var cost=response.Data?response.Data:response;!$scope.baseFieldrules&&response.FieldRules&&($scope.baseFieldrules=response.FieldRules),$scope.model=cost,setSubEntityVisibility(response.FieldRules),$scope.model.GuidEquipment&&($scope.selectedSubEntity="Equipment"),$scope.model.GuidArea&&($scope.selectedSubEntity="Area"),$scope.model.GuidProject&&($scope.selectedSubEntity="Project"),updateAccess(),setProperties(),setTimeout(function(){$scope.activateAutocomplete=!0},250),$scope.isUpdate&&($scope.reload=!0,$scope.reloadDocumentTable=!0),$scope.restrictEdit||($scope.restrictEdit=$scope.model.IsInvoiced),$scope.restrictSave||($scope.restrictSave=$scope.model.IsInvoiced),$scope.restrictDelete||($scope.restrictDelete=$scope.model.IsInvoiced)},getEntity=function(){var defer=$q.defer(),queryString=JSON.stringify(columns);$stateParams.guidEntityToCopy&&(queryString+="&GuidCopyFrom="+$stateParams.guidEntityToCopy);var presets=getPresets();return repository.getMainModel(repository.apiData.cost.url,$scope.isUpdate?$stateParams.guid:"00000000-0000-0000-0000-000000000000",queryString,presets?JSON.stringify(presets):null).then(function(response){onGet(response),defer.resolve(response)}).catch(function(error){repository.growl(error,"danger"),defer.reject()}),defer.promise},getUpdatePayload=function(){var parentProperties=[];for(var propertyName in $scope.model)if(propertyName.startsWith("Guid")){var parentPropertyName=_.capitalize(propertyName.substring(4)),parent=$scope.model[parentPropertyName];parent&&parentProperties.push(parentPropertyName)}var payloadEntity=angular.copy($scope.model);return parentProperties.forEach(function(field){delete payloadEntity[field]}),{payload:payloadEntity,parentProperties:parentProperties}},reApplyParentProperties=function(model,parentProperties){parentProperties.forEach(function(field){!model[field]&&model["Guid"+field]&&$scope.model[field]&&(model[field]=angular.copy($scope.model[field]))})},updateEntity=function(){var defer=$q.defer(),updatePayload=getUpdatePayload();return($scope.isUpdate?repository.updateSingle:repository.createSingle)(repository.apiData.cost.url,updatePayload.payload).then(function(response){reApplyParentProperties(response,updatePayload.parentProperties),onGet(response),defer.resolve(response)}).catch(function(error){repository.growl(error,"danger"),defer.reject()}),defer.promise};getEntity(),$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"equipment":return filter.PropertyFilter=[{Property:"GuidBuilding",Operator:"=",Value:$scope.model.GuidBuilding}],filter.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:!1}),filter;case"area":case"project":return filter.PropertyFilter=[{Property:"GuidBuilding",Operator:"=",Value:$scope.model.GuidBuilding}],filter;case"purchaseOrderItem":return filter.PropertyFilter=[],$scope.model.GuidPurchaseOrder&&filter.PropertyFilter.push({Property:"GuidPurchaseOrder",Operator:"=",Value:$scope.model.GuidPurchaseOrder}),$scope.model.GuidWorkOrder&&filter.PropertyFilter.push({Property:"GuidWorkOrder",Operator:"=",Value:$scope.model.GuidWorkOrder}),$scope.model.GuidProject&&filter.PropertyFilter.push({Property:"WorkOrder.GuidProject",Operator:"=",Value:$scope.model.GuidProject}),filter.PropertyFilter.push({Property:"Status",Operator:"<>",Value:0}),filter.PropertyFilter.push({Property:"Status",Operator:"<>",Value:6}),filter;case"purchaseOrder":return filter.PropertyFilter=[],$scope.model.GuidWorkOrder&&filter.PropertyFilter.push({Property:"PurchaseOrderItem.GuidWorkOrder",Operator:"=",Value:$scope.model.GuidWorkOrder}),$scope.model.GuidProject&&filter.PropertyFilter.push({Property:"PurchaseOrderItem.WorkOrder.GuidProject",Operator:"=",Value:$scope.model.GuidProject}),filter.PropertyFilter.push({Property:"Status",Operator:"<>",Value:0}),filter.PropertyFilter.push({Property:"Status",Operator:"<>",Value:6}),filter;case"workOrder":return $scope.model.GuidProject&&(filter.PropertyFilter=[{Property:"GuidProject",Operator:"=",Value:$scope.model.GuidProject}]),filter}},$scope.update=function(destination){var onUpdate=function(){if($scope.model.PostingDate){var postingDate=new Date($scope.model.PostingDate);postingDate.setHours(postingDate.getHours()+2),$scope.reloadDocumentTable=!0,$scope.model.PostingDate=postingDate.toISOString()}var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-cost-success","Kostnaden har blitt oppdatert."):translationService.translate("create-cost-success","Kostnaden har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):error&&repository.growl(error.Data.Message,"danger")};updateEntity().then(success,error)},amountFieldRule=registeredFieldService.getLocalRegisteredField(repository.apiData.cost.prefix,"Amount");!$scope.model.Amount&&amountFieldRule&&amountFieldRule.Mandatory?swal({title:translationService.translate("web-cost-swal-missingAmount-title","Registrering av kostnad med 0 kr?"),text:translationService.translate("web-cost-swal-missingAmount-text","Ønsker du å fortsette?"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-cost-swal-missingAmount-confirm","Ja"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt")},function(){window.onkeydown=null,window.onfocus=null,onUpdate()}):onUpdate()},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cost-message","Kostnaden vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cost-button-confirm","Ja, fjern Kostnaden"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.cost.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-cost-success","Kostnaden ble fjernet!"),result,"success"),$scope.goBack("priority.list",{menuGuid:$scope.navigation.params.menuGuid})})})};var getAutocompleteString=function(object){if(!object)return"";if(object.Caption)return object.Caption;var caption=object.Id;return object.Description&&(caption+=" - "+object.Description),caption};$scope.isFieldEnabled=function(field){if($scope.restrictEdit)return!1;var model=$scope.model;if(field.startsWith("Guid")&&!model[field]){var validityRules=$scope.getValidityRules(field);if(validityRules&&validityRules.Mandatory)return!0}var canEdit=!$scope.isUpdate||$localStorage.generalOptions.CanEditOrDeleteCost;switch(field){case"GuidPurchaseOrderItem":case"Description":break;default:if(!canEdit)return!1}var isLockedAccounting=model.GuidPurchaseOrderItem&&!$localStorage.generalOptions.CanChangePoItemFromCost;switch(field){case"GuidPurchaseOrderItem":case"Description":case"Quantity":case"GrossAmount":return!0;case"GuidBuilding":return!(model.GuidPurchaseOrderItem||model.GuidWorkOrder||model.GuidEquipment||model.GuidArea||model.GuidProject);case"GuidSupplier":return!model.GuidPurchaseOrderItem&&!model.GuidPurchaseOrder;case"Amount":return!$localStorage.generalOptions.UseUnitPriceWithCost;case"UnitPrice":return!model.GuidConsumable;case"GuidEquipment":case"GuidArea":case"GuidProject":case"GuidWorkOrder":case"GuidPurchaseOrder":return!model.GuidPurchaseOrderItem;case"GuidCostCenter":return!(isLockedAccounting||$localStorage.generalOptions.GetPoItemAccountingFromWo&&(model.GuidWorkOrder||model.GuidPurchaseOrder));case"GuidDepartment":return!(isLockedAccounting||$localStorage.generalOptions.GetPoItemAccountingFromWo&&model.WorkOrder&&model.WorkOrder.GuidDepartment);case"GuidAccount":case"GuidAccounting0":case"GuidAccounting1":case"GuidAccounting2":case"GuidAccounting3":case"GuidAccounting4":return!isLockedAccounting;default:return!model.GuidPurchaseOrderItem}return!0},$scope.onSelectParent=function(parentPropertyName,parent){if(!parent)return void setParent(parentPropertyName,parent);if(!$scope.model[parentPropertyName]||$scope.model[parentPropertyName].Guid!==parent.Guid){$scope.model["Guid"+parentPropertyName]=parent.Guid,$scope.activateAutocomplete=!1;var url=repository.apiData.cost.endpoint["synchronizeWith"+parentPropertyName],updatePayload=getUpdatePayload();repository.runAction(url,updatePayload.payload,"columns="+JSON.stringify(columns),!0).then(function(response){reApplyParentProperties(response,updatePayload.parentProperties),onGet(response),$scope.activateAutocomplete=!0})}},$scope.onPurchaseOrderItem=function(purchaseOrderItem){$scope.onSelectParent("PurchaseOrderItem",purchaseOrderItem)},$scope.onWorkOrder=function(workOrder){$scope.onSelectParent("WorkOrder",workOrder)},$scope.onPurchaseOrder=function(purchaseOrder){$scope.onSelectParent("PurchaseOrder",purchaseOrder)},$scope.onConsumable=function(consumable){$scope.onSelectParent("Consumable",consumable)},$scope.isUpdate||$scope.$watch("model.InvoiceDate",function(newVal,oldVal){newVal!==oldVal&&$scope.onInvoiceDateChanged()}),$scope.onInvoiceDateChanged=function(){$scope.isUpdate||($scope.model.PostingDate=$scope.model.InvoiceDate)},$scope.openPurchaseOrderItem=function(){$scope.model.GuidPurchaseOrderItem&&$scope.hasEditAccess("PurchaseOrderItem")&&$modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"xl",resolve:{params:function(){return{Guid:$scope.model.GuidPurchaseOrderItem}}}}).result.then(function(result){},function(){})},$localStorage.generalOptions.UseUnitPriceWithCost&&$scope.$watchGroup(["model.Quantity","model.UnitPrice"],function(newVal,oldVal){$scope.model.Amount=$scope.model.Quantity*$scope.model.UnitPrice})}angular.module("Plania").controller("CostController",["$scope","Repository","$q","$stateParams","TranslationService","$modal","$localStorage","AccountingService","RegisteredFieldService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService){$scope.isUpdate="costCenter.edit"===$scope.navigation.current.name,$scope.isUpdate&&repository.getSingle(repository.apiData.costCenter.url,$stateParams.guid).then(function(response){$scope.model=response.Data,$scope.reload=!0},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-costCenter-success","Koststed har blitt oppdatert."):translationService.translate("create-costCenter-success","Koststed har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.costCenter.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.costCenter.url,$scope.model).then(success,error)},$scope.delete=function(){swal({ title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-costcenter-message","Koststedet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-costcenter-button-confirm","Ja, fjern Koststedet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.costCenter.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-costCenter-success","Koststedet ble fjernet!"),result,"success"),$scope.goBack("costCenter.list",{menuGuid:$scope.navigation.params.menuGuid})})})}}angular.module("Plania").controller("CostCenterController",["$scope","Repository","$stateParams","TranslationService",controller])}(),function(){function controller($scope,repository,translationService,ngTableParams,constants,listService,enumService,$filter,$modal,registeredFieldService){function setDefaultConfiguration(){$scope.newConfiguration=!1;var defaultConfig=constants.defaultAnonymizationConfiguration;$scope.anonymizationConfiguration.AnonymizationIntervalInMonths=defaultConfig.AnonymizationIntervalInMonths,$scope.anonymizationConfiguration.DeletionIntervalInMonths=defaultConfig.DeletionIntervalInMonths}function initFieldTable(){$scope.fieldTable=new ngTableParams({page:1,count:1e3},{total:0,getData:function($defer,params){repository.getSingleWithNoParameter(repository.apiData.anonymizationConfiguration.url+"/resolvedFieldRules").then(function(result){var data=params.sorting()?$filter("orderBy")(result,params.orderBy()):result;$scope.fieldTable.settings().total=data.length,$defer.resolve(data)},function(error){swal("Feil ved henting av anonymiseringsfelter",error,"error"),$defer.reject("Error getting anonymization fields")})}})}$scope.viewMode=!0,$scope.anonymizationConfiguration=null,$scope.isConfigured=!1,$scope.currentTab="anonymizationList";var showAnonymizationCommentModal=!0;$scope.model={},repository.getSingleWithNoParameter(repository.apiData.anonymizationConfiguration.url).then(function(result){$scope.anonymizationConfiguration=result,initFieldTable(),enumService.GetEnumValues("AnonymizationJobStatus").then(function(result){$scope.AnonymizationJobStatuses=result,$scope.selectedAnonymizationJobStatus=_.find($scope.AnonymizationJobStatuses,function(enumValue){return enumValue.StringValue.toString()===$scope.anonymizationConfiguration.AnonymizationJobStatus})}),$scope.isConfigured=$scope.anonymizationConfiguration.AnonymizationIntervalInMonths>0||$scope.anonymizationConfiguration.DeletionIntervalInMonths>0},function(error){"Ingen data funnet"===error?($scope.isConfigured=!1,setDefaultConfiguration(),initFieldTable()):repository.growl(error,"danger")}),registeredFieldService.getRegisteredField(repository.commonService.prefix.Customer).then(function(registeredFields){var anonymizationCommentRule=_.filter(registeredFields,{DomainFieldName:"AnonymizationComment"})[0];anonymizationCommentRule&&anonymizationCommentRule.Hidden&&(showAnonymizationCommentModal=!1)}),$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode},$scope.getLabelFromInterval=function(value){var interval=_.find(constants.defaultAnonymizationConfigurationIntervals,{months:value});return interval?interval.label:value+" måneder"},$scope.setAnonymizationStatus=function(status){$scope.anonymizationConfiguration.AnonymizationJobStatus=status.StringValue};var addColumnIfNotExists=function(columns,newColumn){if(!_.some(columns,function(col){return col.Property===newColumn.Property})){columns.unshift(newColumn);for(var i=0;i",Value:0}],me.listSetup&&(me.listSetup.Columns.forEach(function(col){columns.push(col.Property),col.Filter&&col.Filter.forEach(function(filter){params.filter().PropertyFilter.push(filter)})}),addAnonymizationColumns(me.listSetup),repository.GetPaginated(me.apiData.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")}))}}),this.selectAllRows=function(){this.allSelected?this.clearSelectedItems():this.table.data.forEach(function(row){me.isSelected(row)||me.selectItem(row)}),this.allSelected=!this.allSelected},this.clearSelectedItems=function(){_.remove(this.selectedItems,function(){return!0})},this.selectItem=function(item){_.some(this.selectedItems,function(i){return i.Guid===item.Guid})?_.remove(this.selectedItems,function(i){return i.Guid===item.Guid}):this.selectedItems.push(item)},this.isSelected=function(item){return _.find(this.selectedItems,function(i){return i.Guid===item.Guid})},this.optionsMenu=function(item){var optionsMenu=[];return optionsMenu.push({html:'Gå til leietaker',click:function(){$scope.navigation.go("housingCustomer.edit",{guid:item.Guid,menuGuid:$scope.navigation.params.menuGuid},event)}}),$scope.userInfo.isSystemAdministrator&&optionsMenu.push({html:'Legg til i unntakslisten',click:function(){var success=function(anonymizationComment){var params={AnonymizationComment:anonymizationComment,CustomerGuids:[]};me.selectedItems.length?me.selectedItems.forEach(function(item){params.CustomerGuids.push(item.Guid)}):params.CustomerGuids.push(item.Guid),repository.runAction(repository.apiData.customer.url+"/addHousingCustomerExceptions",params).then(function(result){repository.growl(translationService.translate("web-anonymization-dashboard-addHousingCustomerExceptions-success","Kundene har blitt lagt til unntakslisten"),"success"),me.clearSelectedItems(),me.table.reload(),$scope.exceptionList.table.reload()},function(error){repository.growl(error,"danger")})};showAnonymizationCommentModal?$modal.open({templateUrl:"app/customer/anonymization/dashboard/addToExceptionListModal.html",controller:"AnonymizationCommentModalController",size:"sm",resolve:{params:function(){return{}}}}).result.then(function(anonymizationComment){success(anonymizationComment)}):success()}}),item.ExpectedAnonymizationDate&&("Delete"===item.AnonymizationAction&&optionsMenu.push({html:'Kjør slettingsfunksjon',click:function(){var guids=[];me.selectedItems.length?me.selectedItems.forEach(function(item){guids.push(item.Guid)}):guids.push(item.Guid),repository.runAction(repository.apiData.customer.url+"/deleteUnusedHousingCustomers",guids).then(function(result){repository.growl(result,"success"),me.table.reload()},function(error){repository.growl(error,"danger")})}}),"Anonymize"===item.AnonymizationAction&&optionsMenu.push({html:'Kjør anonymiseringsfunksjon',click:function(){var guids=[];me.selectedItems.length?me.selectedItems.forEach(function(item){guids.push(item.Guid)}):guids.push(item.Guid),repository.runAction(repository.apiData.customer.url+"/anonymizeHousingCustomers",guids).then(function(result){repository.growl(result,"success"),me.table.reload()},function(error){repository.growl(error,"danger")})}})),optionsMenu};var today=moment(),monthFromToday=moment(today).add(1,"months");this.showStatusIcon=function(item,property){return!!item[property]&&moment(item[property]).isBefore(monthFromToday)},this.getStatusColor=function(item,property){return item[property]?moment(item[property]).isBefore(today)?"text-danger":moment(item[property]).isBefore(monthFromToday)?"text-warning":void 0:null}}},this.getWebListViews=function(selectedSetup,overwriteSelected){listService.getWebListViews(selectedSetup,me.apiData.prefix,!1,planiaUtils.contextIds.anonymizationHousingCustomer,{}).then(function(result){me.listOptions=result.listOptions,_.each(me.listOptions,function(listSetup){addAnonymizationColumns(listSetup)}),me.listSetup=result.selectedListSetup,me.initTable()})},me.getWebListViews()},$scope.exceptionList=new function(){var me=this;this.apiData=repository.apiData.customer,this.allSelected=!1,this.selectedItems=[],this.columns=[{Position:1,Title:translationService.translate("web-anonymization-dashboard-customer-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-anonymization-dashboard-customer-description","Navn"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-anonymization-dashboard-customer-anonymizationComment","Kommentar"),Property:"AnonymizationComment",PropertyType:"string"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:50,sorting:{Id:"desc"},filter:{PropertyFilter:[{Property:"AnonymizationAction",Operator:"=",Value:0}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=$scope.exceptionList.columns.map(function(col){return col.Property});repository.GetPaginated(me.apiData.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),this.selectAllRows=function(){this.allSelected?this.clearSelectedItems():this.table.data.forEach(function(row){me.isSelected(row)||me.selectItem(row)}),this.allSelected=!this.allSelected},this.clearSelectedItems=function(){_.remove(this.selectedItems,function(){return!0})},this.selectItem=function(item){_.some(this.selectedItems,function(i){return i.Guid===item.Guid})?_.remove(this.selectedItems,function(i){return i.Guid===item.Guid}):this.selectedItems.push(item)},this.isSelected=function(item){return _.find(this.selectedItems,function(i){return i.Guid===item.Guid})},this.onClick=function(item){item.AnonymizationComment&&showAnonymizationCommentModal&&$modal.open({templateUrl:"app/customer/anonymization/dashboard/addToExceptionListModal.html",controller:"AnonymizationCommentModalController",size:"sm",resolve:{params:function(){return{anonymizationComment:item.AnonymizationComment}}}}).result.then(function(anonymizationComment){var params={AnonymizationComment:anonymizationComment,CustomerGuids:[item.Guid]};repository.runAction(repository.apiData.customer.url+"/addHousingCustomerExceptions",params).then(function(result){repository.growl(translationService.translate("web-anonymization-dashboard-addHousingCustomerExceptions-updated","Kommentaren er oppdatert"),"success"),me.table.reload()},function(error){repository.growl(error,"danger")})})},this.optionsMenu=function(item){var optionsMenu=[];return optionsMenu.push({html:'Gå til leietaker',click:function(){$scope.navigation.go("housingCustomer.edit",{guid:item.Guid,menuGuid:$scope.navigation.params.menuGuid},event)}}),item.AnonymizationComment&&optionsMenu.push({html:'Se kommentar',click:function(){me.onClick(item)}}),$scope.userInfo.isSystemAdministrator&&optionsMenu.push({html:'Ta bort fra unntakslisten',click:function(){var guids=[];me.selectedItems.length?me.selectedItems.forEach(function(item){guids.push(item.Guid)}):guids.push(item.Guid),repository.runAction(repository.apiData.customer.url+"/removeHousingCustomerExceptions",guids).then(function(result){repository.growl(translationService.translate("web-anonymization-dashboard-removeHousingCustomerExceptions-success","Kundene har blitt tatt ut av unntakslisten"),"success"),me.clearSelectedItems(),me.table.reload(),$scope.anonymizationList.table.reload()},function(error){repository.growl(error,"danger")})}}),optionsMenu})},this.initTable()},$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.getLinkToJob=function(jobId){if(!$scope.mapOfJobGuidsById){$scope.mapOfJobGuidsById={};var columns=["Guid","Id"];repository.GetPaginated(repository.apiData.scheduledJob.url,0,50,{},null,null,JSON.stringify(columns)).then(function(result){result.List.forEach(function(row){$scope.mapOfJobGuidsById[row.Id]=row.Guid})})}var guid=$scope.mapOfJobGuidsById[jobId];return guid?$scope.navigation.href("scheduledJob.edit",{guid:guid}):null},$scope.save=function(){var configuration=$scope.anonymizationConfiguration;repository.updateSingle(repository.apiData.anonymizationConfiguration.url,configuration).then(function(result){repository.growl("Lagring fullført","success"),$scope.toggleViewMode()},function(error){repository.growl(error,"danger")})},$scope.defaultIntervals=constants.defaultAnonymizationConfigurationIntervals}angular.module("Plania").controller("AnonymizationDashboardController",["$scope","Repository","TranslationService","ngTableParams","Constants","ListService","EnumService","$filter","$modal","RegisteredFieldService",controller])}(),function(){function controller($scope,$modalInstance,params){$scope.anonymizationComment=params.anonymizationComment,$scope.cancelModal=function(){$modalInstance.dismiss("cancelled")},$scope.okModal=function(){$modalInstance.close($scope.anonymizationComment)}}angular.module("Plania").controller("AnonymizationCommentModalController",["$scope","$modalInstance","params",controller])}(),function(){function Address(){this.StreetAddress=null,this.PostalAddress=null,this.PostalCode=null,this.PostalArea=null,this.Country=null,this.GuidPostalData=null}function buildAddress(plainAddress){var address=new Address;return plainAddress.StreetAddress&&(address.StreetAddress=plainAddress.StreetAddress),plainAddress.PostalAddress&&(address.PostalAddress=plainAddress.PostalAddress),plainAddress.PostalCode&&(address.PostalCode=plainAddress.PostalCode),plainAddress.PostalArea&&(address.PostalArea=plainAddress.PostalArea),plainAddress.Country&&(address.Country=plainAddress.Country),address}function tryParseInt(str,defaultValue){try{var retValue=defaultValue;return null!==str&&str.length>0&&!isNaN(str)&&(retValue=parseInt(str),isNaN(retValue)&&(retValue=defaultValue)),retValue}catch(ex){return defaultValue}}function controller($scope,repository,$state,$q,$stateParams,$modal,ngTableParams,translationService,$localStorage,listService,$timeout,$http){function Customer(){this.Address=new Address,this.MailingAddress=new Address,this.InvoiceAddress=new Address,this.isEditable=!0}Customer.prototype.url=function(){return repository.apiData.customer.url},Customer.prototype.getClientParentProperties=function(guid){var parentProperties=[];for(var propertyName in this)if(propertyName.startsWith("Guid")){var parentPropertyName=_.capitalize(propertyName.substring(4)),parent=this[parentPropertyName];parent&&parentProperties.push(parentPropertyName)}return parentProperties},Customer.prototype.load=function(guid,columns){var defer=$q.defer(),self=this;return repository.getSingle(this.url(),guid,columns?JSON.stringify(columns):null).then(function(response){angular.merge(self,response.Data),defer.resolve(self)}).catch(function(error){repository.growl(error,"danger"),defer.reject()}),defer.promise},Customer.prototype.prefillFrontModel=function(frontModel){var self=this;frontModel&&(delete frontModel.Guid,delete frontModel.CustomerNr,angular.merge(self,frontModel))},Customer.prototype.hasValidFrontId=function(){var self=this;return self.ExternalId&&tryParseInt(self.ExternalId)&&tryParseInt(self.ExternalId)>0},Customer.prototype.save=function(guid){var defer=$q.defer(),self=this,parentProperties=this.getClientParentProperties(),payloadEntity=angular.copy(this);return parentProperties.forEach(function(field){delete payloadEntity[field]}),function(){($scope.isUpdate?repository.updateSingle:repository.createSingle)(self.url(),payloadEntity).then(function(response){angular.merge(self,response),parentProperties.forEach(function(field){self[field]&&self[field].Guid&&self["Guid"+field]&&self[field].Guid!==self["Guid"+field]&&delete self[field]}),defer.resolve(self)}).catch(function(error){defer.reject(error)})}(),defer.promise},Customer.prototype.resetParent=function(field){this["Guid"+field]&&(this["Guid"+field]=null),this[field]&&delete this[field]},Customer.prototype.getInvoiceCustomer=function(){if(!this.GuidInvoiceCustomer)return this.InvoiceCustomer=null;if(this.InvoiceCustomer&&this.InvoiceCustomer.Guid===this.GuidInvoiceCustomer)return this.InvoiceCustomer;this.InvoiceCustomer=new Customer,this.InvoiceCustomer.Guid=this.GuidInvoiceCustomer;var me=this;return this.InvoiceCustomer.load(this.GuidInvoiceCustomer).then(function(customer){$scope.invoiceCustomerCaption=customer.Caption},function(error){me.InvoiceCustomer.Guid=null,repository.growl(error,"danger")}),this.InvoiceCustomer},Customer.prototype.isFieldEnabled=function(field){if(!this.isEditable||$scope.viewMode)return!1;switch(field){case"PostalArea":case"Country":return!this.Address.GuidPostalData;case"MailingStreetAddress":case"MailingPostalAddress":case"MailingPostalCode":return!($scope.generalOptions.IsBBY&&this.ExternalId)||"Undefined"===this.FrontMailingAddressType;case"MailingPostalArea":case"MailingCountry":return!this.MailingAddress.GuidPostalData&&(!($scope.generalOptions.IsBBY&&this.ExternalId)||"Undefined"===this.FrontMailingAddressType);case"InvoiceStreetAddress":case"InvoicePostalAddress":case"InvoicePostalCode":return!this.GuidInvoiceCustomer;case"InvoicePostalArea":case"InvoiceCountry":return!this.InvoiceAddress.GuidPostalData&&!this.GuidInvoiceCustomer;case"CanBeInvoiceRecipient":return!this.GuidInvoiceCustomer&&!this.HasDependentCustomers;case"Id":case"Description":case"DateOfDeath":return!($scope.generalOptions.IsBBY&&this.ExternalId);case"Email":case"CellPhone":return!($scope.generalOptions.IsBBY&&this.ExternalId&&"Person"===this.CustomerType)}return!0},Customer.prototype.isFieldDisabled=function(field){return!this.isFieldEnabled(field)},Customer.prototype.isFieldVisible=function(field){switch(field){case"GuidInvoiceCustomer":return!this.CanBeInvoiceRecipient;case"CanBeInvoiceRecipient":return!this.GuidInvoiceCustomer;case"DateOfDeath":return"Person"===this.CustomerType&&(!($scope.viewMode&&!this.DateOfDeath)&&(!!this.DateOfDeath||!this.ExternalId));case"MaritalStatus":case"Language":case"Nationality":return"Organization"!==this.CustomerType}return!0},Customer.prototype.getMailingAddress=function(){return this.MailingAddress.isValid()?this.MailingAddress:this.Address},Customer.prototype.getInvoiceAddress=function(){return this.GuidInvoiceCustomer&&this.GuidInvoiceCustomer!==this.Guid?this.getInvoiceCustomer().getInvoiceAddress():this.InvoiceAddress.isValid()?this.InvoiceAddress:this.getMailingAddress()},$scope.model=new Customer,$scope.isUpdate=RegExp("edit$").test($scope.navigation.current.name),$scope.context=$state.includes("housingCustomer")?"HousingCustomer":"Customer",$scope.model.Guid=$stateParams.guid,$scope.generalOptions=$localStorage.generalOptions,$scope.viewMode=!!$scope.isUpdate,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode},$scope.canChangeCustomerType=!1,$scope.activateAutocomplete=!1,$scope.searchResults=[],$scope.search={text:"",focus:!1,hasSearched:!1},$scope.bbyFront={text:"",focus:!1,synchronizing:!1,hasError:!1,errorMessage:""},$scope.steps=[];var updateSteps=function(){var stepIndex=0,steps=[{stepIndex:++stepIndex,name:"chooseCustomerType",title:translationService.translate("web-customer-section-title-customerType","Kundetype")}];$scope.model.CustomerType&&($scope.generalOptions.IsBBY&&$scope.generalOptions.UseFrontApi?steps.push({stepIndex:++stepIndex,name:"bbyFrontSearch",title:translationService.translate("web-customer-section-title-bbyFrontSearch","Front")}):$scope.generalOptions.UseBronnoysundRegister&&"Person"!==$scope.model.CustomerType&&steps.push({stepIndex:++stepIndex,name:"searchBroenoysund",title:translationService.translate("web-customer-section-title-searchBroenoysund","Søk")}),steps.push({stepIndex:++stepIndex,name:"basicInfo",title:translationService.translate("web-customer-section-title-basicInformation","Basisinformasjon")})),$scope.steps=steps};updateSteps(),$scope.currentStep=$scope.steps[0],$scope.goToNextStep=function(){var stepIndex=_.findIndex($scope.steps,{name:$scope.currentStep.name});if(stepIndex>=0&&stepIndex<$scope.steps.length){var nextStep=$scope.steps[++stepIndex];nextStep&&("searchBroenoysund"===nextStep.name&&($scope.searchResults=[],$scope.search.text="",$scope.search.hasSearched=!1,$timeout(function(){$scope.search.focus=!0},500)),"bbyFrontSearch"===nextStep.name&&($scope.bbyFront.text="",$scope.bbyFront.hasValidationError=!1,$timeout(function(){$scope.bbyFront.focus=!0},500)),$scope.currentStep=nextStep)}},$scope.goToPreviousStep=function(){var stepIndex=_.findIndex($scope.steps,{name:$scope.currentStep.name});if(stepIndex>0){var prevStep=$scope.steps[--stepIndex];prevStep&&($scope.currentStep=prevStep)}},$scope.setCustomerType=function(customerType){$scope.model.CustomerType=customerType,updateSteps(),$scope.goToNextStep()},$scope.getPrefillFromFront=function(){$scope.bbyFront.synchronizing||($scope.bbyFront.synchronizing=!0,$http({method:"GET",url:encodeURI(repository.apiUrl.base+"boligbygg/bbycustomer?identificationNumber="+$scope.bbyFront.text+"&customerType="+$scope.model.CustomerType+repository.getUrlParameters("&"))}).then(function(apiResponse){$scope.bbyFront.synchronizing=!1,200===apiResponse.status?apiResponse.data&&$scope.model.prefillFrontModel(apiResponse.data):($scope.bbyFront.synchronizing=!1,$scope.bbyFront.hasError=!0,$scope.model.Id=$scope.bbyFront.text,apiResponse&&("string"==typeof apiResponse.data?$scope.bbyFront.errorMessage=apiResponse.data:apiResponse.data.Message&&($scope.bbyFront.errorMessage=apiResponse.data.Message))),$scope.goToNextStep()}))},$scope.orgNumberRegex=/^[0-9]{9}$/;var isOrganizationNumber=function(orgNumber){return $scope.orgNumberRegex.test(orgNumber)};$scope.searchCustomerRegister=function(){var searchString=$scope.search.text,searchName=!0;try{searchName=!isOrganizationNumber(searchString)}catch(ex){searchName=!0}var queryParameters="";queryParameters=searchName?"name="+searchString:"organizationNumber="+searchString,repository.getWithUrlParameter(repository.apiData.customer.endpoint.searchPublicRegister,queryParameters).then(function(result){result&&($scope.searchResults=result.List,$scope.searchResultTotalCount=result.TotalCount,$scope.search.hasSearched=!0)},function(error){repository.growl(error,"danger")})},$scope.selectCustomer=function(customer){$scope.model.Id=customer.organisasjonsnummer,$scope.model.Description=customer.navn,customer.forretningsadresse&&($scope.model.Address.StreetAddress=customer.forretningsadresse.adresse[0],$scope.model.Address.PostalCode=customer.forretningsadresse.postnummer,$scope.model.Address.PostalArea=customer.forretningsadresse.poststed,$scope.model.Address.Country=customer.forretningsadresse.land),customer.postadresse&&($scope.model.MailingAddress.StreetAddress=customer.postadresse.adresse[0],$scope.model.MailingAddress.PostalCode=customer.postadresse.postnummer,$scope.model.MailingAddress.PostalArea=customer.postadresse.poststed,$scope.model.MailingAddress.Country=customer.postadresse.land),$scope.goToNextStep()};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Customer,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Customer,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Customer),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Customer);$scope.model.isEditable=!$scope.restrictEdit};updateAccess(),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"customer":return filter.FilterModel={Condition:"and",Rules:[{Property:"CanBeInvoiceRecipient",Operator:"=",Value:!0}]},$scope.model.Guid&&filter.FilterModel.Rules.push({Property:"Guid",Operator:"<>",Value:$scope.model.Guid}),filter}return filter},$scope.load=function(guid){var columns=["CustomerCategory.Id","CustomerGroup.Id","LineOfBusiness.Id","Department.Id"];$scope.model.load(guid,columns).then(function(customer){$scope.setHtmlTitleByModel(customer),customer.CustomerLineOfBusiness&&($scope.lineOfBusiness=customer.LineOfBusiness.Id),customer.Department&&($scope.department=customer.Department.Id),customer.CustomerCategory&&($scope.category=customer.CustomerCategory.Id),customer.CustomerGroup&&($scope.group=customer.CustomerGroup.Id),$scope.canChangeCustomerType="Undefined"===customer.CustomerType,updateAccess(),$scope.reloadDocumentTable=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}),$scope.getCardTables()},$scope.init=function(){$scope.activateAutocomplete=!0;var webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value)switch(prefill.Property){case"CustomerLineOfBusiness":$scope.lineOfBusiness=prefill.Value.Label,$scope.model.GuidCustomerLineOfBusiness=prefill.Value.Guid;break;case"CustomerGroup":$scope.group=prefill.Value.Label,$scope.model.GuidCustomerGroup=prefill.Value.Guid;break;case"CustomerCategory":$scope.category=prefill.Value.Label,$scope.model.GuidCustomerCategory=prefill.Value.Guid;break;case"Department":$scope.department=prefill.Value.Label,$scope.model.GuidDepartment=prefill.Value.Guid}else $scope.model[prefill.Property]=prefill.Value})},$scope.$watch("model.InvoiceCustomer.Caption",function(newVal,oldVal){$scope.invoiceCustomerCaption=newVal}),$scope.update=function(destination){var success=function(customer){repository.growl($scope.isUpdate?"Kunden ble oppdatert":"Kunden ble lagret","success"),repository.commonService.setLastRegisterGuid(destination,customer.Guid),"customer.create"===destination?$scope.navigation.go(destination,{reload:!0}):(repository.persistedData.clearPersistedData(),$scope.goBack(destination,{guid:customer.Guid,menuGuid:$scope.navigation.params.menuGuid}))},error=function(error){repository.growl("string"==typeof error?error:error.Data.Message,"danger")};$scope.model.save().then(success).catch(error)},$scope.cancel=function(){$scope.goBack("customer.list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-customer-message","Kunden vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-customer-button-confirm","Ja, fjern kunden"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.customer.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-customer-success","Kunden ble fjernet!"),result,"success"),$scope.goBack("customer.list",{menuGuid:$scope.navigation.params.menuGuid})},function(error){swal({title:"Kunne ikke slette kunden!",text:error.Message+"

    Vil du deaktivere kunden?",type:"error",html:!0,showCancelButton:!0,confirmButtonText:"Deaktiver",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.IsDeactivated=!0,$scope.model.Id="#"+$scope.model.Id,$scope.updateSupplier("customer.list"))})})})},$scope.getInvoiceAddress=function(){return $scope.model.GuidInvoiceCustomer?$scope.model.getInvoiceAddress():$scope.model.InvoiceAddress},$scope.onPostCodeSelect=function(postalData){$scope.model.Address.synchroniseFromPostalData||($scope.model.Address=buildAddress($scope.model.Address)),$scope.model.Address.synchroniseFromPostalData(postalData,translationService)},$scope.onMailingPostCodeSelect=function(postalData){$scope.model.MailingAddress.synchroniseFromPostalData||($scope.model.MailingAddress=buildAddress($scope.model.MailingAddress)),$scope.model.MailingAddress.synchroniseFromPostalData(postalData,translationService)},$scope.onInvoicePostCodeSelect=function(postalData){$scope.model.GuidInvoiceCustomer||($scope.model.InvoiceAddress.synchroniseFromPostalData||($scope.model.InvoiceAddress=buildAddress($scope.model.InvoiceAddress)),$scope.model.InvoiceAddress.synchroniseFromPostalData(postalData,translationService))},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.doorKeyXCustomerColumns=[{Position:1,Title:translationService.translate("web-doorKey-id"),Property:"DoorKey.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-doorKey-description"),Property:"DoorKey.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-doorKeyXUser-quantity"),Property:"Quantity",PropertyType:"number"},{Position:4,Title:translationService.translate("web-doorKey-creationDate"),Property:"CreationDate",PropertyType:"date"}],$scope.onClickDoorKeyXCustomer=function(entity,event){event.preventDefault(),event.stopPropagation(),$scope.navigation.go("doorKey.edit",{guid:entity.GuidDoorKey})},$scope.contactPersonInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-contactperson-firstname"),Property:"FirstName",PropertyType:"string"},{Position:2,Title:translationService.translate("web-contactperson-lastname"),Property:"LastName",PropertyType:"string"},{Position:3,Title:translationService.translate("web-contactperson-telephone"),Property:"Telephone",PropertyType:"string"},{Position:4,Title:translationService.translate("web-contactperson-email"),Property:"Email",PropertyType:"string"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{LastName:"asc"},filter:{PropertyFilter:[{Property:"GuidCustomer",Operator:"=",Value:$stateParams.guid}]}},{total:0, counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.contactPerson.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}))},this.add=function(){me.canCreate()&&$modal.open({templateUrl:"app/contactPerson/contactPerson.html",controller:"ContactPersonController",resolve:{params:function(){return{guidCustomer:$scope.model.Guid}}}}).result.then(function(){me.table.reload()})},this.update=function(item){me.canEdit(item)&&$modal.open({templateUrl:"app/contactPerson/contactPerson.html",controller:"ContactPersonController",resolve:{params:function(){return{guid:item.Guid}}}}).result.then(function(){me.table.reload()},function(){})},this.remove=function(item){me.canDelete(customerLog)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-supplier-contactperson-message","Kontaktpersonen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-supplier-contactperson-button-confirm","Ja, fjern kontaktpersonen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.contactPerson.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-supplier-contactperson-success","Kontaktpersonen ble fjernet!"),result,"success"),me.table.reload()})})},this.canCreate=function(){return $scope.hasCreateAccess("ContactPerson")},this.canEdit=function(item){return item&&$scope.hasEditAccess("ContactPerson")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("ContactPerson")}},$scope.requestInfo=new function(){function navigateToRequest(selectedArea){var newRequest={model:{GuidCustomer:$scope.model.Guid,GuidArea:null!==selectedArea?selectedArea.Guid:null,GuidBuilding:null!==selectedArea?selectedArea.GuidBuilding:null},customer:$scope.model.Caption};repository.persistedData.setPersistedData("request.create",newRequest),$scope.navigation.go("request.create",{showPersistantData:!0},{reload:!0})}var me=this;this.columns="HousingCustomer"===$scope.context?[{Position:1,Title:translationService.translate("web-request-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-request-status"),Property:"Status",PropertyType:"enum.RequestStatus"},{Position:3,Title:translationService.translate("web-request-description"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-request-priority"),Property:"Priority.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-request-forwardPerson"),Property:"ForwardPerson",PropertyType:"string"},{Position:6,Title:translationService.translate("web-building-address"),Property:"Building.Address",PropertyType:"string"},{Position:7,Title:translationService.translate("web-request-creationDate"),Property:"CreationDate",PropertyType:"date"}]:[{Position:1,Title:translationService.translate("web-request-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-id"),Property:"Building.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-request-description"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-request-contactperson"),Property:"ContactPerson",PropertyType:"string"},{Position:5,Title:translationService.translate("web-request-status"),Property:"Status",PropertyType:"enum.RequestStatus"},{Position:6,Title:translationService.translate("web-request-creationDate"),Property:"CreationDate",PropertyType:"date"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{CreationDate:"desc"},filter:{PropertyFilter:[{Property:"GuidCustomer",Operator:"=",Value:$stateParams.guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.request.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}))},this.add=function(){var filterModel={Condition:"and",Rules:[{Property:"GuidCustomer",Operator:"=",Value:$scope.model.Guid},{Property:"GuidArea",Operator:"<>",Value:null},{Property:"Area.IsHousing",Operator:"=",Value:!0},{Property:"StartDate",Operator:"<>",Value:null},{Property:"StartDate",Operator:"<",Value:(new Date).toISOString()},{Condition:"or",Rules:[{Property:"EndDate",Operator:">",Value:(new Date).toISOString()},{Property:"EndDate",Operator:"=",Value:null}]}]},columns=["Area.Id","Area.GuidBuilding"];repository.GetPaginated(repository.apiData.contract.url,0,-1,{"Area.Id":"asc"},{FilterModel:filterModel},null,JSON.stringify(columns)).then(function(result){return result&&1===result.List.length?void navigateToRequest(result.List[0].Area):result&&0===result.List.length?void navigateToRequest(null):void $modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"md",resolve:{modalParams:function(){return{url:repository.apiData.contract.url,sorting:{},title:"Velg areal",filter:{FilterModel:filterModel},columns:[{title:"Areal id",property:"Area.Id"},{title:"Adresse",property:"Area.Address"},{title:"Kategori",property:"Area.AreaCategory.Description"},{title:"Status utleie",property:"Area.RentalStatus"},{property:"Area.GuidBuilding",hidden:!0}]}}}}).result.then(function(item){navigateToRequest(item.Area)})},function(error){repository.showError(error)})},this.canCreate=function(){return $scope.hasCreateAccess("Request")},this.canEdit=function(item){return item&&$scope.hasEditAccess("Request")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("Request")}},$scope.customerDeliveryAddressInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-customerDeliveryAddress-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-customerDeliveryAddress-address","Adresse"),Property:"StreetAddress",PropertyType:"string"},{Position:3,Title:translationService.translate("web-customerDeliveryAddress-po","Postboks"),Property:"PostalAddress",PropertyType:"string"},{Position:4,Title:translationService.translate("web-customerDeliveryAddress-PostNumber","Postnr"),Property:"PostalCode",PropertyType:"string"},{Position:5,Title:translationService.translate("web-customerDeliveryAddress-PostalArea","Poststed"),Property:"PostalArea",PropertyType:"string"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{Description:"desc"},filter:{PropertyFilter:[{Property:"GuidCustomer",Operator:"=",Value:$stateParams.guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.customerDeliveryAddress.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}))},this.add=function(){me.canCreate()&&$modal.open({templateUrl:"app/customer/views/deliveryAddress.html",controller:"CustomerDeliveryAddressController",resolve:{params:function(){return{guidCustomer:$scope.model.Guid,customerName:$scope.model.Description}}}}).result.then(function(){me.table.reload()})},this.update=function(item){me.canEdit(item)&&$modal.open({templateUrl:"app/customer/views/deliveryAddress.html",controller:"CustomerDeliveryAddressController",resolve:{params:function(){return{guid:item.Guid,customerName:$scope.model.Description}}}}).result.then(function(){me.table.reload()},function(){})},this.remove=function(item){me.canDelete(item)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-customer-deliveryAddress-message","Adressen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-customer-deliveryAddress-button-confirm","Ja, fjern adressen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.customerDeliveryAddress.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-customer-deliveryAddress-success","Adressen ble fjernet!"),result,"success"),me.table.reload()})})},this.canCreate=function(){return $scope.hasCreateAccess("CustomerDeliveryAddress")},this.canEdit=function(item){return item&&$scope.hasEditAccess("CustomerDeliveryAddress")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("CustomerDeliveryAddress")}},$scope.workOrderInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-workorder-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-workorder-type"),Property:"Type",PropertyType:"string"},{Position:3,Title:translationService.translate("web-workorder-description"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-workorder-resourcegroup-description","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-workorder-startdate"),Property:"StartDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-workorder-enddate"),Property:"EndDate",PropertyType:"date"}],this.filterTypes=[{value:"-1",name:translationService.translate("web-workorder-filterType-all","Alle")},{value:"0",name:translationService.translate("web-workorder-filterType-project","Prosjekt")},{value:"1",name:translationService.translate("web-workorder-filterType-open","Aktive")},{value:"2",name:translationService.translate("web-workorder-filterType-closed","Historiske")}],this.selectedFilterType=me.filterTypes[2],this.setFilterType=function(filter){me.selectedFilterType=filter,me.table.reload()},this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{ActivityStatus:"Undefined",PropertyFilter:[{Property:"GuidCustomer",Operator:"=",Value:$stateParams.guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)});var filter=angular.copy(params.filter());me.selectedFilterType&&me.selectedFilterType.value>=0&&filter.PropertyFilter.push({Property:"Stage",Operator:"=",Value:me.selectedFilterType.value}),repository.GetPaginated(repository.apiData.workOrder.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}))},this.canCreate=function(){return $scope.hasCreateAccess("WorkOrder")},this.canEdit=function(item){return item&&$scope.hasEditAccess("WorkOrder")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("WorkOrder")}},$scope.contractInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-contract-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-contract-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-area-Id","Bolig Id"),Property:"Area.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-area-Description","Bolig beskrivelse"),Property:"Area.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-contract-startDate","Startdato"),Property:"StartDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-contract-ScheduledEndDate","Dato flyttet ut"),Property:"ScheduledEndDate",PropertyType:"date"},{Position:7,Title:translationService.translate("web-contract-endDate","Sluttdato"),Property:"EndDate",PropertyType:"date"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{StartDate:"desc"},filter:{PropertyFilter:[{Property:"GuidCustomer",Operator:"=",Value:$stateParams.guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.contract.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}))},this.allocateHousing=function(){$modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"md",resolve:{modalParams:function(){return{title:"Velg bolig",url:repository.apiData.area.url,sorting:{},filter:{IsForHousingAllocation:!0},columns:[{title:"Id",property:"Id"},{title:"Beskrivelse",property:"Description"}]}}}}).result.then(function(item){var success=function(result){repository.growl($scope.isUpdate?"Avtalen ble oppdatert":"Avtalen ble lagret","success"),me.table.reload()},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};if(void 0!==item.Guid){var contract={GuidCustomer:$scope.model.Guid,GuidArea:item.Guid};repository.createSingle(repository.apiData.contract.url+"/allocateHousing",contract).then(success).catch(error)}})},this.canCreate=function(){return $scope.hasCreateAccess("Contract")},this.canEdit=function(item){return item&&$scope.hasEditAccess("Contract")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("Contract")}},$scope.customerLogInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-customerLog-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-customerLog-ResponsiblePerson","Ansvarlig"),Property:"ResponsiblePerson",PropertyType:"string"},{Position:3,Title:translationService.translate("web-customerLog-Date","Dato"),Property:"LogDate",PropertyType:"date"},{Position:4,Title:translationService.translate("web-customerLog-userCreatedBy-realName","Opprettet av"),Property:"UserCreatedBy.RealName",PropertyType:"string"},{Position:5,Title:translationService.translate("web-customerLog-creationDate","Opprettet"),Property:"CreationDate",PropertyType:"date"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{LogDate:"desc"},filter:{PropertyFilter:[{Property:"GuidCustomer",Operator:"=",Value:$stateParams.guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.customerLog.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}))},this.add=function(){me.canCreate()&&$modal.open({templateUrl:"app/customer/views/log.html",controller:"CustomerLogController",resolve:{params:function(){return{guidCustomer:$scope.model.Guid}}}}).result.then(function(){me.table.reload()})},this.update=function(customerLog){me.canEdit(customerLog)&&$modal.open({templateUrl:"app/customer/views/log.html",controller:"CustomerLogController",resolve:{params:function(){return{guid:customerLog.Guid}}}}).result.then(function(){$scope.customerLogInfo.table.reload()})},this.remove=function(customerLog){me.canDelete(customerLog)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-customer-customerLog-message","Loggen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-customer-customerLog-button-confirm","Ja, fjern loggen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.customerLog.url,customerLog.Guid).then(function(result){swal(translationService.translate("web-swal-customer-customerLog-success","Loggen ble fjernet!"),result,"success"),me.table.reload()})})},this.contextMenuOptions=function(item){var options=[];return me.canEdit(item)&&options.push({html:' '+translationService.translate("web-customer-customerLog-update","Oppdater")+"",click:function($itemScope,$event,modelValue,text,$li){me.update(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-customer-customerLog-delete","Slett")+"",click:function($itemScope,$event,modelValue,text,$li){me.remove(item)}}),options},this.canCreate=function(){return $scope.hasCreateAccess("CustomerLog")},this.canEdit=function(item){return item&&$scope.hasEditAccess("CustomerLog")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("CustomerLog")}},$scope.getCardTables=function(){"HousingCustomer"===$scope.context?$scope.workOrderInfo.initTable():$scope.customerDeliveryAddressInfo.initTable(),$scope.contactPersonInfo.initTable(),$scope.requestInfo.initTable(),$scope.contractInfo.initTable(),$scope.customerLogInfo.initTable()},$scope.isUpdate?$scope.load($stateParams.guid):$scope.init()}angular.module("Plania").controller("CustomerController",["$scope","Repository","$state","$q","$stateParams","$modal","ngTableParams","TranslationService","$localStorage","ListService","$timeout","$http",controller]),Address.prototype.isValid=function(){return(this.StreetAddress||this.PostalAddress)&&this.PostalCode&&this.PostalArea},Address.prototype.synchroniseFromPostalData=function(postalData,translationService){this.GuidPostalData=postalData?postalData.Guid:null,this.PostalCode=postalData?postalData.ZipCode:null,this.PostalArea=postalData?postalData.PostalArea:null,this.Country=postalData?translationService.getEnumTranslation("countrycode",postalData.CountryCode):null}}(),function(){function controller($scope,$modalInstance,params,repository,translationService){$scope.isUpdate=params.guid,$scope.header=$scope.isUpdate?translationService.translate("customerLog-title-edit","Rediger log"):translationService.translate("customerLog-title-create","Legg til log"),$scope.model={},$scope.model.GuidCustomer=params.guidCustomer,$scope.isUpdate?repository.getSingle(repository.apiData.customerLog.url,params.guid).then(function(response){var result=response.Data;$scope.model=result,setTimeout(function(){$scope.activateAutocomplete=!0},250)}):$scope.model.LogDate=(new Date).toISOString(),$scope.saveLog=function(){$scope.model.LogDate&&($scope.model.LogDate=new Date($scope.model.LogDate).toISOString()),$scope.isUpdate?repository.updateSingle(repository.apiData.customerLog.url,$scope.model).then(function(result){repository.growl("Log har blitt oppdatert","success"),$modalInstance.close()}):repository.createSingle(repository.apiData.customerLog.url,$scope.model).then(function(result){repository.growl("Log har blitt lagret","success"),$modalInstance.close()}).catch(function(error){repository.growl(error,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CustomerLogController",["$scope","$modalInstance","params","Repository","TranslationService",controller])}(),function(){function customerService(repository,$q,$modal,translationService,$rootScope){var service={};return service.getActiveHousing=function(guidCustomer,skipModal){var deferred=$q.defer();if(!guidCustomer||!$rootScope.hasReadAccess("Area"))return $.Deferred().resolve(null).promise();var filter={GuidCustomer:guidCustomer,AreaContext:"ActiveHousing"},areaColumns=[];return repository.GetPaginated(repository.apiData.area.url,0,1,null,filter,"",JSON.stringify(areaColumns)).then(function(result){if(1===result.TotalCount)return void deferred.resolve(result.List[0]);!skipModal&&result.TotalCount>1?$modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"lg",resolve:{modalParams:function(){return{url:repository.apiData.area.url,sorting:{Id:"asc"},title:translationService.translate("web-customer-getActiveHousing-title","Velg bolig"),filter:filter,columns:[{title:translationService.translate("web-area-id"),property:"Id"},{title:translationService.translate("web-area-description"),property:"Description"},{title:translationService.translate("web-area-address"),property:"Address"},{title:translationService.translate("web-areaCategory-description"),property:"AreaCategory.Description"},{title:translationService.translate("web-area-rentalStatus"),property:"RentalStatus"},{property:"Building.Id",hidden:!0},{property:"Building.Description",hidden:!0},{property:"Building.GuidEstate",hidden:!0},{property:"Building.Estate.Id",hidden:!0},{property:"Building.Estate.Description",hidden:!0}]}}}}).result.then(function(item){deferred.resolve(item)},function(){deferred.resolve(null)}):deferred.resolve(null)},function(error){deferred.reject(error)}),deferred.promise},service}angular.module("Plania").factory("CustomerService",["Repository","$q","$modal","TranslationService","$rootScope",customerService])}(),function(){function controller($scope,$modalInstance,params,repository,translationService){$scope.isUpdate=params.guid,$scope.header=$scope.isUpdate?translationService.translate("deliveryAddress-title-edit","Rediger adresse"):translationService.translate("deliveryAddress-title-create","Legg til leveringsadresse"),$scope.model={},$scope.model.GuidCustomer=params.guidCustomer,$scope.customerName=params.customerName,$scope.isUpdate&&repository.getSingle(repository.apiData.customerDeliveryAddress.url,params.guid).then(function(response){var result=response.Data;$scope.model=result,setTimeout(function(){$scope.activateAutocomplete=!0},250)}),$scope.saveDeliveryAdress=function(){$scope.isUpdate?repository.updateSingle(repository.apiData.customerDeliveryAddress.url,$scope.model).then(function(result){repository.growl("Leveringsadresse har blitt oppdatert","success"),$modalInstance.close()}):repository.createSingle(repository.apiData.customerDeliveryAddress.url,$scope.model).then(function(result){repository.growl("Leveringsadresse har blitt lagret","success"),$modalInstance.close()}).catch(function(error){repository.growl(error,"danger")})},$scope.onPostCodeSelect=function(postalInfo){postalInfo?($scope.model.GuidPost=postalInfo.Guid,$scope.model.PostalCode=postalInfo.ZipCode,$scope.model.PostalArea=postalInfo.PostalArea,$scope.model.Country=postalInfo.GuidLand,$scope.postalInfo=postalInfo):($scope.model.GuidPost=null,$scope.model.PostalCode="",$scope.model.PostalArea="",$scope.model.GuidLand="")},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CustomerDeliveryAddressController",["$scope","$modalInstance","params","Repository","TranslationService",controller])}(),function(){function controller($scope,repository,modalInstance,$modal,translationService,iconService,listService,widget,dwgThemeService,$timeout){function setTinymceOptions(){var toolbar="undo redo | styleselect fontselect fontsizeselect | bold italic forecolor backcolor | alignleft aligncenter alignright lineheightselect | bullist numlist outdent indent | addProperty addUserProperty addBuildingImage";$scope.model.WidgetData.prefix||(toolbar="undo redo | styleselect fontselect fontsizeselect | bold italic forecolor backcolor | alignleft aligncenter alignright lineheightselect | bullist numlist outdent indent | addUserProperty");var setup=function(editor){$scope.model.WidgetData.prefix&&(editor.addButton("addProperty",{icon:"plus",tooltip:translationService.translate("web-htmlWidget-tinyMceButton-addDomainProperties","Sett inn et databasefelt"),onclick:function(){if(!$scope.model.WidgetData.prefix)return void swal("Ingen entitet valgt","Velg en entitet for å kunne legge til en kolonne i malen","warning");$modal.open({templateUrl:"app/common/views/addNewListColumnModal.html",controller:"AddNewListColumnController",resolve:{params:function(){return{prefix:$scope.model.WidgetData.prefix,existingColumns:[]}}}}).result.then(function(selectedColumns){selectedColumns.forEach(function(column){editor.insertContent(column.Title+": {{"+column.Property+"}} ")})})}}),editor.addButton("addBuildingImage",{icon:"image",tooltip:translationService.translate("web-htmlWidget-tinyMceButton-addBuildingImage","Sett inn fasadebilde"),onclick:function(){editor.insertContent('')}})),editor.addButton("addUserProperty",{icon:"user",tooltip:translationService.translate("web-htmlWidget-tinyMceButton-addLoggedInUserProperties","Sett inn felt fra innlogget bruker"),onclick:function(){$modal.open({templateUrl:"app/common/modal/views/selectUserInfoPropertyModal.html",controller:"SelectUserInfoPropertyModal"}).result.then(function(selectedProperties){selectedProperties.forEach(function(property){editor.insertContent("{{"+property+"}} ")})})}})};$scope.tinymceOptions={language:"nb_NO",branding:!1,plugins:["advlist autolink lists link image hr","searchreplace lineheight","save table contextmenu directionality","paste textcolor colorpicker imagetools autoresize"],menubar:"edit insert format table",toolbar:toolbar,image_advtab:!0,relative_urls:!1,convert_urls:!1,remove_script_host:!1,paste_data_images:!0,autoresize_min_height:400,autoresize_max_height:600,forced_root_block:!1,lineheight_formats:"14pt 16pt 18pt 20pt 22pt 24pt 26pt 36pt",inline_styles:!0,ui_container:".modal",font_formats:"Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Calibri=calibri;Comic Sans MS=comic sans ms,sans-serif;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;",setup:setup},$scope.$broadcast("$tinymce:refresh")}$scope.model={},$scope.isEdit=!1,$scope.apiData=_.sortBy(_.filter(repository.apiData,function(data){return!0===data.availableForListView}),function(o){return o.description}),$scope.keywords=repository.filterKeyWords,$scope.timeKeywords=repository.timeKeywords,$scope.sortingColumns=[],$scope.boolSelect=[{name:"Ja",value:!0},{name:"Nei",value:!1}],$scope.iconMap=iconService.GetIconMap(),$scope.getIcon=iconService.getIcon,$scope.minimumRefreshInterval=60;var defaultRefreshInterval=600;$scope.widgetTypes=[{title:translationService.translate("web-widget-widgetType-table","Tabell"),directiveName:"pl-table-widget"},{title:translationService.translate("web-widget-widgetType-list","Innmeldinger"),directiveName:"pl-list-widget"},{title:translationService.translate("web-widget-widgetType-link","Linker"),directiveName:"pl-link-widget"},{title:translationService.translate("web-widget-widgetType-report","Rapport"),directiveName:"pl-report-widget"},{title:translationService.translate("web-widget-widgetType-calendar","Kalender"),directiveName:"pl-calendar-widget"},{title:translationService.translate("web-widget-widgetType-drawing","Tegning"),directiveName:"pl-drawing-widget"},{title:translationService.translate("web-widget-widgetType-kpi","Nøkkeltall"),directiveName:"pl-kpi-widget"},{title:translationService.translate("web-widget-widgetType-kpiGroupTable","Kpi tabell"),directiveName:"pl-kpi-group-table-widget"},{title:translationService.translate("web-widget-widgetType-htmlText","Html tekst"),directiveName:"pl-html-text-widget"},{title:translationService.translate("web-widget-widgetType-weatherForecast","Værmelding"),directiveName:"pl-weather-forecast-widget"}],$scope.valueColumnFunctions=[{title:translationService.translate("web-widget-function-sum","Sum"),function:"sum"},{title:translationService.translate("web-widget-function-count","Antall"),function:"count"},{title:translationService.translate("web-widget-function-average","Gjennomsnitt"),function:"average"},{title:translationService.translate("web-widget-function-max","Maks"),function:"max"},{title:translationService.translate("web-widget-function-min","Min"),function:"min"}],$scope.widgetTypes=_.sortBy($scope.widgetTypes,function(o){return o.title}),$scope.valueColumnFunctions=_.sortBy($scope.valueColumnFunctions,function(o){return o.title}),$scope.getPaginationCounts=function(){return $scope.model&&$scope.model.WidgetType?"pl-kpi-group-table-widget"===$scope.model.WidgetType?["10","25","50","100",translationService.translate("web-table-pagination-all","Alle")]:["10","25","50","100"]:[]},$scope.datePickers={},$scope.open=function($event,calendar){$event.preventDefault(),$event.stopPropagation(),$scope.datePickers[calendar]=!$scope.datePickers[calendar]},$scope.calendarViewTypes=[{id:"month",description:translationService.translate("web-addwidget-calendartype-month","Måned")},{id:"basicWeek",description:translationService.translate("web-addwidget-calendartype-week","Uke")},{id:"basicDay",description:translationService.translate("web-addwidget-calendartype-day","Dag")}];var changeModalSize=function(size){$timeout(function(){size?$("#addWidgetModalHeader").closest(".modal-dialog").removeClass("modal-lg modal-sm modal-md modal-xl").addClass("modal-"+size):$("#addWidgetModalHeader").closest(".modal-dialog").removeClass("modal-lg modal-sm modal-md modal-xl")},100)},getContextIdFromApiData=function(selectedApiData){if(selectedApiData)return selectedApiData.contextId?selectedApiData.contextId:getContextIdFromFromPrefix(selectedApiData.prefix)},getContextIdFromFromPrefix=function(prefix){if(prefix)return"List-"+prefix},getContextIdFromFromServiceUrl=function(serviceUrl){if(serviceUrl){var dataTypes=_.filter($scope.apiData,function(data){return data.url===serviceUrl});if(dataTypes.length){if(1===dataTypes.length)return getContextIdFromApiData(dataTypes[0]);var firstPrefix=_.find($scope.apiData,function(data){return!!data.prefix});if(firstPrefix)return getContextIdFromFromPrefix(firstPrefix)}}},getWebListViews=function(){var filters={};"Tiltak"===$scope.model.selectedDataType.description?filters.isCorrectiveAction=!0:"Avvik"===$scope.model.selectedDataType.description&&(filters.isCorrectiveAction=!1);var contextId=$scope.model.selectedDataType.contextId||"List-"+$scope.model.selectedDataType.prefix ;listService.getWebListViews($scope.model.WidgetData.SelectedListSetup,$scope.model.selectedDataType.prefix,!0,contextId,filters).then(function(result){$scope.listOptions=result.listOptions,$scope.model.WidgetData.SelectedListSetup=result.selectedListSetup,$scope.model.WidgetData.SelectedListSetup.VisibleColumns=_.filter($scope.model.WidgetData.SelectedListSetup.Columns,function(c){return!c.Filter||!c.Filter.some(function(f){return f.Hidden})})})};$scope.onSelectWidgetType=function(prev){var setDefaultConfiguration=function(){switch($scope.model.WidgetType){case"pl-table-widget":$scope.model.WidgetData.RefreshInterval=defaultRefreshInterval,$scope.model.WidgetData.defaultPaginationCount=10;break;case"pl-list-widget":$scope.model.WidgetData.RefreshInterval=defaultRefreshInterval;break;case"pl-kpi-widget":$scope.model.WidgetData.color="gray",$scope.model.WidgetData.columns=[],$scope.model.WidgetData.thresholds=[];break;case"pl-link-widget":$scope.model.WidgetData.Links||($scope.model.WidgetData.Links=[]);break;case"pl-drawing-widget":$scope.model.WidgetData.Drawings||($scope.model.WidgetData.Drawings=[]),$scope.dwgThemes=dwgThemeService.getAvailableThemes(),$scope.model.WidgetData.RefreshInterval=defaultRefreshInterval,$scope.drawingDataSourceSelection="selection",$scope.model.WidgetData.DrawingSource="selection";break;case"pl-report-widget":var filter={PropertyFilter:[{Property:"ReportType",Operator:"=",Value:"3"}]};repository.GetPaginated(repository.apiData.report.url,0,100,null,filter).then(function(result){$scope.availableReports=result.List});break;case"pl-calendar-widget":$scope.model.WidgetData.ViewType="basicWeek",$scope.model.WidgetData.ExcludeResourceGroup=!1,$scope.model.WidgetData.ExcludeCompletedWorkOrders=!1,$scope.model.WidgetData.ExcludePeriodicTasks=!1;break;case"pl-kpi-group-table-widget":$scope.model.WidgetData.columns=[],$scope.model.WidgetData.defaultPaginationCount=10,$scope.model.WidgetData.RefreshInterval=defaultRefreshInterval,$scope.model.WidgetData.kpiGroupTable={valueColumns:[],sortingColumn:{},sortingProperty:null};break;case"pl-html-text-widget":$scope.model.WidgetData.ServiceUrl=repository.apiData.building.url,$scope.model.WidgetData.prefix=repository.apiData.building.prefix,$scope.model.WidgetData.fromActiveBuilding=!0,$scope.model.WidgetData.htmlTextBody="",$scope.model.WidgetData.showWidgetHeader=!1,setTinymceOptions();break;case"pl-chart-widget":$scope.model.WidgetData.color="gray",$scope.model.WidgetData.columns=[],$scope.model.WidgetData.thresholds=[],$scope.model.WidgetData.chartType="column",$scope.model.WidgetData.kpiGroupTable={valueColumns:[],sortingColumn:{},sortingProperty:null};break;case"pl-weather-forecast-widget":$scope.model.WidgetData.type="meteogram",$scope.model.WidgetData.locale="nb"}"pl-html-text-widget"===$scope.model.WidgetType?changeModalSize("lg"):changeModalSize()};$scope.model.WidgetData||($scope.model.WidgetData={}),prev&&$scope.model.WidgetType!==prev?swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-addWidgetModal-onSelectWidgetType-message","Endring av widgettype vil nullstille alle konfigurasjonene du har lagt til for denne widgeten."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-addWidgetModal-onSelectWidgetType-button-confirm","Ja, endre widgettype"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt")},function(confirm){window.onkeydown=null,window.onfocus=null,confirm?($scope.model.WidgetData={},$scope.model.selectedDataType=void 0,setDefaultConfiguration()):($scope.model.WidgetType=prev,$scope.$apply())}):setDefaultConfiguration()},$scope.onSelectDataType=function(){$scope.model.WidgetData||($scope.model.WidgetData={});var updateConfiguration=function(reset){$scope.model.WidgetData.contextId=getContextIdFromApiData($scope.model.selectedDataType),"pl-table-widget"===$scope.model.WidgetType&&($scope.model.WidgetData.ServiceUrl=$scope.model.selectedDataType.url,$scope.model.WidgetData.NavigationState=$scope.model.selectedDataType.navigationState,getWebListViews()),"pl-kpi-widget"===$scope.model.WidgetType&&($scope.model.WidgetData.prefix=$scope.model.selectedDataType.prefix,$scope.model.WidgetData.kpiProperty&&!reset||($scope.model.WidgetData.kpiProperty={}),$scope.model.WidgetData.columns&&!reset||($scope.model.WidgetData.columns=[]),$scope.model.WidgetData.thresholds&&!reset||($scope.model.WidgetData.thresholds=[]),getWebListViews()),"pl-kpi-group-table-widget"===$scope.model.WidgetType&&($scope.model.WidgetData.prefix=$scope.model.selectedDataType.prefix,$scope.model.WidgetData.columns&&!reset||($scope.model.WidgetData.columns=[]),reset&&($scope.model.WidgetData.kpiGroupTable={valueColumns:[],sortingColumn:{},sortingProperty:null})),"pl-chart-widget"===$scope.model.WidgetType&&($scope.model.selectedDataType&&($scope.model.WidgetData.prefix=$scope.model.selectedDataType.prefix,$scope.model.WidgetData.columns&&!reset||($scope.model.WidgetData.columns=[])),reset&&($scope.model.WidgetData.chartType="column",$scope.model.WidgetData.kpiGroupTable={valueColumns:[],sortingColumn:{},sortingProperty:null})),reset&&$scope.$apply()},showMessage=!1,prefixChanged=$scope.model.WidgetData.prefix&&$scope.model.selectedDataType.prefix&&$scope.model.WidgetData.prefix!==$scope.model.selectedDataType.prefix;"pl-kpi-widget"!==$scope.model.WidgetType&&"pl-kpi-group-table-widget"!==$scope.model.WidgetType&&"pl-chart-widget"!==$scope.model.WidgetType||!prefixChanged||(showMessage=!0),showMessage?swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-addWidgetModal-onChangeDataType-message","Endring av datatype vil slette noen konfigurasjoner for å unngå inkonsistent oppsett"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-addWidgetModal-onChangeDataType-button-confirm","Ja, endre datatype"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt")},function(confirm){window.onkeydown=null,window.onfocus=null,confirm?updateConfiguration(!0):($scope.model.selectedDataType=$scope.apiData.find(function(data){return data.prefix===$scope.model.WidgetData.prefix}),$scope.$apply())}):updateConfiguration()},$scope.onSelectDrawingDataSourceSelection=function(drawingDataSource){$scope.model.WidgetData.DrawingSource="user"===drawingDataSource?"":"selection"},$scope.updateSortingColumns=function(skipDefault){var columns=[];if($scope.model.WidgetData.kpiGroupTable.groupColumn&&columns.push({Title:$scope.model.WidgetData.kpiGroupTable.groupColumn.Title,Property:$scope.model.WidgetData.kpiGroupTable.groupColumn.Property,Direction:$scope.model.WidgetData.kpiGroupTable.groupColumn.Direction?$scope.model.WidgetData.kpiGroupTable.groupColumn.Direction:"asc",PropertyType:$scope.model.WidgetData.kpiGroupTable.groupColumn.PropertyType}),$scope.model.WidgetData.kpiGroupTable.valueColumns&&$scope.model.WidgetData.kpiGroupTable.valueColumns.length&&$scope.model.WidgetData.kpiGroupTable.valueColumns.forEach(function(col){var colCopy=angular.copy(col),functionTitle="";"sum"===colCopy.Function?functionTitle=translationService.translate("web-widget-function-sum-headerTitle","Sum"):"count"===colCopy.Function?functionTitle=translationService.translate("web-widget-function-count-headerTitle","Antall"):"average"===colCopy.Function?functionTitle=translationService.translate("web-widget-function-average-headerTitle","Snitt"):"max"===colCopy.Function?functionTitle=translationService.translate("web-widget-function-max-headerTitle","Maks"):"min"===colCopy.Function&&(functionTitle=translationService.translate("web-widget-function-min-headerTitle","Min")),colCopy.Title=functionTitle+" "+colCopy.Title,columns.push({Title:colCopy.Title,Property:colCopy.Property,Direction:colCopy.Direction?colCopy.Direction:"asc",Function:colCopy.Function,PropertyType:colCopy.PropertyType})}),!skipDefault){var firstColumn=columns[0];$scope.model.WidgetData.kpiGroupTable.sortingColumn?firstColumn&&firstColumn.Property!==$scope.model.WidgetData.kpiGroupTable.sortingColumn.Property&&($scope.model.WidgetData.kpiGroupTable.sortingColumn=firstColumn):$scope.model.WidgetData.kpiGroupTable.sortingColumn=firstColumn}$scope.sortingColumns=columns};var initSelectedDataTypeFromWidgetData=function(){var selectedDataType=null;("pl-table-widget"!==$scope.model.WidgetType||$scope.model.WidgetData.NavigationState)&&(selectedDataType=_.find($scope.apiData,function(data){var apiDataContextId=data.contextId;return!(!!apiDataContextId&&!!$scope.model.WidgetData.contextId&&apiDataContextId!==$scope.model.WidgetData.contextId||(["pl-table-widget"].includes($scope.model.WidgetType)?data.url!==$scope.model.WidgetData.ServiceUrl:!["pl-kpi-widget","pl-kpi-group-table-widget","pl-chart-widget"].includes($scope.model.WidgetType)||data.prefix!==$scope.model.WidgetData.prefix))}),$scope.model.selectedDataType=selectedDataType,selectedDataType&&$scope.onSelectDataType())};if(widget){switch($scope.model=widget,$scope.model.WidgetType){case"pl-table-widget":$scope.model.WidgetData.defaultPaginationCount||($scope.model.WidgetData.defaultPaginationCount=10),$scope.model.WidgetData.contextId||($scope.model.WidgetData.contextId=getContextIdFromFromServiceUrl($scope.model.WidgetData.ServiceUrl)),initSelectedDataTypeFromWidgetData();break;case"pl-link-widget":$scope.model.WidgetData.Links||($scope.model.WidgetData.Links=[]);break;case"pl-report-widget":$scope.onSelectWidgetType();break;case"pl-drawing-widget":$scope.dwgThemes=dwgThemeService.getAvailableThemes(),!$scope.model.WidgetData.DrawingSource&&$scope.model.WidgetData.Drawings&&($scope.model.WidgetData.DrawingSource=$scope.model.WidgetData.Drawings.length?"selection":void 0),$scope.model.WidgetData.DrawingSource&&"selection"!==$scope.model.WidgetData.DrawingSource?$scope.drawingDataSourceSelection="user":$scope.drawingDataSourceSelection="selection";break;case"pl-kpi-widget":$scope.model.WidgetData.contextId||($scope.model.WidgetData.contextId=getContextIdFromFromPrefix($scope.model.WidgetData.prefix)),initSelectedDataTypeFromWidgetData();break;case"pl-kpi-group-table-widget":$scope.model.WidgetData.contextId||($scope.model.WidgetData.contextId=getContextIdFromFromPrefix($scope.model.WidgetData.prefix)),initSelectedDataTypeFromWidgetData(),$scope.updateSortingColumns(!0);break;case"pl-html-text-widget":setTinymceOptions();break;case"pl-chart-widget":$scope.model.WidgetData.contextId||($scope.model.WidgetData.contextId=getContextIdFromFromPrefix($scope.model.WidgetData.prefix)),initSelectedDataTypeFromWidgetData()}"pl-html-text-widget"===$scope.model.WidgetType?changeModalSize("lg"):changeModalSize(),$scope.isEdit=!0}$scope.editLink=function(link){$modal.open({controller:"AddNewLinkModalController",templateUrl:"app/dashboard/directives/widgets/addNewLinkModal.html",resolve:{link:function(){return link}}}).result.then(function(editedLink){if(link)link=editedLink;else{if($scope.model.WidgetData.Links.length>0){var sortedLinks=_.sortBy($scope.model.WidgetData.Links,function(o){return o.Id}),newId=sortedLinks[sortedLinks.length-1].Id+1;editedLink.Id=newId}else editedLink.Id=1;$scope.model.WidgetData.Links.push(editedLink)}})},$scope.addDrawings=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Legg til Tegning",columns:[{Title:translationService.translate("web-drawing-id"),Property:"Id"},{Title:translationService.translate("web-drawing-description"),Property:"Description"}],url:repository.apiData.drawing.url,sorting:{Id:"asc"},filter:{},useObjects:!0}}}}).result.then(function(selectedItems){$scope.model.WidgetData.Drawings||($scope.model.WidgetData.Drawings=[]),selectedItems.forEach(function(item){_.find($scope.model.WidgetData.Drawings,function(o){return o.Guid===item.Guid})||$scope.model.WidgetData.Drawings.push(item)})},function(error){})},$scope.addNewColumn=function(type){if(!$scope.model.WidgetData.prefix)return void swal(translationService.translate("web-widget-addNewListColumn-missingPrefix-title","Mangler datatype"),translationService.translate("web-widget-addNewListColumn-missingPrefix-message","Velg en datatype for å kunne legge til en kolonne"),"warning");$modal.open({templateUrl:"app/common/views/addNewListColumnModal.html",controller:"AddNewListColumnController",resolve:{params:function(){return{prefix:$scope.model.WidgetData.prefix,existingColumns:"filter"===type?null:$scope.model.WidgetData.columns,hideExpandableColumns:"keycolumn"===type,showAdvancedMode:!0}}}}).result.then(function(selectedColumns){var column=selectedColumns[0];"filter"===type&&selectedColumns.forEach(function(column){column.Filter=[{Operator:"=",Property:column.Property}],column.PropertyType.startsWith("enum.")&&(column.Filter[0].Value=null),$scope.model.WidgetData.columns.push(column),"date"===column.PropertyType&&($scope.datePickers[column.$$hashKey]=!1)}),"keycolumn"===type&&($scope.model.WidgetData.kpiProperty={title:column.Title,property:column.Property,propertyType:column.PropertyType,operation:$scope.model.WidgetData.kpiProperty.operation,value:""}),"interval"===type&&($scope.model.WidgetData.interval={title:column.Title,property:column.Property,daysBack:0,daysForward:0}),"keyGroupColumn"===type&&($scope.model.WidgetData.kpiGroupTable.groupColumn={Title:column.Title,Property:column.Property,PropertyType:column.PropertyType},$scope.updateSortingColumns()),"valueColumn"===type&&(selectedColumns.forEach(function(column){var valueColumn={Title:column.Title,Property:column.Property,Function:"number"!==column.PropertyType&&"double"!==column.PropertyType&&"decimal"!==column.PropertyType||"Id"===column.Property?"count":"sum",PropertyType:column.PropertyType};$scope.model.WidgetData.kpiGroupTable.valueColumns.push(valueColumn),"date"===column.PropertyType&&($scope.datePickers[column.$$hashKey]=!1)}),$scope.updateSortingColumns())})},$scope.valueColumnFunctionFilter=function(column){return function(valueFunction){return("number"===column.PropertyType||"double"===column.PropertyType||"decimal"===column.PropertyType)&&"Id"!==column.Property||("count"===valueFunction.function||"percent"===valueFunction.function)}},$scope.openIconModal=function(){$modal.open({templateUrl:"app/common/modal/views/selectIconModal.html",controller:"SelectIconModalController"}).result.then(function(selectedIcon){$scope.model.WidgetData.icon=selectedIcon})},$scope.removeIcon=function(){$scope.model.WidgetData.icon=null},$scope.$watch("model.WidgetData.kpiProperty.operation",function(newValue,oldValue){newValue!==oldValue&&("count"!==newValue||$scope.model.WidgetData.kpiProperty.property||($scope.model.WidgetData.kpiProperty={title:"Guid",property:"Guid",operation:"count",value:""}))}),$scope.onHtmlDataTypeSelect=function(){$scope.model.WidgetData&&($scope.model.WidgetData.prefix?($scope.model.WidgetData.ServiceUrl=repository.apiData.building.url,$scope.model.WidgetData.prefix=repository.apiData.building.prefix,$scope.model.WidgetData.fromActiveBuilding=!0):($scope.model.WidgetData.ServiceUrl="",$scope.model.WidgetData.prefix="",$scope.model.WidgetData.fromActiveBuilding=!1),setTinymceOptions())},$scope.validateWidget=function(){switch($scope.model.WidgetType){case"pl-table-widget":case"pl-list-widget":case"pl-link-widget":break;case"pl-report-widget":if(!$scope.model.WidgetData.ReportName)return repository.growl(translationService.translate("web-reportWidget-missing-reportName","Rapport er obligatorisk"),"danger"),!1;break;case"pl-drawing-widget":if(!$scope.model.WidgetData.DrawingSource)return repository.growl(translationService.translate("web-drawingWidget-missing-drawingSource","Må velge en datakilde for tegninger"),"danger"),!1;break;case"pl-kpi-widget":var property=$scope.model.WidgetData.kpiProperty;if(!property)return repository.growl(translationService.translate("web-kpiWidget-missing-selectedDatatype","Datatype er obligatorisk"),"danger"),!1;if(!property.operation)return repository.growl(translationService.translate("web-kpiWidget-missing-operation","Kalkuleringstype er obligatorisk"),"danger"),!1;if("count"!==property.operation&&!property.property)return repository.growl(translationService.translate("web-kpiWidget-missing-property","Nøkkelkolonne er obligatorisk"),"danger"),!1;if("percent"===property.operation&&property.propertyType.startsWith("enum.")&&(void 0===property.value||null===property.value||""===property.value))return repository.growl(translationService.translate("web-kpiWidget-percentOperation-enumMissingValue","Mangler sammenligningsverdi"),"danger"),!1;break;case"pl-kpi-group-table-widget":if(!$scope.model.WidgetData.prefix)return repository.growl(translationService.translate("web-kpiGroupTableWidget-missing-prefix","Datatype er obligatorisk"),"danger"),!1;if(!$scope.model.WidgetData.kpiGroupTable.groupColumn)return repository.growl(translationService.translate("web-kpiGroupTableWidget-missing-groupColumn","Grupperingskolonne er obligatorisk"),"danger"),!1;if(!$scope.model.WidgetData.kpiGroupTable.valueColumns||!$scope.model.WidgetData.kpiGroupTable.valueColumns.length)return repository.growl(translationService.translate("web-kpiGroupTableWidget-missing-valueColumns","Minst 1 verdi kolonne må bli valgt"),"danger"),!1;break;case"pl-chart-widget":if(!$scope.model.WidgetData.prefix)return repository.growl(translationService.translate("web-chartWidget-missing-prefix","Datatype er obligatorisk"),"danger"),!1;if(!$scope.model.WidgetData.kpiGroupTable.groupColumn)return repository.growl(translationService.translate("web-chartWidget-missing-groupColumn","Grupperingskolonne er obligatorisk"),"danger"),!1;if(!$scope.model.WidgetData.kpiGroupTable.valueColumns||!$scope.model.WidgetData.kpiGroupTable.valueColumns.length)return repository.growl(translationService.translate("web-chartWidget-missing-valueColumns","Minst 1 verdi kolonne må bli valgt"),"danger"),!1}return $scope.model.WidgetData.AutoRefresh&&(!$scope.model.WidgetData.RefreshInterval||$scope.model.WidgetData.RefreshInterval<$scope.minimumRefreshInterval)&&($scope.model.WidgetData.RefreshInterval=$scope.minimumRefreshInterval),!0},$scope.save=function(){$scope.validateWidget()&&("pl-drawing-widget"===$scope.model.WidgetType&&"selection"!==$scope.model.WidgetData.DrawingSource&&($scope.model.WidgetData.Drawings=[]),modalInstance.close($scope.model))},$scope.cancel=function(reason){modalInstance.dismiss("cancel")}}angular.module("Plania").controller("AddWidgetModalController",["$scope","Repository","$modalInstance","$modal","TranslationService","IconService","ListService","widget","DwgThemeService","$timeout",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,translationService,$q,$state,colorService){$scope.edit=$stateParams.editMode,$scope.model={},$scope.restrictEdit=!0;var convertColors=function(widgetData){return widgetData?(widgetData.color&&(widgetData.color=colorService.convertToRainbow(widgetData.color)),widgetData.thresholds&&Array.isArray(widgetData.thresholds)&&widgetData.thresholds.length&&widgetData.thresholds.forEach(function(threshold){threshold.color&&(threshold.color=colorService.convertToRainbow(threshold.color))}),widgetData):widgetData},parseWidgetData=function(){$scope.model.WidgetDtos.forEach(function(widget){widget.WidgetData&&"string"==typeof widget.WidgetData&&(widget.WidgetData=convertColors(JSON.parse(widget.WidgetData)))})};$scope.openDashboardSettings=function(){var edit=!!$stateParams.guid;$modal.open({templateUrl:"app/dashboard/dashboardSettingsModal.html",controller:"DashboardSettingsModalController",resolve:{params:function(){return{edit:edit,model:$scope.model}}}}).result.then(function(selectedWidget){$scope.saveDashboard()},function(){})};var updateAccess=function(){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.WebDashboard,checkOtherDO)},errorFunction=function(error){"Ingen data funnet"===error?repository.growl(translationService.translate("web-dashboard-couldnotfind-error","Kunne ikke finne dashbordet, sjekk at dashbord er registrert på riktig klient i forhold til rettighetsprofil"),"danger"):repository.growl(error,"danger")};$stateParams.guid?repository.getSingle(repository.apiData.webDashboard.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess(),parseWidgetData()},errorFunction):$scope.navigation.params.menuGuid?(menuParams=repository.getMenuParameters($scope.navigation.params.menuGuid),repository.getSingle(repository.apiData.webDashboard.url,menuParams.GuidDashboard).then(function(response){$scope.model=response.Data,updateAccess(),parseWidgetData()},errorFunction)):repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix.WebDashboard).then(function(result){$scope.model.WidgetDtos=[],$scope.restrictEdit=!1,$scope.openDashboardSettings()}),$scope.openAddWidgetModal=function(){$modal.open({templateUrl:"app/dashboard/addWidgetModal.html",controller:"AddWidgetModalController",resolve:{widget:function(){return null}}}).result.then(function(selectedWidget){$scope.sharedControl.addNewWidget(selectedWidget),$scope.saveDashboard(!1)},function(){})},$scope.toggleEdit=function(){$scope.edit=!$scope.edit,$scope.sharedControl.setMode($scope.edit)};var disableEdit=function(){$scope.edit=!1,$scope.sharedControl.setMode($scope.edit)};$scope.sharedControl={},$scope.saveDashboard=function(shouldDisableEdit){var deferred=$q.defer(),error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger"),deferred.reject()};return $scope.model.WidgetDtos.forEach(function(widget){"object"==typeof widget.WidgetData&&(widget.WidgetData=JSON.stringify(widget.WidgetData))}),$scope.model.Guid?repository.updateSingle(repository.apiData.webDashboard.url,$scope.model).then(function(response){repository.growl("Dashbordet har blitt oppdatert","info"),parseWidgetData(),shouldDisableEdit&&disableEdit(),deferred.resolve(response)}).catch(error):repository.createSingle(repository.apiData.webDashboard.url,$scope.model).then(function(response){repository.growl("Dashbordet har blitt opprettet","info"),$scope.model.Guid=response.Guid,parseWidgetData(),shouldDisableEdit&&disableEdit(),$state.go("dashboard.view",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid},{location:"replace"}),deferred.resolve(response)}).catch(error),deferred.promise},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("DashboardController",["$scope","Repository","$stateParams","$modal","TranslationService","$q","$state","ColorService",controller])}(),function(){function controller($scope,repository,modalInstance,$modal,translationService,params){$scope.model=params.model,$scope.edit=params.edit,$scope.save=function(){modalInstance.close($scope.model)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dashboard-message","Dashboardet vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dashboard-button-confirm","Ja, fjern dashboardet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.webDashboard.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-dashboard-success","Dashboardet ble fjernet!"),result,"success"),$scope.goBack("dashboard.list",{menuGuid:$scope.navigation.params.menuGuid}),modalInstance.dismiss("deleted")})})},$scope.cancel=function(reason){modalInstance.dismiss("cancel")}}angular.module("Plania").controller("DashboardSettingsModalController",["$scope","Repository","$modalInstance","$modal","TranslationService","params",controller])}(),angular.module("Plania").factory("DashboardSharedDataService",[function(){var service={},selectedDrawingGuids=[];return service.getDrawingGuids=function(){return selectedDrawingGuids},service.setDrawingGuids=function(drawingGuids){for(;selectedDrawingGuids.length>0;)selectedDrawingGuids.pop();drawingGuids.forEach(function(guid){selectedDrawingGuids.push(guid)})},service}]),function(){var app=angular.module("Plania");app.directive("plDashboardGrid",["$injector","$compile","$parse","$http",function($injector,$compile,$parse,$http){return{restrict:"E",replace:!0,scope:{widgets:"=widgets",control:"=control",edit:"=edit",saveFunction:"=saveFunction"},templateUrl:"/app/dashboard/directives/dashboardGrid.html",controller:function($scope,$compile,$parse,$http){$scope.internalControl=$scope.control||{};var gridOptions={alwaysShowResizeHandle:!0,cellHeight:75,animate:!0,resizable:{handles:"e, se, s, sw, w"}};$scope.grid=$(".grid-stack").gridstack(gridOptions).data("gridstack"),$(".grid-stack").on("change",function(e,nodes){for(var i=$scope.widgets.length-1;i>=0;i--){var widget=$scope.widgets[i],node=_.find(nodes,{id:widget.Guid});node&&(widget.GridHeight=node.height,widget.GridWidth=node.width,widget.GridPositionY=node.y,widget.GridPositionX=node.x)}});var isAvailable=function(newWidget,x,y){return!_.find($scope.grid.grid.nodes,function(b){var a={x:x,y:y,width:newWidget.GridWidth,height:newWidget.GridHeight};return!(a.x+a.width<=b.x||b.x+b.width<=a.x||a.y+a.height<=b.y||b.y+b.height<=a.y)})};$scope.internalControl.addNewWidget=function(newWidgetModel){var width=12,gridHeight="pl-kpi-widget"===newWidgetModel.WidgetType?1:4;GridStackUI.Utils.sort($scope.grid.grid.nodes,1,width);for(var newWidget={Guid:Math.floor(68719476736*Math.random()).toString(32),GridPositionX:0,GridPositionY:0,GridWidth:4,GridHeight:gridHeight,WidgetType:newWidgetModel.WidgetType,WidgetData:newWidgetModel.WidgetData,Id:newWidgetModel.Id,Description:newWidgetModel.Description},i=0;;++i){var x=i%width,y=Math.floor(i/width);if(!(x+newWidget.GridWidth>width)&&isAvailable(newWidget,x,y)){newWidget.GridPositionX=x,newWidget.GridPositionY=y;break}}$scope.widgets.push(newWidget)},$scope.internalControl.setMode=function(isEdit){$scope.edit=isEdit,$scope.grid.movable(".grid-stack-item",isEdit),$scope.grid.resizable(".grid-stack-item",isEdit)},$scope.attachWidget=function(element,attrs){$scope.grid.addWidget(element,attrs.gsX,attrs.gsY,attrs.gsWidth,attrs.gsHeight,attrs.gsAutoPosition,null,null,null,null,attrs.gsId),$scope.internalControl.setMode($scope.edit)},$scope.removeWidget=function(element,attrs){$scope.grid.remove_widget(element),$scope.widgets=_.reject($scope.widgets,function(widget){return widget.Guid===attrs.gsId})}}}}]),app.directive("addWidget",function($parse,$compile){return{compile:function(tElement,tAttrs){var directiveGetter=$parse(tAttrs.addWidget);return function(scope,element){element.removeAttr("add-widget");var directive=directiveGetter(scope);element.attr(directive,""),$compile(element)(scope)}}}})}(),function(){function controller($scope,modalInstance,link,translationService){$scope.isUpdate=!!link,$scope.linkTypes=[{value:"UrlLink",name:translationService.translate("web-web-webDashboardWidget-link-type-urlLink","Url lenke")},{value:"WebMenu",name:translationService.translate("web-web-webDashboardWidget-link-type-webMenu","Webmeny")}],link?($scope.model=link,$scope.model.Type||($scope.model.Type="UrlLink")):$scope.model={},$scope.activateAutocomplete=!0,$scope.onWebmenuSelect=function(webmenu){if(!webmenu)return void($scope.model.GuidWebMenu="");$scope.model.GuidWebMenu=webmenu.Guid,$scope.model.Title||($scope.model.Title=webmenu.Name)},$scope.isSaveDisabled=function(){return!$scope.model.Title||!$scope.model.Type||("UrlLink"===$scope.model.Type?!$scope.model.Url:"WebMenu"===$scope.model.Type&&!$scope.model.GuidWebMenu)},$scope.save=function(){$scope.model.IsExternalLink&&0!==$scope.model.Url.indexOf("http")&&($scope.model.Url="https://"+$scope.model.Url),modalInstance.close($scope.model)},$scope.cancel=function(){modalInstance.dismiss("cancel")}}angular.module("Plania").controller("AddNewLinkModalController",["$scope","$modalInstance","link","TranslationService",controller])}(),function(){function safeController($scope,translationService,repository,modal,$timeout){try{controller($scope,translationService,repository,modal,$timeout)}catch(error){console.log(error)}}function controller($scope,translationService,repository,modal,$timeout){$scope.model=$scope.widget,$scope.eventSource=repository.apiData.workOrder.url,$scope.sharedController={},$scope.editWidget=function(){modal.open({controller:"AddWidgetModalController",templateUrl:"app/dashboard/addWidgetModal.html",resolve:{widget:function(){return $scope.model}}}).result.then(function(widgetModel){$scope.saveFunction(!1)},function(){})}}angular.module("Plania").directive("plCalendarWidget",["TranslationService","$timeout",function(translationService,$timeout){return{restrict:"A",require:"^plDashboardGrid",scope:{widget:"=widget",edit:"=edit",saveFunction:"=saveFunction"},link:function(scope,element,attrs,gridCtrl){scope.$parent.attachWidget(element,attrs),scope.removeWidget=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dashboard-calendar-message","Kalenderen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dashboard-calendar-confirm","Ja, fjern kalenderen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-dashboard-calendar-success","Kalenderen ble fjernet!"),"","success"),scope.$parent.removeWidget(element,attrs)})},$(".grid-stack").on("resizestop",function(event,ui){$(event.target).find(".pl-calendar-widget").length>0&&$timeout(function(){scope.setHeight()},350)}),scope.setHeight=function(){if(scope.sharedController&&scope.sharedController.resizeCalendar){var ele=$(element).find(".pl-calendar-widget");if(ele){var bodyHeight=ele.height();scope.sharedController.resizeCalendar(bodyHeight)}}},$timeout(function(){scope.setHeight()},10)},templateUrl:"app/dashboard/directives/widgets/calendarWidget.html",controller:["$scope","TranslationService","Repository","$modal","$timeout",safeController]}}])}(),function(){function safeController($scope,translationService,repository,ngTableParams,modal,$rootScope,$filter,$interval,$localStorage,listCompressionService){try{controller($scope,translationService,repository,ngTableParams,modal,$rootScope,$filter,$interval,$localStorage,listCompressionService)}catch(error){console.log(error)}}function controller($scope,translationService,repository,ngTableParams,modal,$rootScope,$filter,$interval,$localStorage,listCompressionService){function getPropertyFilters(){var filters=[];return $scope.model.WidgetData.columns&&$scope.model.WidgetData.columns.length>0&&$scope.model.WidgetData.columns.forEach(function(col){col.Filter&&filters.push(angular.copy(col.Filter[0]))}),repository.GetKeywordFilters(filters)}$scope.model=$scope.widget,$scope.chartData=[],$scope.hasReadAccess=!1;"string"==typeof $scope.model.WidgetData&&($scope.model.WidgetData=JSON.parse($scope.model.WidgetData)),$scope.editWidget=function(){modal.open({controller:"AddWidgetModalController",templateUrl:"app/dashboard/addWidgetModal.html",resolve:{widget:function(){return $scope.model}}}).result.then(function(widgetModel){$scope.saveFunction(!1).then(function(){getChartData()})},function(){})} ;var getChartData=function(){$scope.chartData=[];var kpi={Prefix:$scope.model.WidgetData.prefix,FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,PropertyFilter:getPropertyFilters(),Properties:[],RowGroup:$scope.model.WidgetData.kpiGroupTable.groupColumn.Property};$scope.model.WidgetData.kpiGroupTable.valueColumns.forEach(function(valCol){kpi.Properties.push({Property:valCol.Property,Function:valCol.Function})});var filter=repository.commonService.getFilterData();filter.selectedBuilding&&filter.selectedBuilding.Guid&&(kpi.GuidBuilding=filter.selectedBuilding.Guid),filter.selectedEstate&&filter.selectedEstate.Guid&&(kpi.GuidEstate=filter.selectedEstate.Guid),filter.selectedSelection&&filter.selectedSelection.Guid&&(kpi.GuidSelection=filter.selectedSelection.Guid),repository.createSingle(repository.apiData.kpi.url,kpi).then(function(result){result.forEach(function(res){$scope.chartData.push({Caption:res.GroupCaption,Value:res.Result[0].Value,text:res.GroupCaption+", "+res.Result[0].Value})})})};getChartData(),$scope.$on($rootScope.events.newSelection,function(){getChartData()})}angular.module("Plania").directive("plChartWidget",["TranslationService",function(translationService){return{restrict:"A",require:"^plDashboardGrid",scope:{widget:"=widget",edit:"=edit",saveFunction:"=saveFunction"},link:function(scope,element,attrs,gridCtrl){scope.$parent.attachWidget(element,attrs),scope.removeWidget=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-chart-widget-message","Grafen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-chart-widget-confirm","Ja, fjern grafen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-chart-widget-success","Grafen ble fjernet!"),"","success"),scope.$parent.removeWidget(element,attrs)})}},templateUrl:"app/dashboard/directives/widgets/chartWidget.html",controller:["$scope","TranslationService","Repository","NgTableParams","$modal","$rootScope","$filter","$interval","$localStorage","ListCompressionService",safeController]}}])}(),function(){function safeController($scope,translationService,repository,modal,$interval,sharedDataService,$rootScope){try{controller($scope,translationService,repository,modal,$interval,sharedDataService,$rootScope)}catch(error){console.log(error)}}function controller($scope,translationService,repository,modal,$interval,sharedDataService,$rootScope){$scope.model=$scope.widget,$scope.model.fullscreen=!1,$scope.showNetAreal=!0,$scope.isStaticTheme=!0,$scope.update=!1,$scope.errorState={hasError:!1,text:""},"string"==typeof $scope.model.WidgetData&&($scope.model.WidgetData=JSON.parse($scope.model.WidgetData)),$scope.drawings=[];var areas=[],getDrawings=function(){$scope.errorState={hasError:!1,text:""};var filter={PropertyFilter:[]},guidDrawings=[];if($scope.model.WidgetData.DrawingSource&&"selection"!==$scope.model.WidgetData.DrawingSource)switch($scope.model.WidgetData.DrawingSource){case"personOrganization":if(!$rootScope.userInfo.guidPersonOrganization)return $scope.drawings=[],areas=[],delete $scope.model.selectedDrawing,$scope.errorState.hasError=!0,void($scope.errorState.text="Mangler organisasjon på person.");filter.PropertyFilter.push({Property:"Areas.GuidOrganization",Operator:"=",Value:$rootScope.userInfo.guidPersonOrganization});break;case"personOrganizationUnit":if(!$rootScope.userInfo.guidPersonOrganizationUnit)return $scope.drawings=[],areas=[],delete $scope.model.selectedDrawing,$scope.errorState.hasError=!0,void($scope.errorState.text="Mangler organisasjonsenhet på person.");filter.PropertyFilter.push({Property:"Areas.GuidOrganizationUnit",Operator:"=",Value:$rootScope.userInfo.guidPersonOrganizationUnit});break;case"personOrganizationSection":if(!$rootScope.userInfo.guidPersonOrganizationSection)return $scope.drawings=[],areas=[],delete $scope.model.selectedDrawing,$scope.errorState.hasError=!0,void($scope.errorState.text="Mangler organisasjonseksjon på person.");filter.PropertyFilter.push({Property:"Areas.GuidOrganizationSection",Operator:"=",Value:$rootScope.userInfo.guidPersonOrganizationSection})}else{if("object"==typeof $scope.model.WidgetData.Drawings[0]?guidDrawings=_.map($scope.model.WidgetData.Drawings,"Guid"):"string"==typeof $scope.model.WidgetData.Drawings[0]&&(guidDrawings=$scope.model.WidgetData.Drawings),!guidDrawings.length)return $scope.drawings=[],areas=[],void delete $scope.model.selectedDrawing;filter.PropertyFilter.push({Property:"Guid",Operator:"in",Value:guidDrawings.join(",")})}repository.GetPaginated(repository.apiData.drawing.url,0,-1,{},filter,null,JSON.stringify(["Id","Description"])).then(function(result){var drawings=result.List;guidDrawings.length&&(drawings=drawings.sort(function(a,b){return guidDrawings.indexOf(a.Guid)-guidDrawings.indexOf(b.Guid)})),$scope.drawings=drawings,$scope.model.selectedDrawing=$scope.drawings[0];var guidSelectedDrawings=_.map($scope.drawings,"Guid");sharedDataService.setDrawingGuids(guidSelectedDrawings),areas=[];var filter={PropertyFilter:[{Property:"GuidDrawing",Operator:"in",value:guidSelectedDrawings.join(",")}]};repository.GetPaginated(repository.apiData.area.url,0,-1,{},filter,null,JSON.stringify(["Id"])).then(function(result){areas=areas.concat(result.List)})},function(error){repository.showError(error)})};getDrawings(),$scope.$on("dashboard.activateItem",function(evt,data){if(data.GuidArea){var area=_.find(areas,{Guid:data.GuidArea});if(area){var drawing=_.find($scope.drawings,{Guid:area.GuidDrawing});drawing&&($scope.model.selectedDrawing=drawing,$scope.model.highlightArea=data.GuidArea)}}}),$scope.setFullscreen=function(){$scope.model.fullscreen=!$scope.model.fullscreen},$scope.editWidget=function(){modal.open({controller:"AddWidgetModalController",templateUrl:"app/dashboard/addWidgetModal.html",resolve:{widget:function(){return $scope.model}}}).result.then(function(widgetModel){$scope.saveFunction(!1).then(function(){getDrawings()})},function(){})},$scope.updateFunction=function(){$scope.update=!$scope.update}}angular.module("Plania").directive("plDrawingWidget",["TranslationService",function(translationService){return{restrict:"A",require:"^plDashboardGrid",scope:{widget:"=widget",edit:"=edit",saveFunction:"=saveFunction",shouldStopInterval:"=shouldStopInterval"},link:function(scope,element,attrs,gridCtrl){scope.$parent.attachWidget(element,attrs),scope.removeWidget=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dashboard-drawing-message","Tegningene vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dashboard-drawing-confirm","Ja, fjern tegningene"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-dashboard-drawing-success","Tegningene ble fjernet!"),"","success"),scope.$parent.removeWidget(element,attrs)})}},templateUrl:"app/dashboard/directives/widgets/drawingWidget.html",controller:["$scope","TranslationService","Repository","$modal","$interval","DashboardSharedDataService","$rootScope",safeController]}}])}(),function(){function safeController($scope,commonService,repository,$rootScope,$sce,modal,$filter){try{controller($scope,commonService,repository,$rootScope,$sce,modal,$filter)}catch(error){console.log(error)}}function controller($scope,commonService,repository,$rootScope,$sce,modal,$filter){function setHtmlBody(tmpString,properties,mappedProperties,userProperties){if(properties&&properties.length>0)for(var i=0;i0)for(var mappedUserProperties=userProperties.map(function(x){return x.match(/[\@\w\.]+/)[0]}),j=0;j0&&$scope.model.WidgetData.columns.forEach(function(col){col.Filter&&filters.push(angular.copy(col.Filter[0]))}),repository.GetKeywordFilters(filters)}function cancelInterval(interval){$interval.cancel(interval),interval=void 0}$scope.model=$scope.widget,$scope.kpiResult=[],$scope.rowTotals={},$scope.columnTotals={},$scope.grandTotal={value:0,stringValue:"0"},$scope.hasReadAccess=!1;var refreshInterval;if("string"==typeof $scope.model.WidgetData&&($scope.model.WidgetData=JSON.parse($scope.model.WidgetData)),$scope.editWidget=function(){modal.open({controller:"AddWidgetModalController",templateUrl:"app/dashboard/addWidgetModal.html",resolve:{widget:function(){return $scope.model}}}).result.then(function(widgetModel){$scope.saveFunction(!1).then(function(){initializeData(),getKpiData(),updateAutoRefresh()})},function(){})},$scope.model.WidgetData){var initializeData=function(){$scope.visibleColumns=[],$scope.visibleColumns.push($scope.model.WidgetData.kpiGroupTable.groupColumn),$scope.model.WidgetData.kpiGroupTable.valueColumns.forEach(function(valCol){var valColCopy=angular.copy(valCol),functionTitle="";"sum"===valCol.Function?functionTitle=translationService.translate("web-widget-function-sum-headerTitle","Sum"):"count"===valCol.Function?functionTitle=translationService.translate("web-widget-function-count-headerTitle","Antall"):"average"===valCol.Function?functionTitle=translationService.translate("web-widget-function-average-headerTitle","Snitt"):"max"===valCol.Function?functionTitle=translationService.translate("web-widget-function-max-headerTitle","Maks"):"min"===valCol.Function&&(functionTitle=translationService.translate("web-widget-function-min-headerTitle","Min")),valColCopy.Title=functionTitle+" "+valCol.Title,$scope.visibleColumns.push(valColCopy)}),$scope.model.WidgetData.kpiGroupTable.showRowTotal&&$scope.visibleColumns.push({Title:translationService.translate("web-dashboard-kpiGroupTableWidget-rowTotal","Total"),PropertyType:"double",Property:"RowTotal"})};initializeData();var getKpiData=function(){if($scope.model.WidgetData&&$scope.model.WidgetData.prefix?$scope.hasReadAccess=$rootScope.hasReadAccess($scope.model.WidgetData.prefix):$scope.hasReadAccess=!1,$scope.hasReadAccess){var kpi={Prefix:$scope.model.WidgetData.prefix,FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,PropertyFilter:getPropertyFilters(),Properties:[],RowGroup:$scope.model.WidgetData.kpiGroupTable.groupColumn.Property};$scope.model.WidgetData.kpiGroupTable.valueColumns.forEach(function(valCol){kpi.Properties.push({Property:valCol.Property,Function:valCol.Function})});var filter=repository.commonService.getFilterData();filter.selectedBuilding&&filter.selectedBuilding.Guid&&(kpi.GuidBuilding=filter.selectedBuilding.Guid),filter.selectedEstate&&filter.selectedEstate.Guid&&(kpi.GuidEstate=filter.selectedEstate.Guid),filter.selectedSelection&&filter.selectedSelection.Guid&&(kpi.GuidSelection=filter.selectedSelection.Guid),repository.createSingle(repository.apiData.kpi.url,kpi).then(function(result){$scope.kpiResult=result;var totalColumnSum={},grandTotal=0,showRowDecimal=$scope.model.WidgetData.kpiGroupTable.valueColumns.some(function(col){return"double"===col.PropertyType||"decimal"===col.PropertyType});$scope.kpiResult.forEach(function(res){var totalRowSum=0;res.Result.forEach(function(kpiResult,index){totalRowSum+=parseFloat(kpiResult.Value),totalColumnSum[index]||(totalColumnSum[index]=0),totalColumnSum[index]+=parseFloat(kpiResult.Value)}),grandTotal+=totalRowSum,$scope.rowTotals[res.GroupCaption]={value:totalRowSum,stringValue:$filter("number")(totalRowSum,showRowDecimal?2:0)}}),$scope.grandTotal={value:grandTotal,stringValue:$filter("number")(grandTotal,showRowDecimal?2:0)},$scope.model.WidgetData.kpiGroupTable.valueColumns.forEach(function(col,index){var showColumnDecimal="double"===col.PropertyType||"decimal"===col.PropertyType;$scope.columnTotals[index]={value:totalColumnSum[index],stringValue:$filter("number")(totalColumnSum[index],showColumnDecimal?2:0)}}),$scope.widgetTable.reload()})}};getKpiData(),$scope.model.WidgetData.kpiGroupTable.sortingColumn||($scope.model.WidgetData.kpiGroupTable.sortingColumn={Property:$scope.model.WidgetData.kpiGroupTable.groupColumn.Property,Direction:"asc"}),$scope.widgetTable=new ngTableParams({count:$scope.model.WidgetData.defaultPaginationCount?$scope.model.WidgetData.defaultPaginationCount:10,page:1,sorting:$scope.model.WidgetData.kpiGroupTable.sortingColumn},{counts:[10,25,50,100,translationService.translate("web-table-pagination-all","Alle")],getData:function($defer,params){var list=sortTable($scope.kpiResult,params.sorting());params.count()!==translationService.translate("web-table-pagination-all","Alle")&&(list=list.slice((params.page()-1)*params.count(),params.page()*params.count())),$defer.resolve(list),params.total($scope.kpiResult.length)}});var updateAutoRefresh=function(){$scope.model.WidgetData.AutoRefresh&&$scope.model.WidgetData.RefreshInterval?(refreshInterval&&cancelInterval(refreshInterval),refreshInterval=$interval(function(){getKpiData()},1e3*$scope.model.WidgetData.RefreshInterval),$scope.$on("$destroy",function(){cancelInterval(refreshInterval)})):refreshInterval&&cancelInterval(refreshInterval)};updateAutoRefresh(),$scope.formatValueField=function(valueField){var propertyColumn=$scope.visibleColumns.find(function(col){return col.Property===valueField.Property});return $filter("number")(valueField.Value,!propertyColumn||"double"!==propertyColumn.PropertyType&&"decimal"!==propertyColumn.PropertyType?0:2)},$scope.formatGroupCaption=function(text){return $scope.model.WidgetData.kpiGroupTable&&$scope.model.WidgetData.kpiGroupTable.groupColumn&&"date"===$scope.model.WidgetData.kpiGroupTable.groupColumn.PropertyType?$filter("date")(new Date(text),"dd.MM.yyyy"):text};var sortTable=function(tableData,sortingColumn){return sortingColumn?(sortingColumn.Function?tableData.sort(function(a,b){var valA,valB;return a.Result.forEach(function(property){property.Property===sortingColumn.Property&&property.Function===sortingColumn.Function&&(valA=property.Value)}),b.Result.forEach(function(property){property.Property===sortingColumn.Property&&property.Function===sortingColumn.Function&&(valB=property.Value)}),valA-valB>0?1:valA-valB<0?-1:0}):"RowTotal"===sortingColumn.Property?tableData.sort(function(a,b){var valA=$scope.rowTotals[a.GroupCaption].value,valB=$scope.rowTotals[b.GroupCaption].value;return valA-valB>0?1:valA-valB<0?-1:0}):"number"===sortingColumn.PropertyType||"double"===sortingColumn.PropertyType?tableData.sort(function(a,b){return a.GroupCaption-b.GroupCaption}):"date"===sortingColumn.PropertyType?tableData.sort(function(a,b){return"Undefined"===a.GroupCaption||"Undefined"===b.GroupCaption?-1:new Date(a.GroupCaption)-new Date(b.GroupCaption)}):tableData.sort(function(a,b){return a.GroupCaptionb.GroupCaption?1:0}),"desc"===sortingColumn.Direction&&tableData.reverse(),tableData):tableData};$scope.sortByColumn=function(sortColumn){sortColumn.Direction="asc"===sortColumn.Direction?"desc":"asc",$scope.widgetTable.sorting(sortColumn)},$scope.$on($rootScope.events.newSelection,function(){getKpiData()})}}angular.module("Plania").directive("plKpiGroupTableWidget",["TranslationService",function(translationService){return{restrict:"A",require:"^plDashboardGrid",scope:{widget:"=widget",edit:"=edit",saveFunction:"=saveFunction"},link:function(scope,element,attrs,gridCtrl){scope.$parent.attachWidget(element,attrs),scope.removeWidget=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dashboard-table-message","Tabellen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dashboard-table-confirm","Ja, fjern tabellen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-dashboard-table-success","Tabellen ble fjernet!"),"","success"),scope.$parent.removeWidget(element,attrs)})}},templateUrl:"app/dashboard/directives/widgets/kpiGroupTableWidget.html",controller:["$scope","TranslationService","Repository","NgTableParams","$modal","$rootScope","$filter","$interval","$localStorage",safeController]}}])}(),function(){function safeController($scope,translationService,iconService,repository,modal,$rootScope,listCompressionService,$state){try{controller($scope,translationService,iconService,repository,modal,$rootScope,listCompressionService,$state)}catch(error){console.log(error)}}function controller($scope,translationService,iconService,repository,modal,$rootScope,listCompressionService,$state){function getPropertyFilters(){var filters=[];return $scope.model.WidgetData.columns&&$scope.model.WidgetData.columns.length>0&&$scope.model.WidgetData.columns.forEach(function(col){col.Filter&&filters.push(angular.copy(col.Filter[0]))}),repository.GetKeywordFilters(filters)}function getKpiObject(){var kpi={Prefix:$scope.model.WidgetData.prefix,FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,PropertyFilter:getPropertyFilters(),Properties:[]};if($scope.model.WidgetData.interval){var today=new Date;today.setDate(today.getDate()-$scope.model.WidgetData.interval.daysBack),kpi.FromDate=today.toISOString(),today=new Date,today.setDate(today.getDate()+$scope.model.WidgetData.interval.daysForward),kpi.ToDate=today.toISOString(),kpi.DateProperty=$scope.model.WidgetData.interval.property}$scope.model.WidgetData.kpiProperty&&(kpi.Properties=[{Property:$scope.model.WidgetData.kpiProperty.property,Function:$scope.model.WidgetData.kpiProperty.operation,Value:$scope.model.WidgetData.kpiProperty.value}]);var filter=repository.commonService.getFilterData();filter.selectedBuilding&&filter.selectedBuilding.Guid&&(kpi.GuidBuilding=filter.selectedBuilding.Guid),filter.selectedEstate&&filter.selectedEstate.Guid&&(kpi.GuidEstate=filter.selectedEstate.Guid),filter.selectedSelection&&filter.selectedSelection.Guid&&(kpi.GuidSelection=filter.selectedSelection.Guid);var propertyFilter=angular.copy(kpi.PropertyFilter);return $scope.model.WidgetData.kpiProperty&&"percent"===$scope.model.WidgetData.kpiProperty.operation&&propertyFilter.push({Property:$scope.model.WidgetData.kpiProperty.property,Operator:"=",Value:$scope.model.WidgetData.kpiProperty.value}),$scope.kpiPrefixParams=listCompressionService.encodeListUri({filter:{PropertyFilter:propertyFilter},selectedListSetup:$scope.model.WidgetData.SelectedListSetup}),$scope.kpiPrefixState=getKpiNavState(),kpi}$scope.model=$scope.widget,$scope.color="black",$scope.errorMessage="",$scope.iconMap=iconService.GetIconMap(),$scope.getIcon=iconService.getIcon,$scope.editWidget=function(){modal.open({controller:"AddWidgetModalController",templateUrl:"app/dashboard/addWidgetModal.html",resolve:{widget:function(){return $scope.model}}}).result.then(function(widgetModel){$scope.saveFunction(!1).then(function(){getKpi()})},function(){})},"string"==typeof $scope.model.WidgetData&&($scope.model.WidgetData=JSON.parse($scope.model.WidgetData));var setColor=function(){var widgetData=$scope.model.WidgetData;if(widgetData.thresholds&&widgetData.thresholds.length>0&&$scope.model.Value){var colorChanged=!1;widgetData.thresholds.forEach(function(threshold){var value=$scope.model.Value;"string"==typeof value&&(value=Number(value.replace("%",""))),value>=threshold.value&&($scope.color=threshold.color,colorChanged=!0)}),colorChanged||($scope.color=widgetData.color)}else $scope.color=widgetData.color},findApiData=function(widgetData){var apiDataList=_.filter(repository.apiData,function(obj){return obj.prefix===widgetData.prefix});if(0===apiDataList.length)return null;if(apiDataList.length>1&&widgetData.SelectedListSetup){var contextId=widgetData.SelectedListSetup.ContextId;if(contextId){var apiDataWithContext=_.find(apiDataList,function(obj){return obj.contextId===contextId});if(apiDataWithContext)return apiDataWithContext}}return apiDataList[0]},getKpiNavState=function(){var state=null,apiData=findApiData($scope.model.WidgetData);if(apiData&&apiData.navigationState){var mainState=apiData.navigationState.split(".")[0];"document"===mainState&&"DocumentXEntity"===apiData.prefix&&(mainState="documentXEntity"),state=mainState+".list"}return state},getKpi=function(){$scope.model.WidgetData.color&&($scope.color=$scope.model.WidgetData.color);var kpi=getKpiObject();$scope.errorMessage="",repository.createSingle(repository.apiData.kpi.url,kpi).then(function(result){$scope.model.Value=result[0].Result[0].Value,setColor();var convertedValue=Number($scope.model.Value);isNaN(convertedValue)||($scope.model.Value=convertedValue)},function(error){$scope.errorMessage=error,$scope.kpiPrefixState=null,$scope.color="gray"})};$scope.getHref=function(){return $state.href($scope.kpiPrefixState,{filter:$scope.kpiPrefixParams})},$scope.model.WidgetData&&getKpi(),$scope.isNumber=function(value){return"number"==typeof value},$scope.$on($rootScope.events.newSelection,function(){$scope.model.WidgetData&&getKpi()})}angular.module("Plania").directive("plKpiWidget",["TranslationService","$window",function(translationService,$window){return{restrict:"A",require:"^plDashboardGrid",scope:{widget:"=widget",edit:"=edit",saveFunction:"=saveFunction"},link:function(scope,element,attrs,gridCtrl){function shouldShowIcon(){var ele=$(element);if(ele){var width=ele.width();scope.isIconVisible=width>=250}else scope.isIconVisible=!0}function onResize(){shouldShowIcon(),scope.$digest()}scope.$parent.attachWidget(element,attrs),scope.isIconVisible=!0,scope.removeWidget=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dashboard-widget-message","Modulen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dashboard-widget-confirm","Ja, fjern modulen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-dashboard-widget-success","Modulen ble fjernet!"),"","success"),scope.$parent.removeWidget(element,attrs)})},shouldShowIcon(),angular.element($window).on("resize",onResize),scope.$on("$destroy",function(){angular.element($window).off("resize",onResize)})},templateUrl:"app/dashboard/directives/widgets/kpiWidget.html",controller:["$scope","TranslationService","IconService","Repository","$modal","$rootScope","ListCompressionService","$state",safeController]}}])}(),function(){function safeController($scope,modal,repository,menuService,translationService){try{controller($scope,modal,repository,menuService,translationService)}catch(error){console.log(error)}}function controller($scope,modal,repository,menuService,translationService){$scope.model=$scope.widget;var webmenus={},loadWebmenus=function(){var guids=[];if($scope.model.WidgetData&&Array.isArray($scope.model.WidgetData.Links)&&$scope.model.WidgetData.Links.forEach(function(link){"WebMenu"===link.Type&&link.GuidWebMenu&&guids.push(link.GuidWebMenu)}),guids.length){var filter={FilterModel:{Condition:"and",Rules:[{Property:"Guid",Operator:"in",Value:guids}]}};repository.GetPaginated(repository.apiData.webMenu.url,0,-1,null,filter).then(function(result){result.List.forEach(function(webMenu){webmenus[webMenu.Guid]=repository.parseAndStoreWebMenu(webMenu)})})}};loadWebmenus(),$scope.editWidget=function(){modal.open({controller:"AddWidgetModalController",templateUrl:"app/dashboard/addWidgetModal.html",resolve:{widget:function(){return $scope.model}}}).result.then(function(widgetModel){$scope.saveFunction(!1).then(function(){loadWebmenus()})})};var getInternalWebMenu=function(link){return"WebMenu"===link.Type&&link.GuidWebMenu&&webmenus[link.GuidWebMenu]?webmenus[link.GuidWebMenu]:null};$scope.getHref=function(link){var webmenu=getInternalWebMenu(link);return webmenu?menuService.getHref(webmenu):link.Url},$scope.onClick=function(event,link){var webmenu=getInternalWebMenu(link);if(webmenu)return menuService.navigateFromLink(event,webmenu)},$scope.isDisabled=function(link){var webmenu=getInternalWebMenu(link);if(webmenu)return menuService.isDisabled(webmenu)},$scope.getDisabledMessage=function(link){var webmenu=getInternalWebMenu(link);return webmenu&&menuService.isDisabled(webmenu)&&webmenu.isBuildingDependent?translationService.translate("web-webDashboard-link-webmenu-disabledFromIsBuildingDependent","Velg bygg"):null}}var app=angular.module("Plania");app.directive("plLinkWidget",["TranslationService",function(translationService){return{restrict:"A",require:"^plDashboardGrid",scope:{widget:"=widget",edit:"=edit",saveFunction:"=saveFunction"},link:function(scope,element,attrs,gridCtrl){scope.$parent.attachWidget(element,attrs),scope.removeWidget=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dashboard-link-message","Linkene vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dashboard-link-confirm","Ja, fjern linkene"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-dashboard-link-success","Linkene ble fjernet!"),"","success"),scope.$parent.removeWidget(element,attrs)})}},templateUrl:"app/dashboard/directives/widgets/linkWidget.html",controller:["$scope","$modal","Repository","MenuService","TranslationService",safeController]}}]),app.directive("linkTarget",function(){return{restrict:"A",link:function(scope,element,attrs){element.href;scope.link.IsExternalLink&&element.attr("target","_blank"),element.href=""}}})}(),function(){function safeController($scope,translationService,repository,operationalMessageService,$modal,$rootScope,states,$interval,sharedDataService,$timeout){try{controller($scope,translationService,repository,operationalMessageService,$modal,$rootScope,states,$interval,sharedDataService,$timeout)}catch(error){console.log(error)}} function controller($scope,translationService,repository,operationalMessageService,$modal,$rootScope,states,$interval,sharedDataService,$timeout){function setRefreshInterval(){refreshInterval&&cancelInterval(refreshInterval),refreshInterval=$interval(function(){getItems()},1e3*$scope.model.WidgetData.RefreshInterval),$scope.$on("$destroy",function(){cancelInterval(refreshInterval)})}function cancelInterval(interval){$interval.cancel(interval),interval=void 0}function removeItemFromShadowList(item){_.remove(itemShadowList,function(o){return o===item.Guid})}$scope.model=$scope.widget,$scope.search={},$scope.showFilter=!1,$scope.listviewSearchStat=!1,$scope.hideSearch=function(){$scope.search={},$scope.listviewSearchStat=!1};var updateAccess=function(){if($scope.model.WidgetData.DataType){var prefix=repository.apiData[$scope.model.WidgetData.DataType].prefix;prefix&&($scope.hasReadAccess=$rootScope.hasReadAccess(prefix),$scope.hasEditAccess=$rootScope.hasEditAccess(prefix),$scope.hasCreateAccess=$rootScope.hasCreateAccess(prefix),$scope.hasDeleteAccess=$rootScope.hasDeleteAccess(prefix))}};updateAccess(),$scope.count=50,$scope.totalCount=0,"string"==typeof $scope.model.WidgetData&&($scope.model.WidgetData=JSON.parse($scope.model.WidgetData)),$scope.widget.WidgetData||($scope.widget.WidgetData={}),$scope.guidDrawings=sharedDataService.getDrawingGuids();var searchTimeOutPromise;$scope.searchChanged=function(){$timeout.cancel(searchTimeOutPromise),searchTimeOutPromise=$timeout(function(){getItems()},500)};var filterTypes=operationalMessageService.getCommonFilterTypes();$scope.setFilter=function(filterType){$scope.selectedFilter=_.find(filterTypes,{value:filterType}),getItems(),$scope.showFilterDropdown=!1},$scope.selectedFilter=_.find(filterTypes,{value:"active"});var refreshInterval,isFirstDataFetch=!0,itemShadowList=[],getItems=function(){if($scope.model.WidgetData.DataType){var url=repository.apiData[$scope.model.WidgetData.DataType].url,sorting={CreationDate:"desc"},columns=["Id","Description","CreationDate"],filter={PropertyFilter:[],searchString:$scope.search.searchString?$scope.search.searchString:void 0};switch($scope.model.WidgetData.DataType.toLowerCase()){case"areaxcleaningtask":columns.push("Area.Id","Area.Description","Area.Building.Id","Area.Building.Description","CleaningTask.Id","CleaningTask.CleaningType"),filter.PropertyFilter.push({Property:"GuidArea",Operator:"<>",Value:""},{Property:"CleaningTask.CleaningType",Operator:"<>",Value:-1},{Property:"CleaningTask.CleaningType",Operator:"<>",Value:0},{Property:"CleaningTask.CleaningType",Operator:"<>",Value:2},{Property:"GuidCleaner",Operator:"=",Value:""},{Property:"GuidCleaningTeam",Operator:"=",Value:""}),$scope.guidDrawings.length>0&&filter.PropertyFilter.push({Property:"Area.GuidDrawing",Operator:"in",Value:$scope.guidDrawings.join(",")});break;case"request":columns.push("Building.Id","Building.Description","Area.Building.Id","Area.Building.Description"),filter.PropertyFilter.push({Property:"GuidArea",Operator:"<>",Value:""},{Property:"Status",Operator:"=",Value:"0"}),$scope.guidDrawings.length>0&&filter.PropertyFilter.push({Property:"Area.GuidDrawing",Operator:"in",Value:$scope.guidDrawings.join(",")});break;case"operationalmessage":sorting={DueDate:"desc"},columns.push("Message","DueDate","Type","StartDate","Status","Estate.Id","Estate.Description","Building.Id","Building.Description","Building.Estate.Id","Building.Estate.Description","Equipment.Id","Equipment.Description","Equipment.Building.Id","Equipment.Building.Description","Equipment.Building.Estate.Id","Equipment.Building.Estate.Description","ContactPerson.FirstName","ContactPerson.LastName","WorkOrder.Id","WorkOrder.Description"),delete filter.PropertyFilter,filter.FilterModel=operationalMessageService.getCommonFilterModel($scope.selectedFilter.value)}repository.GetPaginated(url,0,$scope.count,sorting,filter,"",JSON.stringify(columns)).then(function(result){$scope.totalCount=result.TotalCount,"operationalMessage"===$scope.model.WidgetData.DataType&&result.List.forEach(function(message){message.startDateText=operationalMessageService.getStartDateText(message),message.dueDateText=operationalMessageService.getDueDateText(message)}),$scope.items=result.List,$scope.items.length&&(isFirstDataFetch&&(firstListItemDate=$scope.items[0].CreationDate,isFirstDataFetch=!1),$scope.items.forEach(function(item){_.contains(itemShadowList,item.Guid)||moment(item.CreationDate).isAfter(moment(firstListItemDate))&&itemShadowList.push(item.Guid)}),firstListItemDate=$scope.items[0].CreationDate)},function(error){repository.growl(error,"danger")})}};getItems(),$scope.model.WidgetData.AutoRefresh&&$scope.model.WidgetData.RefreshInterval&&setRefreshInterval(),$scope.isNewAndUnread=function(item){return _.contains(itemShadowList,item.Guid)},$scope.$watch("guidDrawings",function(newValue,oldValue){newValue!==oldValue&&getItems()},!0),$scope.$watch("model.WidgetData",function(newValue,oldValue){newValue!==oldValue&&("string"==typeof $scope.model.WidgetData&&($scope.model.WidgetData=JSON.parse($scope.model.WidgetData)),$scope.model.WidgetData.AutoRefresh&&$scope.model.WidgetData.RefreshInterval?setRefreshInterval():refreshInterval&&cancelInterval(refreshInterval),getItems())},!0),$scope.addMoreData=function(){$scope.count+=50,getItems()},$scope.$on($rootScope.events.newSelection,function(){updateAccess(),getItems()}),$scope.activateItem=function(item){removeItemFromShadowList(item),$scope.$root.$broadcast("dashboard.activateItem",item)},$scope.addNew=function(){"operationalMessage"===$scope.model.WidgetData.DataType&&$modal.open({templateUrl:"app/operationalMessage/views/operationalMessageModal.html",controller:"OperationalMessageModalController",resolve:{params:function(){return{}}}}).result.then(function(){getItems()},function(){})},$scope.editItem=function(item){removeItemFromShadowList(item),"request"===$scope.model.WidgetData.DataType?$rootScope.navigation.go("request.edit",{guid:item.Guid}):"areaXCleaningTask"===$scope.model.WidgetData.DataType?$modal.open({templateUrl:"app/area/views/EditAreaXCleaningTaskSimpleModal.html",controller:"AreaXCleaningTaskController",resolve:{modalParams:function(){return{Guid:item.Guid}}}}).result.then(function(result){repository.growl(result,"info"),getItems()}):"operationalMessage"===$scope.model.WidgetData.DataType&&$modal.open({templateUrl:"app/operationalMessage/views/operationalMessageModal.html",controller:"OperationalMessageModalController",resolve:{params:function(){return{guid:item.Guid}}}}).result.then(function(result){getItems()})},$scope.editWidget=function(){$modal.open({controller:"AddWidgetModalController",templateUrl:"app/dashboard/addWidgetModal.html",resolve:{widget:function(){return $scope.model}}}).result.then(function(widgetModel){$scope.saveFunction(!1)},function(){})},$scope.getLowestEntityCaption=operationalMessageService.getLowestEntityCaption,$scope.getEntityIcon=operationalMessageService.getEntityIcon;var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.menuOptions=function(message){var options=[];return $scope.hasReadAccess&&options.push({html:' '+translationService.translate("web-operationalMessage-menuOption-view","Åpne")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.editItem(message)}}),message.GuidEstate&&options.push(getMenuLink($rootScope.navigation.href("estate.edit",{guid:message.GuidEstate}),translationService.translate("web-operationalMessage-menuOption-viewEstate","Gå til eiendom"))),message.GuidBuilding&&options.push(getMenuLink($rootScope.navigation.href("building.edit",{guid:message.GuidBuilding}),translationService.translate("web-operationalMessage-menuOption-viewBuilding","Gå til bygg"))),message.GuidEquipment&&options.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:message.GuidEquipment}),translationService.translate("web-operationalMessage-menuOption-viewEquipment","Gå til anlegg"))),message.GuidWorkOrder?options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:message.GuidWorkOrder}),translationService.translate("web-operationalMessage-menuOption-viewWorkOrder","Gå til arbeidsodre"))):$rootScope.hasCreateAccess("WorkOrder")&&options.push({html:' '+translationService.translate("web-operationalMessage-menuOption-createWorkOrder","Opprett arbeidsordre")+"",click:function(){operationalMessageService.createWorkOrder(message)}}),options}}angular.module("Plania").directive("plListWidget",["TranslationService",function(translationService){return{restrict:"A",require:"^plDashboardGrid",scope:{widget:"=widget",edit:"=edit",saveFunction:"=saveFunction",selectedDrawings:"=selectedDrawings"},link:function(scope,element,attrs,gridCtrl){scope.$parent.attachWidget(element,attrs),scope.removeWidget=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dashboard-list-message","Listen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dashboard-list-confirm","Ja, fjern listen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-dashboard-list-success","Listen ble fjernet!"),"","success"),scope.$parent.removeWidget(element,attrs)})}},templateUrl:"app/dashboard/directives/widgets/listWidget.html",controller:["$scope","TranslationService","Repository","OperationalMessageService","$modal","$rootScope","states","$interval","DashboardSharedDataService","$timeout",safeController]}}])}(),function(){function safeController($scope,modal){try{controller($scope,modal)}catch(error){console.log(error)}}function controller($scope,modal){$scope.model=$scope.widget,$scope.sharedController={},$scope.refreshWidget=function(){$scope.sharedController.refresh()},$scope.toggleReportFilters=function(){$scope.sharedController.toggleFilters()},$scope.toggleZoomMode=function(){$scope.sharedController.toggleZoomMode()},$scope.editWidget=function(){modal.open({controller:"AddWidgetModalController",templateUrl:"app/dashboard/addWidgetModal.html",resolve:{widget:function(){return $scope.model}}}).result.then(function(widgetModel){$scope.saveFunction(!1)},function(){})}}angular.module("Plania").directive("plReportWidget",["TranslationService",function(translationService){return{restrict:"A",require:"^plDashboardGrid",scope:{widget:"=widget",edit:"=edit",saveFunction:"=saveFunction"},link:function(scope,element,attrs,gridCtrl){scope.$parent.attachWidget(element,attrs),scope.removeWidget=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dashboard-report-message","Rapporten vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dashboard-report-confirm","Ja, fjern rapporten"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-dashboard-report-success","Rapporten ble fjernet!"),"","success"),scope.$parent.removeWidget(element,attrs)})}},templateUrl:"app/dashboard/directives/widgets/reportWidget.html",controller:["$scope","$modal",safeController]}}])}(),function(){function safeController($scope,repository,ngTableParams,modal,$rootScope,states,$interval,$localStorage,$modal,listService,translationService){try{controller($scope,repository,ngTableParams,modal,$rootScope,states,$interval,$localStorage,$modal,listService,translationService)}catch(error){console.log(error)}}function controller($scope,repository,ngTableParams,modal,$rootScope,states,$interval,$localStorage,$modal,listService,translationService){function cancelInterval(interval){$interval.cancel(interval),interval=void 0}$scope.model=$scope.widget,$scope.search={},$scope.canCreateNew=!1,$scope.filterConfirmationIsCollapsed=!0,$scope.selectedListSetup=null;var refreshInterval,onSelectionEventListener,dataReceivedFromBroadcast={},createNavState="";$scope.model.WidgetData||($scope.model.WidgetData={}),"string"==typeof $scope.model.WidgetData&&($scope.model.WidgetData=JSON.parse($scope.model.WidgetData)),$scope.editWidget=function(){modal.open({controller:"AddWidgetModalController",templateUrl:"app/dashboard/addWidgetModal.html",resolve:{widget:function(){return $scope.model}}}).result.then(function(widgetModel){$scope.saveFunction(!1).then(function(){updateAutoRefresh(),updateOnSelectionEvent(),setCreateNavState(),$scope.widgetTable.filter().searchString="",getTable()})},function(){})};var getEntityName=function(){var entityName=$scope.selectedListSetup?$scope.selectedListSetup.EntityName:"";return entityName||(entityName=$scope.selectedListSetup?$scope.selectedListSetup.EntityType:""),entityName||(entityName="Undefined"),entityName},setCreateNavState=function(){try{if(!(createNavState=$scope.model.WidgetData.NavigationState))return void($scope.canCreateNew=!1);var entityName=getEntityName();if(createNavState=createNavState.replace(".edit",".create"),!createNavState.includes(".create"))return void($scope.canCreateNew=!1);$scope.canCreateNew=!!_.find(states.list,function(o){return o.name===createNavState})&&$rootScope.hasCreateAccess(entityName)}catch(ex){$scope.canCreateNew=!1}};setCreateNavState(),$scope.markRow=function(item){return item.HasUnreadComments};var groupByFunction=function(obj){return listService.getGroupNameFromListSetup($scope.selectedListSetup,obj)},getTable=function(){if($scope.model.WidgetData.SelectedListSetup){var entityName=$scope.model.WidgetData.SelectedListSetup.EntityName,entityType=$scope.model.WidgetData.SelectedListSetup.EntityType,contextId=$scope.model.WidgetData.contextId||"List-"+entityType;listService.getWebListViews($scope.model.WidgetData.SelectedListSetup,entityType,!1,contextId).then(function(result){$scope.selectedListSetup=_.find(result.listOptions,function(item){return item.Guid===$scope.model.WidgetData.SelectedListSetup.Guid}),setCreateNavState();var listParams={};if(entityName!==repository.apiData.userGroup.prefix&&entityType!==repository.apiData.userGroup.prefix||(listParams.UserGroup=1),entityName===repository.apiData.workOrder.prefix||entityType===repository.apiData.workOrder.prefix){var filter=_.filter(listParams.PropertyFilter,function(row){return"stage"===row.Property.toLowerCase()});filter[0]?listParams.ActivityStatus=filter[0].Value:listParams.ActivityStatus="Active"}if(entityName!==repository.apiData.request.prefix&&entityType!==repository.apiData.request.prefix||$rootScope.userInfo.isSystemAdministrator||(listParams.PropertyFilter=_.union(listParams.PropertyFilter,[{Property:"IsTemplate",Operator:"=",Value:"0"}])),entityName===repository.apiData.project.prefix||entityType===repository.apiData.project.prefix){var isTemplate=$scope.model.WidgetData.NavigationState.indexOf("projectTemplate")>-1;listParams.PropertyFilter=_.union(listParams.PropertyFilter,[{Property:"IsTemplate",Operator:"=",Value:isTemplate?"1":"0"}])}entityName!==repository.apiData.workOrderXResourceGroup.prefix&&entityType!==repository.apiData.workOrderXResourceGroup.prefix||(listParams.PropertyFilter=_.union(listParams.PropertyFilter,[{Property:"GuidPerson",Operator:"=",Value:repository.authService.getUserData().guidPerson}])),entityName!==repository.apiData.controlListItemAnswer.prefix&&entityType!==repository.apiData.controlListItemAnswer.prefix||(listParams.FilterAnswerList=!0);var sorting=$scope.selectedListSetup.Sorting;"string"==typeof sorting&&(sorting=JSON.parse(sorting)),$scope.widgetTable=new ngTableParams({page:1,count:$scope.model.WidgetData.defaultPaginationCount?$scope.model.WidgetData.defaultPaginationCount:10,sorting:sorting,filter:listParams},{total:0,counts:[10,25,50,100],groupBy:$scope.selectedListSetup.GroupBy?groupByFunction:"",paginationMaxBlocks:6,getData:function($defer,params){var filter=params.$params.filter,columns=[];filter.PropertyFilter||(filter.PropertyFilter=[]),$scope.selectedListSetup.VisibleColumns=_.filter($scope.selectedListSetup.Columns,function(c){return!c.Filter||!c.Filter.some(function(f){return f.Hidden})}),$scope.selectedListSetup.Columns.forEach(function(col){col.Filter&&("string"==typeof col.Filter&&(col.Filter=JSON.parse(col.Filter)),filter.PropertyFilter=_.union(filter.PropertyFilter,col.Filter)),columns.push(col.Property)});var sorting=params.sorting();if($scope.selectedListSetup.GroupBy){var groupSort={};groupSort[$scope.selectedListSetup.GroupBy]="asc";for(var attrname in sorting)groupSort[attrname]=sorting[attrname];sorting=groupSort,$scope.widgetTable.$params.sorting=groupSort}$scope.hideTable||repository.GetPaginated($scope.widget.WidgetData.ServiceUrl,params.page()-1,params.count(),sorting,filter,"",JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.showError(error)})}})})}};getTable(),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)};var updateAutoRefresh=function(){$scope.model.WidgetData.AutoRefresh&&$scope.model.WidgetData.RefreshInterval?(refreshInterval&&cancelInterval(refreshInterval),refreshInterval=$interval(function(){$scope.widgetTable&&$scope.widgetTable.reload()},1e3*$scope.model.WidgetData.RefreshInterval),$scope.$on("$destroy",function(){cancelInterval(refreshInterval)})):refreshInterval&&cancelInterval(refreshInterval)};updateAutoRefresh(),$scope.navigate=function(item){var itemPrefix=item.Prefix;if("ControlListXEntity"===itemPrefix||"ControlListItemAnswer"===itemPrefix){var params={restrictEdit:!0};return params.workOrderCaption="ControlListXEntity"===itemPrefix?item.WorkOrder.Caption:item.ControlListXEntity.WorkOrder.Caption,params.controlList="ControlListXEntity"===itemPrefix?item.ControlList:item.ControlListXEntity.ControlList,params.controlListXEntity="ControlListXEntity"===itemPrefix?item:{Guid:item.GuidControlListXEntity},void $modal.open({templateUrl:"app/controlList/views/controlListCompletionModal.html",size:"xl",controller:"ControlListCompletionModalController",resolve:{params:function(){return params}}})}return"BuildingXPerson"===itemPrefix?void $modal.open({templateUrl:"app/buildingPerson/views/editBuildingPerson.html",controller:"BuildingPersonController",resolve:{params:function(){return{guid:item.Guid,modalParam:{isUpdate:!0}}}}}):"ChangeSet"===itemPrefix?void $modal.open({templateUrl:"app/changeSet/views/changeSetModal.html",controller:"ChangeSetModalController",resolve:{params:function(){return{guid:item.Guid}}}}):void $rootScope.navigation.go($scope.model.WidgetData.NavigationState,{guid:item.Guid},{reload:!0})},$scope.selectedList=[],$scope.addSelected=function(guid){if(_.contains($scope.selectedList,guid))for(var i=0;i<$scope.selectedList.length;i++){var p=$scope.selectedList[i];if(p===guid){$scope.selectedList.splice(i,1);break}}else $scope.selectedList.push(guid)},$scope.isSelected=function(guid){return _.contains($scope.selectedList,guid)},$scope.$watch("selectedList",function(newValue,oldValue){newValue!==oldValue&&($scope.selectedList.length>0?$scope.filterConfirmationIsCollapsed=!1:(!1===$scope.filterConfirmationIsCollapsed&&$scope.broadcastNewFilter(),$scope.filterConfirmationIsCollapsed=!0))},!0),$scope.broadcastNewFilter=function(){var objects=[];$scope.selectedList.forEach(function(guid){objects.push(_.find($scope.widgetTable.data,function(o){return o.Guid===guid}))});var entityName=getEntityName(),newFilterData={entityName:entityName,objects:objects};$scope.$root.$broadcast("dashboard.newFilter",newFilterData)};var onNewFilter=function(evt,data){dataReceivedFromBroadcast=data,0===data.objects.length?$scope.hideTable=!0:$scope.hideTable=!1;var filter=$scope.widgetTable.filter();filter||(filter={}),filter.PropertyFilter||(filter.PropertyFilter=[]);var previousFilterIndex=_.findIndex(filter.PropertyFilter,function(o){return o.Property==="Guid"+data.entityName});previousFilterIndex>-1&&filter.PropertyFilter.splice(previousFilterIndex,1),data.objects.length>0&&filter.PropertyFilter.push({Property:"Guid"+data.entityName,Operator:"in",Value:_.map(data.objects,"Guid").join(",")})},updateOnSelectionEvent=function(){onSelectionEventListener&&onSelectionEventListener(),$scope.model.WidgetData.FilterOnSelectionEvent?($scope.hideTable=!0,onSelectionEventListener=$scope.$on("dashboard.newFilter",onNewFilter)):($scope.hideTable=!1,onSelectionEventListener=void 0)};updateOnSelectionEvent(),$scope.addNew=function(){$rootScope.navigation.go(createNavState,{reload:!0})},$scope.$on($rootScope.events.newSelection,function(){$scope.widgetTable&&$scope.widgetTable.reload(),setCreateNavState()})}angular.module("Plania").directive("plTableWidget",["TranslationService",function(translationService){return{restrict:"A",require:"^plDashboardGrid",scope:{widget:"=widget",edit:"=edit",saveFunction:"=saveFunction"},link:function(scope,element,attrs,gridCtrl){scope.$parent.attachWidget(element,attrs),scope.removeWidget=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dashboard-table-message","Tabellen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dashboard-table-confirm","Ja, fjern tabellen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-dashboard-table-success","Tabellen ble fjernet!"),"","success"),scope.$parent.removeWidget(element,attrs)})}},controller:["$scope","Repository","NgTableParams","$modal","$rootScope","states","$interval","$localStorage","$modal","ListService","TranslationService",safeController],templateUrl:"app/dashboard/directives/widgets/tableWidget.html"}}])}(),function(){function safeController($scope,modal){try{controller($scope,modal)}catch(error){console.log(error)}}function controller($scope,modal){if($scope.model=$scope.widget,$scope.url="","string"==typeof $scope.model.WidgetData&&($scope.model.WidgetData=JSON.parse($scope.model.WidgetData)),$scope.editWidget=function(){modal.open({controller:"AddWidgetModalController",templateUrl:"app/dashboard/addWidgetModal.html",resolve:{widget:function(){return $scope.model}}}).result.then(function(widgetModel){$scope.saveFunction(!1).then(function(){setUrl()})},function(){})},$scope.model.WidgetData){var setUrl=function(){var url="";if($scope.model.WidgetData&&$scope.model.WidgetData.locationId){switch(url="https://www.yr.no/",$scope.model.WidgetData.locale){case"nn":url+="nn/innhald/";break;case"sme":url+="sme/sisdoallu/";break;case"en":url+="en/content/";break;default:url+="nb/innhold/"}switch(url+=$scope.model.WidgetData.locationId+"/",$scope.model.WidgetData.type){case"meteogram":url+="meteogram.svg";break;case"table":url+="table.html";break;default:url+="card.html"}}$scope.url=url};setUrl()}}angular.module("Plania").directive("plWeatherForecastWidget",["TranslationService",function(translationService){return{restrict:"A",require:"^plDashboardGrid",scope:{widget:"=widget",edit:"=edit",saveFunction:"=saveFunction"},link:function(scope,element,attrs,gridCtrl){scope.$parent.attachWidget(element,attrs),scope.removeWidget=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dashboard-table-message","Tabellen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dashboard-table-confirm","Ja, fjern tabellen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-dashboard-table-success","Tabellen ble fjernet!"),"","success"),scope.$parent.removeWidget(element,attrs)})}},templateUrl:"app/dashboard/directives/widgets/weatherForecastWidget.html",controller:["$scope","$modal",safeController]}}])}(),function(){function controller($scope,$modalInstance,params,repository,translationService){var guidBimFile=params.guidBimFile,guidDataImport=params.guidDataImport,ifcType=params.ifcType,existingColumns=params.existingColumns;$scope.enableConstantValue=params.enableConstantValue,$scope.inputMode="column",$scope.model=[],$scope.constantValue="",repository.getWithUrlParameter("dataimport/bim/"+guidBimFile+"/properties/"+guidDataImport,"ifcType="+ifcType).then(function(result){_.forEach(result,function(col){$scope.model.push(col)})}),$scope.selectedColumns=[],$scope.ok=function(){"column"===$scope.inputMode?$modalInstance.close({type:"column",value:$scope.selectedColumns}):"constant"===$scope.inputMode&&$modalInstance.close({type:"constant",value:$scope.constantValue})};var match=function(textToSearch,searchValue){return!searchValue||!!textToSearch&&textToSearch.toLowerCase().includes(searchValue.toLowerCase())},searchMatch=function(col,searchString){return match(col.Title,searchString)};$scope.columnFilter=function(col){return!!searchMatch(col,$scope.searchString)&&col},$scope.selectColumn=function(column,event){if(event.stopPropagation(),column.Children.length>0)column.isExpanded=!column.isExpanded;else if(_.contains($scope.selectedColumns,column))for(var i=0;i<$scope.selectedColumns.length;i++){var p=$scope.selectedColumns[i];if(p===column)return void $scope.selectedColumns.splice(i,1)}else $scope.selectedColumns.push(column)},$scope.alreadyMapped=function(column){return!!_.contains(existingColumns,column.Title)||!!_.contains(existingColumns,column.Children.Title)},$scope.isColumnSelected=function(column){return _.contains($scope.selectedColumns,column)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("AddImportFieldMappingModalController",["$scope","$modalInstance","params","Repository","TranslationService",controller])}(),function(){function controller($scope,translationService,repository,registeredFieldService,$q,$stateParams,$rootScope){$scope.model=[{id:"excel",enabled:$rootScope.hasModule("DataImport")||$rootScope.hasModule("DataAcquisition"),title:translationService.translate("web-dataImport-create-excel-title","EXCEL"),description:translationService.translate("web-dataImport-create-excel-description","Importer data fra Excel ark."),link:function(){$scope.navigation.transitionTo("dataImport.edit")},color:"green",disabledReason:translationService.translate("web-dataImport-create-excel-disabledReason","Forutsetter DataImport lisens.")},{id:"bim",enabled:$rootScope.hasModule("IFCBimsyncHosting"),title:translationService.translate("web-dataImport-create-bim-title","BIM"),description:translationService.translate("web-dataImport-create-bim-description","Importer data fra Bim model."),link:function(){$scope.navigation.transitionTo("dataImport.bim")},color:"blue",disabledReason:translationService.translate("web-dataImport-create-bim-disabledReason","Forutsetter IFCBimsyncHosting lisens.")}]}angular.module("Plania").controller("CreateDataImportController",["$scope","TranslationService","Repository","RegisteredFieldService","$q","$stateParams","$rootScope",controller])}(),function(){function controller($scope,translationService,repository,registeredFieldService,$q,$stateParams,$modal,$location,signalR,$timeout,config,$window){function getNumberOfDataOwnersInLicense(){repository.getSingleWithNoParameter(repository.apiData.planiaSystem.url).then(function(result){result&&($scope.currentNumberOfDataOwners=result.CurrentNumberOfDataOwners)},function(error){repository.showError(error)})}function getModel(){repository.getSingle(repository.apiData.dataImportBim.url,$scope.model.Guid).then(function(result){$scope.model=result.Data,$scope.getBuildings(),$scope.model.InputConfig.BimConfig.GuidBuilding&&$scope.getBimModels(),$scope.model.InputConfig.BimConfig.GuidBimFile&&($scope.getIfcTypes(),$scope.getPreview()),$scope.model.Summary&&($scope.runSummary=JSON.parse($scope.model.Summary)),$scope.model.ValidationSummary&&($scope.validationSummary=JSON.parse($scope.model.ValidationSummary));var hash=$location.hash();hash?setCurrentStep(_.find($scope.steps,function(step){return step.name===hash})):"Completed"===$scope.model.Status?setCurrentStep(_.find($scope.steps,function(step){return"startImport"===step.name})):$scope.model.FieldMapping&&$scope.model.FieldMapping.length>0?setCurrentStep(_.find($scope.steps,function(step){return"validateImport"===step.name})):$scope.model.GuidBinaryData?setCurrentStep(_.find($scope.steps,function(step){return"editFieldMappings"===step.name})):$scope.model.EntityType&&setCurrentStep(_.find($scope.steps,function(step){return"chooseSource"===step.name}))},function(error){repository.growl(error,"danger")})}function handleChooseObjectStep(){var deferred=$q.defer();return $scope.model.Guid?repository.updateSingle(repository.apiData.dataImportBim.url,$scope.model).then(function(response){$scope.model=response,deferred.resolve(!0)},function(error){repository.growl(error,"danger"),deferred.reject(error)}):(delete $scope.model.Guid,repository.createSingle(repository.apiData.dataImportBim.url,$scope.model).then(function(response){$scope.model=response,$location.path($location.path()+response.Guid),$location.replace(),deferred.resolve(!0)},function(error){repository.growl(error,"danger"),deferred.reject(error)})),deferred.promise}function handleChooseSourceStep(){var deferred=$q.defer();return repository.updateSingle(repository.apiData.dataImportBim.url,$scope.model).then(function(response){$scope.model=response,repository.runAction("dataImport/bim/"+$scope.model.Guid+"/GetInitialFieldMappings").then(function(result){$scope.model.FieldMapping=result.FieldMapping,deferred.resolve(!0)},function(error){repository.growl(error,"danger"),deferred.reject(error)})},function(error){repository.growl(error,"danger"),deferred.reject(error)}),deferred.promise}function onChooseSourceAppearing(){$scope.model.GuidBinaryData&&!$scope.tempTable&&$scope.getPreview()}function onFieldMappingsAppearing(){$scope.tempTable||$scope.getPreview()}function updateDataImport(){var deferred=$q.defer();return repository.updateSingle(repository.apiData.dataImportBim.url,$scope.model).then(function(response){$scope.model=response,deferred.resolve(!0)},function(error){repository.growl(error,"danger"),deferred.reject(error)}),deferred.promise}function getRelationType(mapping){return mapping.PlaniaField?mapping.PlaniaField.startsWith("NonsReference.")?"Owned":mapping.PlaniaField.includes(".")?"Relation":"Direct":"Direct"}function getProcessingSignalRMethodName(){return"processingDataImportRun_"+$scope.model.Guid}function getValidatingSignalRMethodName(){return"validatingDataImportRun_"+$scope.model.Guid}function initializeImportJobValidatingSignalR(methodName){signalR.on(methodName,function(progress){if(!0===progress.Finished)return void($scope.importJobValidating=!1);$scope.importJobValidating=!0,$scope.importJobValidationProgress=progress,$scope.validationSummary.RowSummaries.push(progress.RowSummary),$scope.validationSummary.RunStatistics=progress.RunStatistics }),$scope.$on("$destroy",function(){signalR.off(methodName)})}function initializeImportJobProcessingSignalR(methodName){signalR.on(methodName,function(progress){if(!0===progress.Finished)return void $timeout(function(){$scope.importJobProcessing=!1,getModel()},250);$scope.importJobProcessing=!0,$scope.importJobProgress=progress,$scope.runSummary.RowSummaries.push(progress.RowSummary),$scope.runSummary.RunStatistics=progress.RunStatistics}),$scope.$on("$destroy",function(){signalR.off(methodName)})}$scope.isEdit=!!$stateParams.guid,$scope.entityTypes=[{key:repository.apiData.estate.prefix,value:translationService.translate("web-enum-prefix-estate")},{key:repository.apiData.building.prefix,value:translationService.translate("web-enum-prefix-building")},{key:repository.apiData.equipment.prefix,value:translationService.translate("web-enum-prefix-equipment")},{key:repository.apiData.area.prefix,value:translationService.translate("web-enum-prefix-area")},{key:repository.apiData.component.prefix,value:translationService.translate("web-enum-prefix-component")},{key:repository.apiData.supplier.prefix,value:translationService.translate("web-enum-prefix-supplier")},{key:repository.apiData.person.prefix,value:translationService.translate("web-enum-prefix-person")},{key:repository.apiData.customer.prefix,value:translationService.translate("web-enum-prefix-customer")}],$scope.steps=[{stepIndex:1,name:"chooseObject",hidden:!1,title:translationService.translate("web-dataImport-wizard-stepTitle-chooseObject","Velg objekt"),onNextStepClicked:handleChooseObjectStep},{stepIndex:2,name:"chooseSource",hidden:!1,title:translationService.translate("web-dataImport-wizard-stepTitle-chooseSource","Velg kilde"),onNextStepClicked:handleChooseSourceStep,onStepAppearing:onChooseSourceAppearing},{stepIndex:3,name:"editFieldMappings",hidden:!1,title:translationService.translate("web-dataImport-wizard-stepTitle-editFieldMappings","Rediger knytninger"),onNextStepClicked:updateDataImport,onStepAppearing:onFieldMappingsAppearing},{stepIndex:4,name:"validateImport",hidden:!1,title:translationService.translate("web-dataImport-wizard-stepTitle-validateImport","Validering"),onNextStepClicked:updateDataImport},{stepIndex:5,name:"startImport",hidden:!1,title:translationService.translate("web-dataImport-wizard-stepTitle-startImport","Start import")}],$scope.isEdit||($scope.currentStep=$scope.steps[0],$scope.completedStepIndex=$scope.currentStep.stepIndex);var setCurrentStep=function(step){$location.hash(step.name).replace(),$scope.currentStep=step,(void 0===$scope.completedStepIndex||$scope.completedStepIndex<$scope.currentStep.stepIndex)&&($scope.completedStepIndex=$scope.currentStep.stepIndex),void 0!==$scope.currentStep.onStepAppearing&&$scope.currentStep.onStepAppearing()},onChangeStep=function(step){if(void 0===$scope.currentStep.onNextStepClicked)return void setCurrentStep(step);$scope.currentStep.onNextStepClicked().then(function(valid){valid&&setCurrentStep(step)})};$scope.onStepClick=function(step){step.stepIndex>$scope.completedStepIndex||setCurrentStep(step)},$scope.handlePreviousStep=function(){var step=_.find($scope.steps,function(step){return step.stepIndex===$scope.currentStep.stepIndex-1});step&&setCurrentStep(step)},$scope.handleNextStep=function(){var step=_.find($scope.steps,function(step){return step.stepIndex===$scope.currentStep.stepIndex+1});step&&onChangeStep(step)},$scope.model={Guid:$stateParams.guid,FieldMapping:[],InputConfig:{Type:"Bim",BimConfig:{Filter:[]}}},$scope.showSelectFile=!0,$stateParams.guid?getModel():$stateParams.guidEntityToCopy&&repository.getSingle(repository.apiData.dataImportBim.url,$stateParams.guidEntityToCopy).then(function(result){delete result.Data.Guid,delete result.Data.GuidBinaryData,$scope.model=result.Data,$scope.model.Id+=" - kopi"}),$scope.currentNumberOfDataOwners=0,getNumberOfDataOwnersInLicense(),registeredFieldService.getRegisteredField(repository.commonService.prefix.DataImport).then(function(result){$scope.fieldRules=result}),$scope.getBuildings=function(){var filter={PropertyFilter:[{Property:"GuidBuilding",Operator:"<>",Value:null}]},columns=["Building.Id","Building.Description"];repository.GetPaginated(repository.apiData.buildingXBimFile.url,0,-1,{"Building.Id":"asc"},filter,null,JSON.stringify(columns)).then(function(result){$scope.buildingOptions=_.map(_.uniq(result.List,!1,function(a){return a.Building.Guid}),function(ifc){return{Guid:ifc.Building.Guid,Caption:ifc.Building.Caption}})})},$scope.getIfcTypes=function(){var guidBimFile=$scope.model.InputConfig.BimConfig.GuidBimFile;guidBimFile&&repository.getSingleWithNoParameter("dataImport/bim/"+guidBimFile+"/ifcTypes").then(function(result){$scope.bimIfcTypes=result},function(error){repository.growl(error,"danger")})},$scope.getBimModels=function(){var guidBuilding=$scope.model.InputConfig.BimConfig.GuidBuilding;guidBuilding&&repository.getWithUrlParameter("dataImport/bim/models","guidBuilding="+guidBuilding).then(function(result){$scope.bimModelOptions=result?result.Models:[]},function(error){repository.growl(error,"danger")})},$scope.getPreview=function(){var guidBimFile=$scope.model.InputConfig.BimConfig.GuidBimFile,ifcType=$scope.model.InputConfig.BimConfig.IfcType,guidDataImport=$scope.model.Guid;repository.getWithUrlParameter("dataImport/bim/"+guidBimFile+"/products","guidDataImport="+guidDataImport+"&ifcType="+ifcType+"&limitTo=10").then(function(result){$scope.tempTable=result.Table,$scope.totalCount=result.TotalCount},function(error){$scope.tempTable=[],repository.growl(error,"danger")})},$scope.addFilter=function(){var guidBimFile=$scope.model.InputConfig.BimConfig.GuidBimFile,ifcType=$scope.model.InputConfig.BimConfig.IfcType;$modal.open({templateUrl:"app/dataImport/views/addImportFieldMappingModal.html",controller:"AddImportFieldMappingModalController",resolve:{params:function(){return{guidBimFile:guidBimFile,guidDataImport:$scope.model.Guid,ifcType:ifcType,enableConstantValue:!1}}}}).result.then(function(modalResult){if("column"===modalResult.type){var selectedColumn=modalResult.value[0],filter={Operation:"=",Value:"",Type:""};filter.Field=selectedColumn.PropertyName,filter.Title=selectedColumn.Title,filter.Type=selectedColumn.Type,$scope.model.InputConfig.BimConfig.Filter.push(filter)}})},$scope.removeFilter=function(filterElement){var index=$scope.model.InputConfig.BimConfig.Filter.indexOf(filterElement);index>-1&&$scope.model.InputConfig.BimConfig.Filter.splice(index,1)},$scope.updateFilter=function(){updateDataImport().then(function(){$scope.getPreview()})},$scope.setMappingColumn=function(mapping){var existingColumns=[];$scope.model.FieldMapping.forEach(function(map){map.PlaniaField&&existingColumns.push({Property:map.PlaniaField})}),$modal.open({templateUrl:"app/common/views/addNewListColumnModal.html",controller:"AddNewListColumnController",resolve:{params:function(){return{prefix:$scope.model.EntityType,existingColumns:existingColumns,showAdvancedMode:!0}}}}).result.then(function(selectedColumns){if(selectedColumns&&selectedColumns.length){if(selectedColumns[0].Property.split(".").length>=3)return;mapping.PlaniaField=selectedColumns[0].Property,mapping.PlaniaFieldTitle=selectedColumns[0].Title}})},$scope.setImportMappingColumn=function(mapping){$scope.addImportFields(mapping)},$scope.resetImportMappingColumn=function(mapping){mapping.ImportField=null},$scope.resetMappingColumn=function(mapping){if(mapping){var mappingToChange=_.find($scope.model.FieldMapping,function(fieldMapping){return fieldMapping.ImportField===mapping.ImportField});mappingToChange.PlaniaField===$scope.model.PrimaryField&&($scope.model.PrimaryField=null),mappingToChange.PlaniaField=null,mappingToChange.PlaniaFieldTitle=null}},$scope.setPrimaryField=function(mapping){!mapping.PlaniaField||mapping.PlaniaField.split(".").length>=2||($scope.model.PrimaryField=mapping.PlaniaField)},$scope.addMapping=function(){$scope.model.FieldMapping.push({ImportField:"",PlaniaField:"",PlaniaFieldTile:""})},$scope.removeMapping=function(mapping){var index=$scope.model.FieldMapping.indexOf(mapping);$scope.model.FieldMapping.splice(index,1)},$scope.addImportFields=function(mapping){var guidBimFile=$scope.model.InputConfig.BimConfig.GuidBimFile,ifcType=$scope.model.InputConfig.BimConfig.IfcType;$modal.open({templateUrl:"app/dataImport/views/addImportFieldMappingModal.html",controller:"AddImportFieldMappingModalController",resolve:{params:function(){return{guidBimFile:guidBimFile,guidDataImport:$scope.model.Guid,ifcType:ifcType,enableConstantValue:!0,existingColumns:_.map($scope.model.FieldMapping,"ImportField")}}}}).result.then(function(modalResult){if("column"===modalResult.type){var selectedColumns=modalResult.value;if(mapping)return void(mapping.ImportField=selectedColumns[0].Title);_.forEach(selectedColumns,function(col){$scope.model.FieldMapping.push({ImportField:col.Title,PlaniaField:"",PlaniaFieldTitle:""})})}if("constant"===modalResult.type){var fieldMapping={ImportField:"[Constant]",IsConstant:!0,ConstantValue:modalResult.value,PlaniaField:"",PlaniaFieldTitle:""};mapping?(mapping.ImportField=fieldMapping.ImportField,mapping.IsConstant=fieldMapping.IsConstant,mapping.ConstantValue=fieldMapping.ConstantValue):$scope.model.FieldMapping.push(fieldMapping)}})},$scope.mappingPrimaryFieldTooltipText={isPrimaryField:translationService.translate("web-dataImport-fieldMapping-isPrimaryField-popover","Denne kolonnen er valgt som hovedkolonne. Denne blir da brukt for å sjekke om et import objekt eksisterer i Plania."),isRelationField:translationService.translate("web-dataImport-fieldMapping-isRelationField-popover","Denne kolonnen er en knytningskolonne. Denne blir brukt for å knytte et import objekt til et annet relatert objekt som allerede eksisterer i Plania."),isNotSelected:translationService.translate("web-dataImport-fieldMapping-isNotSelected-popover","Klikk for å velge denne kolonnen som hovedkolonne. Denne blir da brukt for å sjekke om et import objekt eksisterer i Plania."),isOwnedField:translationService.translate("web-dataImport-fieldMapping-isOwnedField-popover","Denne kolonnen kan opprettes eller oppdateres likt som egenskaper på import objektet.")},$scope.getTooltipText=function(mapping,model){var relationType=getRelationType(mapping);return model.PrimaryField===mapping.PlaniaField?$scope.mappingPrimaryFieldTooltipText.isPrimaryField:"Relation"===relationType?$scope.mappingPrimaryFieldTooltipText.isRelationField:"Owned"===relationType?$scope.mappingPrimaryFieldTooltipText.isOwnedField:$scope.mappingPrimaryFieldTooltipText.isNotSelected},$scope.getClasses=function(mapping,model){var relationType=getRelationType(mapping),classes={"fas fa-star c-amber":model.PrimaryField===mapping.PlaniaField,"fas fa-star c-bluegray":"Relation"===relationType,"far fa-star":model.PrimaryField!==mapping.PlaniaField&&("Direct"===relationType||"Owned"===relationType)},classString="";for(var key in classes)classes[key]&&(classString+=key+" ");return classString.trim()},initializeImportJobValidatingSignalR(getValidatingSignalRMethodName()),$scope.runValidation=function(){updateDataImport().then(function(){$scope.validationSummary={RowSummaries:[]},repository.runAction(repository.apiData.dataImportBim.url+$scope.model.Guid+"/RunValidation").then(function(result){},function(error){repository.growl(error,"danger")})})},initializeImportJobProcessingSignalR(getProcessingSignalRMethodName()),$scope.startImport=function(){$scope.runSummary={RowSummaries:[]},repository.runAction(repository.apiData.dataImportBim.url+$scope.model.Guid+"/RunImport").then(function(result){},function(error){repository.growl(error,"danger")})},$scope.createNewImport=function(){$scope.navigation.go("dataImport.bim",{guidEntityToCopy:$scope.model.Guid},{inherit:!1})},$scope.deleteImport=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-dataImport-wizard-startImport-deleteMessage","Dataimport vil bli fjernet"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-button-confirm","Ja"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.dataImportBim.url,$scope.model.Guid).then(function(){repository.growl("Dataimport slettet","success"),$scope.goBack("dataImport.list",{menuGuid:$scope.navigation.params.menuGuid}),swal.close()})})},$scope.summaryStatusFilter="",$scope.validationSummaryStatusFilter="",$scope.rowStatuses=[{key:"Created",value:"Opprettet"},{key:"Updated",value:"Oppdatert"},{key:"Error",value:"Feilet"}],$scope.summaryFilter=function(status){return function(row){return!status||row.RowStatus===status}}}angular.module("Plania").controller("DataBimImportController",["$scope","TranslationService","Repository","RegisteredFieldService","$q","$stateParams","$modal","$location","SignalR","$timeout","config","$window",controller])}(),function(){function controller($scope,translationService,repository,registeredFieldService,$q,$stateParams,$modal,$location,signalR,$timeout,config,$window){function getNumberOfDataOwnersInLicense(){repository.getSingleWithNoParameter(repository.apiData.planiaSystem.url).then(function(result){result&&($scope.currentNumberOfDataOwners=result.CurrentNumberOfDataOwners)},function(error){repository.showError(error)})}function getModel(){repository.getSingle(repository.apiData.dataImport.url,$scope.model.Guid).then(function(result){$scope.model=result.Data,$scope.model.GuidBinaryData&&($scope.showSelectFile=!1,$scope.getSheetOptions()),$scope.model.Summary&&($scope.runSummary=JSON.parse($scope.model.Summary)),$scope.model.ValidationSummary&&($scope.validationSummary=JSON.parse($scope.model.ValidationSummary)),"Started"===$scope.model.Status&&checkJobStatus();var hash=$location.hash();hash?setCurrentStep(_.find($scope.steps,function(step){return step.name===hash})):"Completed"===$scope.model.Status?setCurrentStep(_.find($scope.steps,function(step){return"startImport"===step.name})):$scope.model.FieldMapping&&$scope.model.FieldMapping.length>0?setCurrentStep(_.find($scope.steps,function(step){return"validateImport"===step.name})):$scope.model.GuidBinaryData?setCurrentStep(_.find($scope.steps,function(step){return"editFieldMappings"===step.name})):$scope.model.EntityType&&setCurrentStep(_.find($scope.steps,function(step){return"chooseSource"===step.name}))},function(error){repository.growl(error,"danger")})}function handleChooseObjectStep(){var deferred=$q.defer();return $scope.model.Guid?repository.updateSingle(repository.apiData.dataImport.url,$scope.model).then(function(response){$scope.model=response,deferred.resolve(!0)},function(error){repository.growl(error,"danger"),deferred.reject(error)}):repository.createSingle(repository.apiData.dataImport.url,$scope.model).then(function(response){$scope.model=response,$location.path($location.path()+response.Guid),$location.replace(),deferred.resolve(!0)},function(error){repository.growl(error,"danger"),deferred.reject(error)}),deferred.promise}function handleChooseSourceStep(){var deferred=$q.defer();return repository.updateSingle(repository.apiData.dataImport.url,$scope.model).then(function(response){$scope.model=response,repository.runAction(repository.apiData.dataImport.url+$scope.model.Guid+"/GetInitialFieldMappings").then(function(result){$scope.model.FieldMapping=result.FieldMapping,deferred.resolve(!0)},function(error){repository.growl(error,"danger"),deferred.reject(error)})},function(error){repository.growl(error,"danger"),deferred.reject(error)}),deferred.promise}function onChooseSourceAppearing(){$scope.sheetOptions&&$scope.model.GuidBinaryData&&!$scope.tempTable&&$scope.getPreview()}function onFieldMappingsAppearing(){$scope.tempTable||$scope.getPreview()}function updateDataImport(){var deferred=$q.defer();return repository.updateSingle(repository.apiData.dataImport.url,$scope.model).then(function(response){$scope.model=response,deferred.resolve(!0)},function(error){repository.growl(error,"danger"),deferred.reject(error)}),deferred.promise}function getRelationType(mapping){return mapping.PlaniaField?mapping.PlaniaField.startsWith("NonsReference.")?"Owned":mapping.PlaniaField.includes(".")?"Relation":"Direct":"Direct"}function checkJobStatus(){repository.getSingleWithNoParameter(repository.apiData.dataImport.url+$scope.model.Guid+"/JobStatus").then(function(result){result&&($scope.importJobId=result)})}function getProcessingSignalRMethodName(){return"processingDataImportRun_"+$scope.model.Guid}function getValidatingSignalRMethodName(){return"validatingDataImportRun_"+$scope.model.Guid}function initializeImportJobValidatingSignalR(methodName){$scope.validationSummary||($scope.validationSummary={RowSummaries:[]}),signalR.on(methodName,function(progress){if(!0===progress.Finished)return void($scope.importJobValidating=!1);$scope.importJobValidating=!0,$scope.importJobValidationProgress=progress,$scope.validationSummary.RowSummaries.push(progress.RowSummary),$scope.validationSummary.RunStatistics=progress.RunStatistics}),$scope.$on("$destroy",function(){signalR.off(methodName)})}function initializeImportJobProcessingSignalR(methodName){$scope.runSummary||($scope.runSummary={RowSummaries:[]}),signalR.on(methodName,function(progress){if(!0===progress.Finished)return void $timeout(function(){$scope.importJobProcessing=!1,getModel()},250);$scope.importJobProcessing=!0,$scope.importJobProgress=progress,$scope.runSummary.RowSummaries.push(progress.RowSummary),$scope.runSummary.RunStatistics=progress.RunStatistics}),$scope.$on("$destroy",function(){signalR.off(methodName)})}function downloadSummaryReport(url){url+="?access_token="+repository.authService.getPlaniaToken().access,url+=repository.getUrlParameters("&"),$window.open(url,"_self")}$scope.isEdit=!!$stateParams.guid,$scope.entityTypes=[{key:repository.apiData.estate.prefix,value:translationService.translate("web-enum-prefix-estate")},{key:repository.apiData.building.prefix,value:translationService.translate("web-enum-prefix-building")},{key:repository.apiData.equipment.prefix,value:translationService.translate("web-enum-prefix-equipment")},{key:repository.apiData.area.prefix,value:translationService.translate("web-enum-prefix-area")},{key:repository.apiData.component.prefix,value:translationService.translate("web-enum-prefix-component")},{key:repository.apiData.supplier.prefix,value:translationService.translate("web-enum-prefix-supplier")},{key:repository.apiData.person.prefix,value:translationService.translate("web-enum-prefix-person")},{key:repository.apiData.customer.prefix,value:translationService.translate("web-enum-prefix-customer")},{key:repository.apiData.cost.prefix,value:translationService.translate("web-enum-prefix-cost")},{key:repository.apiData.doorKey.prefix,value:translationService.translate("web-enum-prefix-doorKey")},{key:repository.apiData.doorLock.prefix,value:translationService.translate("web-enum-prefix-doorLock")},{key:repository.apiData.condition.prefix,value:translationService.translate("web-enum-prefix-condition")}],$scope.entityTypes.sort(function(a,b){return a.valueb.value?1:0}),$scope.steps=[{stepIndex:1,name:"chooseObject",hidden:!1,title:translationService.translate("web-dataImport-wizard-stepTitle-chooseObject","Velg objekt"),onNextStepClicked:handleChooseObjectStep},{stepIndex:2,name:"chooseSource",hidden:!1,title:translationService.translate("web-dataImport-wizard-stepTitle-chooseSource","Velg kilde"),onNextStepClicked:handleChooseSourceStep,onStepAppearing:onChooseSourceAppearing},{stepIndex:3,name:"editFieldMappings",hidden:!1,title:translationService.translate("web-dataImport-wizard-stepTitle-editFieldMappings","Rediger knytninger"),onNextStepClicked:updateDataImport,onStepAppearing:onFieldMappingsAppearing},{stepIndex:4,name:"validateImport",hidden:!1,title:translationService.translate("web-dataImport-wizard-stepTitle-validateImport","Validering"),onNextStepClicked:updateDataImport},{stepIndex:5,name:"startImport",hidden:!1,title:translationService.translate("web-dataImport-wizard-stepTitle-startImport","Start import")}],$scope.isEdit||($scope.currentStep=$scope.steps[0],$scope.completedStepIndex=$scope.currentStep.stepIndex);var setCurrentStep=function(step){$location.hash(step.name).replace(),$scope.currentStep=step,(void 0===$scope.completedStepIndex||$scope.completedStepIndex<$scope.currentStep.stepIndex)&&($scope.completedStepIndex=$scope.currentStep.stepIndex),void 0!==$scope.currentStep.onStepAppearing&&$scope.currentStep.onStepAppearing()},onChangeStep=function(step){if(void 0===$scope.currentStep.onNextStepClicked)return void setCurrentStep(step);$scope.currentStep.onNextStepClicked().then(function(valid){valid&&setCurrentStep(step)})};$scope.onStepClick=function(step){step.stepIndex>$scope.completedStepIndex||setCurrentStep(step)},$scope.handlePreviousStep=function(){var step=_.find($scope.steps,function(step){return step.stepIndex===$scope.currentStep.stepIndex-1});step&&setCurrentStep(step)},$scope.handleNextStep=function(){var step=_.find($scope.steps,function(step){return step.stepIndex===$scope.currentStep.stepIndex+1});step&&onChangeStep(step)},$scope.model={Guid:$stateParams.guid,InputConfig:{Type:"Excel",ExcelConfig:{}},FieldMapping:[]},$scope.showSelectFile=!0,$stateParams.guid?getModel():$stateParams.guidEntityToCopy&&repository.getSingle(repository.apiData.dataImport.url,$stateParams.guidEntityToCopy).then(function(result){delete result.Data.Guid,$scope.model=result.Data,$scope.model.Id+=" - kopi"}),$scope.currentNumberOfDataOwners=0,getNumberOfDataOwnersInLicense(),registeredFieldService.getRegisteredField(repository.commonService.prefix.DataImport).then(function(result){$scope.fieldRules=result}),$scope.dragOverClass=function($event){var items=$event.dataTransfer.items,hasFile=!1;if(items){for(var i=0;i=file.total?"success":"info"}))},$scope.setMappingColumn=function(mapping){var existingColumns=[];$scope.model.FieldMapping.forEach(function(map){map.PlaniaField&&existingColumns.push({Property:map.PlaniaField})}),$modal.open({templateUrl:"app/common/views/addNewListColumnModal.html",controller:"AddNewListColumnController",resolve:{params:function(){return{prefix:$scope.model.EntityType,existingColumns:existingColumns,showAdvancedMode:!0}}}}).result.then(function(selectedColumns){if(selectedColumns&&selectedColumns.length){if(selectedColumns[0].Property.split(".").length>=3)return;mapping.PlaniaField=selectedColumns[0].Property,mapping.PlaniaFieldTitle=selectedColumns[0].Title}})},$scope.resetMappingColumn=function(mapping){if(mapping){var mappingToChange=_.find($scope.model.FieldMapping,function(fieldMapping){return fieldMapping.ImportField===mapping.ImportField});mappingToChange.PlaniaField===$scope.model.PrimaryField&&($scope.model.PrimaryField=null),mappingToChange.PlaniaField=null,mappingToChange.PlaniaFieldTitle=null}},$scope.setPrimaryField=function(mapping){!mapping.PlaniaField||mapping.PlaniaField.split(".").length>=2||($scope.model.PrimaryField=mapping.PlaniaField)},$scope.mappingPrimaryFieldTooltipText={isPrimaryField:translationService.translate("web-dataImport-fieldMapping-isPrimaryField-popover","Denne kolonnen er valgt som hovedkolonne. Denne blir da brukt for å sjekke om et import objekt eksisterer i Plania."),isRelationField:translationService.translate("web-dataImport-fieldMapping-isRelationField-popover","Denne kolonnen er en knytningskolonne. Denne blir brukt for å knytte et import objekt til et annet relatert objekt som allerede eksisterer i Plania."),isNotSelected:translationService.translate("web-dataImport-fieldMapping-isNotSelected-popover","Klikk for å velge denne kolonnen som hovedkolonne. Denne blir da brukt for å sjekke om et import objekt eksisterer i Plania."),isOwnedField:translationService.translate("web-dataImport-fieldMapping-isOwnedField-popover","Denne kolonnen kan opprettes eller oppdateres likt som egenskaper på import objektet.")},$scope.getTooltipText=function(mapping,model){var relationType=getRelationType(mapping);return model.PrimaryField===mapping.PlaniaField?$scope.mappingPrimaryFieldTooltipText.isPrimaryField:"Relation"===relationType?$scope.mappingPrimaryFieldTooltipText.isRelationField:"Owned"===relationType?$scope.mappingPrimaryFieldTooltipText.isOwnedField:$scope.mappingPrimaryFieldTooltipText.isNotSelected},$scope.getClasses=function(mapping,model){var relationType=getRelationType(mapping),classes={"fas fa-star c-amber":model.PrimaryField===mapping.PlaniaField,"fas fa-star c-bluegray":"Relation"===relationType,"far fa-star":model.PrimaryField!==mapping.PlaniaField&&("Direct"===relationType||"Owned"===relationType)},classString="";for(var key in classes)classes[key]&&(classString+=key+" ");return classString.trim()},initializeImportJobValidatingSignalR(getValidatingSignalRMethodName()),$scope.runValidation=function(){updateDataImport().then(function(){$scope.validationSummary={RowSummaries:[]},repository.runAction(repository.apiData.dataImport.url+$scope.model.Guid+"/RunValidation").then(function(result){$scope.importJobId=result,$scope.importJobValidating=!0,$scope.importJobValidationProgress={Current:0,Total:100}},function(error){repository.growl(error,"danger")})})},$scope.cancelValidation=function(){$scope.importJobId&&repository.runAction(repository.apiData.dataImport.url+$scope.model.Guid+"/CancelValidation/"+$scope.importJobId).then(function(result){repository.growl("Validering avbrutt","info")},function(error){repository.growl(error,"danger")})},initializeImportJobProcessingSignalR(getProcessingSignalRMethodName()),$scope.startImport=function(){$scope.runSummary={RowSummaries:[]},repository.runAction(repository.apiData.dataImport.url+$scope.model.Guid+"/RunImport").then(function(result){$scope.importJobId=result,$scope.importJobProcessing=!0,$scope.importJobProgress={Current:0,Total:100}},function(error){repository.growl(error,"danger")})},$scope.cancelImport=function(){$scope.importJobId&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-cancelImport-message","Importen vil avbrytes"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-button-yes","Ja"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.runAction(repository.apiData.dataImport.url+$scope.model.Guid+"/CancelImport/"+$scope.importJobId).then(function(result){repository.growl("Import avbrutt","info")},function(error){repository.growl(error,"danger")})})},$scope.downloadSummaryReport=function(){downloadSummaryReport(config.baseUrlApi+repository.apiData.dataImport.url+$scope.model.Guid+"/ExportExcelSummary")},$scope.downloadValidationReport=function(){downloadSummaryReport(config.baseUrlApi+repository.apiData.dataImport.url+$scope.model.Guid+"/ExportExcelValidationSummary")},$scope.createNewImport=function(){$scope.navigation.go("dataImport.edit",{guidEntityToCopy:$scope.model.Guid},{inherit:!1})},$scope.deleteImport=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-dataImport-wizard-startImport-deleteMessage","Dataimport vil bli fjernet"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-button-confirm","Ja"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.dataImport.url,$scope.model.Guid).then(function(){repository.growl("Dataimport slettet","success"),$scope.goBack("dataImport.list",{menuGuid:$scope.navigation.params.menuGuid}),swal.close()})})},$scope.summaryStatusFilter="",$scope.validationSummaryStatusFilter="",$scope.rowStatuses=[{key:"Created",value:"Opprettet"},{key:"Updated",value:"Oppdatert"},{key:"Error",value:"Feilet"}],$scope.summaryFilter=function(status){return function(row){return!status||row.RowStatus===status}}}angular.module("Plania").controller("DataImportController",["$scope","TranslationService","Repository","RegisteredFieldService","$q","$stateParams","$modal","$location","SignalR","$timeout","config","$window",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,ngTableParams,translationService){$scope.isUpdate="dataOwner.edit"===$scope.navigation.current.name,$scope.languages=[],$scope.model={},$scope.restrictEdit=!1,$scope.activateAutocomplete=!1,$scope.refreshId=(new Date).toISOString();var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=!1;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.DataOwner,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.DataOwner,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.DataOwner),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.DataOwner)};updateAccess();var getSingle=function(){repository.getSingle(repository.apiData.dataOwner.url,$stateParams.guid).then(function(response){var dataOwner=response.Data;$scope.model=dataOwner,updateAccess(),repository.GetPaginated(repository.apiData.language.url,0,100,{},{}).then(function(result){$scope.languages=[],result.List.forEach(function(row){$scope.languages.push(row)}),$scope.model.GuidLanguage=$scope.model.GuidLanguage?$scope.model.GuidLanguage:$scope.languages[0].Guid}),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")})} ;$scope.isUpdate?getSingle():(repository.GetPaginated(repository.apiData.language.url,0,100,{},{}).then(function(result){result.List.forEach(function(row){$scope.languages.push(row)});var language=_.filter($scope.languages,{Country:"Norway"})[0]||$scope.languages[0];$scope.model.GuidLanguage=language.Guid}),$scope.activateAutocomplete=!0),$scope.onPostCodeSelect=function(postalInfo){postalInfo?($scope.model.PostalCode=postalInfo.ZipCode,$scope.model.GuidPost=postalInfo.Guid,$scope.model.PostalArea=postalInfo.PostalArea,$scope.model.County=postalInfo.County,$scope.model.Municipality=postalInfo.MunicipalityName,$scope.postalInfo=postalInfo):($scope.model.GuidPost=null,$scope.model.PostalArea="",$scope.model.County="",$scope.model.Municipality="")},$scope.updateDataOwner=function(destination){$scope.model.ActivityPeriodDate=$scope.model.ActivityPeriodDate?new Date($scope.model.ActivityPeriodDate).toISOString():null,$scope.model.EnergyPeriodDate=$scope.model.EnergyPeriodDate?new Date($scope.model.EnergyPeriodDate).toISOString():null;var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-dataowner-success","Kienten har blitt oppdatert."):translationService.translate("create-dataowner-success","Klienten har blitt registrert."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(result){repository.growl(result,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.dataOwner.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.dataOwner.url,$scope.model).then(success).catch(error)},$scope.deleteDataOwner=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-dataowner-message","Klienten vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-dataowner-button-confirm","Ja, fjern klienten!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.dataOwner.url,$scope.model.Guid).then(function(result){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-dataowner-success","Klienten ble fjernet!"),result,"success"),repository.growl(translationService.translate("delete-dataowner-success-message"," Klienten ble fjernet fra systemet"),"success"),$scope.goBack("dataOwner.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.onImageFileSelect=function(images){function handleFileUpload(file){var reader=new FileReader;reader.onload=function(e){var newFile={ImageSrc:e.target.result.substr(e.target.result.indexOf("base64,")+"base64,".length),Name:file.name};files.push(newFile),onLoadEndHandler()},reader.readAsDataURL(file)}function onLoadEndHandler(image){var url=repository.apiData.dataOwner.url+"logoImage/"+$scope.model.Guid;repository.createSingle(url,files).then(function(result){result.Guid&&($scope.model.GuidImageLogo=result.Guid),repository.growl(translationService.translate("web-dataOwner-imageLogo-update-success","Logo har blitt oppdatert"),"success"),$scope.refreshId=(new Date).toISOString()},function(error){error&&repository.growl(error,"danger")})}var files=[];images&&0!==images.length&&handleFileUpload(images[0])},$scope.deleteLogo=function(){var url=repository.apiData.dataOwner.url+"logoImage/"+$scope.model.Guid;repository.deleteSingle(url,"").then(function(result){repository.growl(translationService.translate("web-dataOwner-imageLogo-delete-success","Logo har blitt slettet"),"success"),$scope.model.GuidImageLogo=null,$scope.refreshId=(new Date).toISOString()},function(error){repository.growl(error)})},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"documentCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}return filter}}angular.module("Plania").controller("DataOwnerController",["$scope","Repository","$stateParams","$modal","ngTableParams","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService){$scope.isUpdate="department.edit"===$scope.navigation.current.name,$scope.activateAutocomplete=!1;var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Department,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Department,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Department),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Department)};if($scope.isUpdate){var columns=["PurchaseOrderForm.Description"];repository.getSingle(repository.apiData.department.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,updateAccess(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})}else $scope.activateAutocomplete=!0;$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-department-success","Avdeling har blitt oppdatert."):translationService.translate("create-department-success","Avdeling har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};delete $scope.model.PurchaseOrderForm,$scope.isUpdate?repository.updateSingle(repository.apiData.department.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.department.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-department-message","Avdeling vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-department-button-confirm","Ja, fjern avdeling"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.department.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-department-success","Avdeling ble fjernet!"),result,"success"),$scope.goBack("department.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("DepartmentController",["$scope","Repository","$stateParams","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,$modalInstance,$modal,$localStorage,translationService,constants,$rootScope,deviationService,registeredFieldService){var isModal=$stateParams.isModal;$scope.isUpdate=!!$stateParams.guid,$scope.model={},$scope.modelDto={},$scope.modelIsLoaded=!1,$stateParams.guid&&($scope.model.Guid=$stateParams.guid),$scope.parentEntity=$stateParams.parentEntity,$scope.disableEntityInput=$stateParams.disableEntityInput,$scope.activateAutocomplete=!1,$scope.viewMode=!(isModal||!$scope.isUpdate),$scope.filterOnBuilding=$localStorage.generalOptions.InspectedEntityLocation===constants.inspectedEntityLocation.building&&"WorkOrder"===$scope.parentEntity,$scope.filterOnEstate=$localStorage.generalOptions.InspectedEntityLocation===constants.inspectedEntityLocation.estate&&"WorkOrder"===$scope.parentEntity,$scope.reloadDocumentTable=!1,$scope.isDocumentsCollapsed=!0,$scope.defaultDocumentCategory={Guid:repository.commonService.getFilterData().selectedDataOwner.GuidWoXEqDocumentCategory,Name:repository.commonService.getFilterData().selectedDataOwner.WoXEqDocumentCategory},$scope.entityCommentSearch={searchString:"",focus:!1},$scope.generalOptions=$localStorage.generalOptions,$scope.extendedDeviationControl=$localStorage.generalOptions.ExtendedDeviationControl,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode};var updateAccess=function(status){if(status&&"Closed"===status)$scope.restrictEdit=!0,$scope.restrictDelete=!0;else if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Deviation,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Deviation,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Deviation),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Deviation)};isModal&&!$scope.isUpdate&&($scope.processingSectionVisibility=!0,registeredFieldService.getRegisteredField(repository.commonService.prefix.Deviation).then(function(registeredFields){var fields=["GuidPriority","PriorityComment","DeadlineDate"];$scope.extendedDeviationControl&&fields.push("GuidResponsiblePerson","CausalAnalysis","RiskOfRepetition","GuidClassificationReference");var visibility={};fields.forEach(function(field){var rule=_.filter(registeredFields,{DomainFieldName:field})[0];visibility[field]=!!rule&&!!rule.Mandatory}),Object.values(visibility).every(function(value){return!1===value})?$scope.processingSectionVisibility=!1:$scope.processingSectionVisibility=visibility})),$scope.canCloseDeviation=function(guidWorkOrder){return"Closed"!==$scope.model.Status&&($localStorage.generalOptions.CloseDeviationFromWoOnly?guidWorkOrder&&$scope.model.GuidWorkOrder===guidWorkOrder:!guidWorkOrder||$scope.model.GuidWorkOrder===guidWorkOrder)},$scope.closeDeviation=function(){swal({title:translationService.translate("web-swal-close-Deviation","Bekreft lukking av avvik"),text:translationService.translate("web-swal-close-Deviation-message","Er avviket klar til å bli lukket?"),type:"info",showCancelButton:!0,confirmButtonColor:"#2196f3",confirmButtonText:translationService.translate("web-swal-deviation-button-confirm","Ja, Lukk avviket!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.runAction(repository.apiData.deviation.endpoint.close+$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-deviation-success","Avviket ble lukket!"),"","success"),$scope.goBack("deviation.edit",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})})})},$scope.closeOrPostponeDeviationDirectly=function(shouldClose){$modal.open({templateUrl:"app/deviation/views/closeDeviationDirectlyModal.html",controller:"CloseDeviationDirectlyModalController",resolve:{params:function(){return{guid:$scope.model.Guid,close:!!shouldClose}}}}).result.then(function(result){getDeviation()})},$stateParams.building&&($scope.model.Building=$stateParams.building,$scope.model.GuidBuilding=$stateParams.building.guid),$stateParams.estate&&($scope.model.Estate=$stateParams.estate,$scope.model.GuidEstate=$stateParams.estate.guid),$stateParams.area&&($scope.model.Area=$stateParams.area,$scope.model.GuidArea=$stateParams.area.guid),$stateParams.equipment&&($scope.model.Equipment=$stateParams.equipment,$scope.model.GuidEquipment=$stateParams.equipment.guid);var columns=["UserClosedBy.RealName","UserCreatedBy.RealName","Estate.Id","Estate.Description","Building.Id","Building.Description","Area.Id","Area.Description","Equipment.Id","Equipment.Description","DeviationType.Id","DeviationType.Description","ControlListItemAnswer.Value","ControlListItemAnswer.ControlListItem.Name","ControlListItemAnswer.ControlListXEntity.Guid","ControlListItemAnswer.ControlListXEntity.Equipment.Id","ControlListItemAnswer.ControlListXEntity.Equipment.Description","ControlListItemAnswer.ControlListXEntity.Area.Id","ControlListItemAnswer.ControlListXEntity.Area.Description","ControlListItemAnswer.ControlListXEntity.ControlList.Name","ControlListItemAnswer.ControlListXEntity.ControlList.Id","ControlListItemAnswer.ControlListXEntity.ControlList.Description","ControlListItemAnswer.ControlListXEntity.WorkOrder.Id","ControlListItemAnswer.ControlListXEntity.WorkOrder.Description","ControlListItemAnswer.ControlListXEntity.WorkOrder.Status","ControlListItemAnswer.ControlListXEntity.WorkOrder.DueDate","ControlListItemAnswer.ControlListXEntity.WorkOrder.GuidProject","ControlListItemAnswer.ControlListXEntity.WorkOrder.EndDate","ControlListItemAnswer.ControlListXEntity.WorkOrder.GuidPeriodicTask","ControlListItemAnswer.ControlListXEntity.WorkOrder.Project.Id","ControlListItemAnswer.ControlListXEntity.WorkOrder.Project.Id","CorrectiveWorkOrder.Id","CorrectiveWorkOrder.Description","CorrectiveWorkOrder.Status","CorrectiveWorkOrder.DueDate","CorrectiveWorkOrder.GuidProject","CorrectiveWorkOrder.EndDate","CorrectiveWorkOrder.GuidPeriodicTask","CorrectiveWorkOrder.Project.Id","CorrectiveWorkOrder.Project.Id","InspectionWorkOrder.Id","InspectionWorkOrder.Description","InspectionWorkOrder.Status","InspectionWorkOrder.DueDate","InspectionWorkOrder.GuidProject","InspectionWorkOrder.EndDate","InspectionWorkOrder.GuidPeriodicTask","InspectionWorkOrder.Project.Id","InspectionWorkOrder.Project.Id","Priority.Guid","Priority.Description","PriorityComment","Priority.Color","ResponsiblePerson.FirstName","ResponsiblePerson.LastName","ClassificationReference.Id","ClassificationReference.Description"];$scope.deviationCauses=[],function(){var filter={FilterModel:{Condition:"and",Rules:[{Property:"ReferenceType.Context",Operator:"=",Value:"DeviationCause"}]}};repository.GetPaginated(repository.apiData.referenceData.url,0,-1,{IndexPosition:"asc"},filter).then(function(response){$scope.deviationCauses=response.List.map(function(data){return data.Caption})})}();var getDeviation=function(){repository.getMainModel(repository.apiData.deviation.url,$scope.model.Guid,JSON.stringify(columns)).then(function(result){$scope.model=result.Data,$scope.reloadDocumentTable=!0,updateAccess($scope.model.Status),setTimeout(function(){$scope.activateAutocomplete=!0},250),$scope.modelIsLoaded=!0},function(error){repository.showError(error)})};if($scope.isUpdate)getDeviation();else{if($scope.model.RegisteredDate=(new Date).toISOString(),!isModal){var selectedBuilding=repository.commonService.getFilterData().selectedBuilding;selectedBuilding.Guid&&($scope.model.GuidBuilding=selectedBuilding.Guid,$scope.model.Building={Caption:selectedBuilding.Name},selectedBuilding.Estate&&($scope.model.GuidEstate=selectedBuilding.Estate.Guid,$scope.model.Estate=selectedBuilding.Estate))}var selectedEstate=repository.commonService.getFilterData().selectedEstate;selectedEstate&&""!==selectedEstate.Guid&&($scope.model.GuidEstate=selectedEstate.Guid,$scope.modelDto.estate=selectedEstate.Name);var webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value)switch(prefill.Property){case"Estate":$scope.model.Estate={Caption:prefill.Value.Label},$scope.model.GuidEstate=prefill.Value.Guid;break;case"Building":$scope.model.Building={Caption:prefill.Value.Label},$scope.model.GuidBuilding=prefill.Value.Guid;break;case"Equipment":$scope.model.Equipment={Caption:prefill.Value.Label},$scope.model.GuidEquipment=prefill.Value.Guid;break;case"Area":$scope.model.Area={Caption:prefill.Value.Label},$scope.model.GuidArea=prefill.Value.Guid;break;case"DeviationType":$scope.model.DeviationType={Caption:prefill.Value.Label},$scope.model.GuidDeviationType=prefill.Value.Guid}else if("@CurrentBuilding"===prefill.Value){var selectedBuilding=repository.commonService.getFilterData().selectedBuilding;selectedBuilding.Guid&&($scope.model.Building={Caption:selectedBuilding.Name},$scope.model.GuidBuilding=selectedBuilding.Guid)}else $scope.model[prefill.Property]=prefill.Value}),$scope.activateAutocomplete=!0,$scope.modelIsLoaded=!0}$scope.saveAction=function(action){$scope.model.DeadlineDate&&($scope.model.DeadlineDate=new Date($scope.model.DeadlineDate).toISOString()),$scope.isUpdate?repository.updateSingle(repository.apiData.deviation.url,$scope.model).then(function(result){repository.growl(translationService.translate("web-deviation-deviationUpdated","Avvik oppdatert"),"success"),isModal?$modalInstance.close("ok"):($scope.goBack(action,{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid}),$scope.model=result)}).catch(function(error){repository.growl(error,"danger")}):($scope.model.GuidInspectionWorkOrder=$stateParams.GuidInspectionWorkOrder,repository.createSingle(repository.apiData.deviation.url,$scope.model).then(function(result){repository.growl(translationService.translate("web-deviation-deviationAdded","Avvik har blitt lagt til"),"success"),"close"===action?$modalInstance.close("ok"):(isModal||($scope.viewMode=!0,repository.commonService.setLastRegisterGuid("deviation.list",result.Guid),$scope.goBack(action,{guid:result.Guid,menuGuid:$scope.navigation.params.menuGuid})),$scope.model.Guid=result.Guid,getDeviation(),$scope.isUpdate=!0)}).catch(function(error){repository.growl(error,"danger")}))},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.autoCompleteFilter=function(filterName){var filter={},estateFieldRule=registeredFieldService.getLocalRegisteredField(repository.apiData.deviation.prefix,"GuidEstate"),isEstateHidden=estateFieldRule&&estateFieldRule.Hidden;switch(filterName){case"building":return $scope.model.GuidEstate&&(isEstateHidden||(filter.PropertyFilter=[{Property:"GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}])),filter;case"area":return filter={GuidBuilding:$scope.model.GuidBuilding?$scope.model.GuidBuilding:null},$scope.model.GuidEstate&&!isEstateHidden&&(filter.PropertyFilter=[{Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]),filter;case"equipment":if(filter={GuidBuilding:$scope.model.GuidBuilding,hasConditionControl:!0,PropertyFilter:[]},!$scope.model.GuidEstate||$scope.model.GuidBuilding||isEstateHidden||(filter.PropertyFilter=[{Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]),$localStorage.generalOptions.FilterDeviationByEqPrefix&&$scope.model.GuidDeviationType){var id=$scope.model.DeviationType.Caption.substr(0,3).trim();filter.PropertyFilter.push({Property:"Id",Operator:"StartsWith",Value:id})}return filter.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:!1}),filter;case"deviationType":return $localStorage.generalOptions.FilterDeviationByEqPrefix&&$scope.model.GuidEquipment?{PropertyFilter:[{Property:"Id",Operator:"StartsWith",Value:$scope.model.Equipment.Caption.substr(0,3).trim()}]}:{};case"priority":return{PropertyFilter:[{Property:"EntityType",Operator:"=",Value:"Deviation"}]};case"deviationClassification":return filter.FilterModel={Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null}]},{Property:"ReferenceType.Context",Operator:"=",Value:"DeviationClassification"}]},filter}},$scope.getDeviationClassificationColumns=function(){return[{Title:translationService.translate("web-deviationClassification-indexPosition","Indeks"),Property:"IndexPosition"},{Title:translationService.translate("web-deviationClassification-id","Id"),Property:"Id"},{Title:translationService.translate("web-deviationClassification-description","Beskrivelse"),Property:"Description"}]},$scope.openReferenceData=function(){$modal.open({templateUrl:"app/referenceData/views/referenceDataInfoModal.html",controller:"ReferenceDataInfoModalController",resolve:{modalParams:function(){return{guid:$scope.model.GuidClassificationReference,initialModel:$scope.model.ClassificationReference}}},size:"lg"})},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.onEstateSelect=function(estate){if(!estate)return void($scope.model.GuidEstate="");$scope.model.GuidEstate!==estate.Guid&&($scope.model.GuidBuilding="",$scope.model.Building=null,$scope.model.GuidEquipment="",$scope.model.Equipment=null,$scope.model.GuidArea="",$scope.model.Area=null),$scope.model.GuidEstate=estate.Guid},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidEquipment="",$scope.model.Equipment=null,$scope.model.GuidArea="",$scope.model.Area=null),$scope.model.GuidBuilding=building.Guid,$scope.model.GuidEstate&&""!==$scope.model.GuidEstate||($scope.model.GuidEstate=building.GuidEstate,$scope.model.Estate=building.Estate)},$scope.onAreaSelect=function(area){if(!area)return void($scope.model.GuidArea="");$scope.model.GuidArea=area.Guid,$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=area.GuidBuilding,$scope.model.Building=area.Building),$scope.model.GuidEstate&&""!==$scope.model.GuidEstate||($scope.model.GuidEstate=area.Building.Estate.Guid,$scope.model.Estate=area.Building.Estate)},$scope.onEquipmentSelect=function(equipment){if(!equipment)return void($scope.model.GuidEquipment="");$scope.model.GuidEquipment=equipment.Guid,$scope.model.GuidEstate&&""!==$scope.model.GuidEstate||($scope.model.GuidEstate=equipment.Building.Estate.Guid,$scope.model.Estate=equipment.Building.Estate),$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=equipment.GuidBuilding,$scope.model.Building=equipment.Building),equipment.GuidArea&&($scope.model.GuidArea=equipment.GuidArea,$scope.model.Area=equipment.Area)},$scope.onDeviationTypeSelect=function(deviationType){if(!deviationType)return $scope.model.GuidDeviationType="",void($scope.model.DeviationType=null);$scope.model.GuidDeviationType=deviationType.Guid},$scope.openControlList=function(){$modal.open({templateUrl:"app/controlList/views/controlListCompletionModal.html",size:"xl",controller:"ControlListCompletionModalController",resolve:{params:function(){return{workOrderCaption:$scope.model.ControlListItemAnswer.ControlListXEntity.WorkOrder.Caption,controlList:$scope.model.ControlListItemAnswer.ControlListXEntity.ControlList,controlListXEntity:$scope.model.ControlListItemAnswer.ControlListXEntity,restrictEdit:!0}}}}).result.then(function(result){},function(){})},$scope.createWorkOrder=function(){deviationService.createWorkOrder($scope.model)};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.originContextMenu=function(){var options=[];return $scope.hasReadAccess("ControlListXEntity")&&$scope.model.GuidControlListItemAnswer&&options.push({html:' '+translationService.translate("web-deviation-originContextMenu-viewInspectionControlListXEntity","Åpne kontrollisten")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.openControlList()}}),$scope.hasReadAccess("WorkOrder")&&$scope.model.GuidInspectionWorkOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:$scope.model.GuidInspectionWorkOrder}),translationService.translate("web-deviation-originContextMenu-viewInspectionWorkOrder","Gå til arbeidsordre"))),$scope.hasReadAccess("Project")&&$scope.model.GuidInspectionWorkOrder&&$scope.model.InspectionWorkOrder&&$scope.model.InspectionWorkOrder.GuidProject&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("project.edit",{guid:$scope.model.InspectionWorkOrder.GuidProject}),translationService.translate("web-deviation-originContextMenu-viewInspectionProject","Gå til prosjekt"))),$scope.hasReadAccess("PeriodicTask")&&$scope.model.GuidInspectionWorkOrder&&$scope.model.InspectionWorkOrder&&$scope.model.InspectionWorkOrder.GuidPeriodicTask&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:$scope.model.InspectionWorkOrder.GuidPeriodicTask}),translationService.translate("web-deviation-originContextMenu-viewInspectionPeriodicTask","Gå til periodisk rutine"))),0===options.length&&options.push({html:''+translationService.translate("web-deviation-originContextMenu-empty","Ingen aksjoner tilgjengelig")+"",enabled:!1}),options},$scope.followUpContextMenu=function(){var options=[];return $scope.hasEditAccess("Deviation")&&$scope.model.GuidCorrectiveWorkOrder&&$scope.model.CorrectiveWorkOrder&&!$scope.model.CorrectiveWorkOrder.EndDate&&$scope.canCloseDeviation($scope.model.GuidCorrectiveWorkOrder)&&options.push({html:' '+translationService.translate("web-deviation-followUpContextMenu-closeDeviationFromCorrective","Lukk avviket via")+" "+$scope.model.CorrectiveWorkOrder.Caption+"",click:function(){$scope.closeDeviation()}}),$scope.hasEditAccess("Deviation")&&!$scope.model.GuidCorrectiveWorkOrder&&$scope.model.GuidInspectionWorkOrder&&$scope.model.InspectionWorkOrder&&!$scope.model.InspectionWorkOrder.EndDate&&$scope.canCloseDeviation($scope.model.GuidInspectionWorkOrder)&&options.push({html:' '+translationService.translate("web-deviation-followUpContextMenu-closeDeviationFromInspection","Lukk avviket via")+" "+$scope.model.InspectionWorkOrder.Caption+"",click:function(){$scope.closeDeviation()}}),$scope.hasEditAccess("Deviation")&&!$scope.model.GuidCorrectiveWorkOrder&&!$scope.model.GuidInspectionWorkOrder&&$scope.canCloseDeviation()&&options.push({html:' '+translationService.translate("web-deviation-followUpContextMenu-closeDeviationFromDirectly","Lukk avviket direkte uten arbeidsordre")+"",click:function(){$scope.closeDeviation()}}),$scope.hasReadAccess("WorkOrder")&&$scope.model.GuidCorrectiveWorkOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:$scope.model.GuidCorrectiveWorkOrder}),translationService.translate("web-deviation-followUpContextMenu-viewCorrectiveWorkOrder","Gå til arbeidsordre"))),$scope.hasReadAccess("Project")&&$scope.model.GuidCorrectiveWorkOrder&&$scope.model.CorrectiveWorkOrder&&$scope.model.CorrectiveWorkOrder.GuidProject&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("project.edit",{guid:$scope.model.CorrectiveWorkOrder.GuidProject}),translationService.translate("web-deviation-followUpContextMenu-viewCorrectiveProject","Gå til prosjekt"))),$scope.hasReadAccess("PeriodicTask")&&$scope.model.GuidCorrectiveWorkOrder&&$scope.model.CorrectiveWorkOrder&&$scope.model.CorrectiveWorkOrder.GuidPeriodicTask&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:$scope.model.CorrectiveWorkOrder.GuidPeriodicTask}),translationService.translate("web-deviation-followUpContextMenu-viewCorrectivePeriodicTask","Gå til periodisk rutine"))),$scope.hasEditAccess("Deviation")&&"InWorks"===$scope.model.Status&&$scope.model.GuidCorrectiveWorkOrder&&!$scope.model.CorrectiveWorkOrder.EndDate&&options.push({html:' '+translationService.translate("web-deviation-followUpContextMenu-removeFromWorkOrder","Koble fra arbeidsordre")+"",click:function(){swal({title:translationService.translate("web-deviation-followUpContextMenu-removeFromWorkOrder-swalTitle","Bekreft frakobling av avvik"),text:translationService.translate("web-deviation-followUpContextMenu-removeFromWorkOrder-swalMessage","Er du sikker på at du vil koble dette avviket ifra arbeidsordren?"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-deviation-followUpContextMenu-removeFromWorkOrder-swalConfirm","Ja, koble fra!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.runAction(repository.apiData.deviation.endpoint.resetCorrectiveWorkOrder+$scope.model.Guid).then(function(result){swal(translationService.translate("web-deviation-followUpContextMenu-removeFromWorkOrder-success","Avviket ble frakoblet arbeidsordren"),result.Caption,"success"),$scope.goBack("deviation.edit",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})},function(error){swal("Error",error,"error")})})}}),$scope.hasCreateAccess("WorkOrder")&&"Closed"!==$scope.model.Status&&!$scope.model.GuidCorrectiveWorkOrder&&options.push({html:' '+translationService.translate("web-deviation-followUpContextMenu-createWorkOrder","Opprett ny arbeidsordre for utbedring av avvik")+"",click:function(){$scope.createWorkOrder()}}),$scope.hasReadAccess("WorkOrder")&&"Closed"!==$scope.model.Status&&$scope.hasEditAccess("Deviation")&&!$scope.model.GuidCorrectiveWorkOrder&&options.push({html:' '+translationService.translate("web-deviation-followUpContextMenu-addToExistingWo","Koble til eksisterende arbeidsordre")+"",click:function(){$modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:translationService.translate("web-deviation-followUpContextMenu-addToExistingWo-modalTitle","Velg arbeidsordre avviket skal kobles til"),url:repository.apiData.workOrder.url,sorting:{Id:"desc"},filter:{PropertyFilter:[{Property:"EndDate",Operator:"=",Value:null}]},columns:[{title:translationService.translate("web-workOrder-Id","Ao Nr"),property:"Id"},{title:translationService.translate("web-workOrder-Description","Beskrivelse"),property:"Description",PropertyType:"String"},{title:translationService.translate("web-workOrder-Building-Id","Bygg Id"),property:"Building.Id"},{title:translationService.translate("web-workOrder-Building-Description","Byggbeskrivelse"),property:"Building.Description",PropertyType:"String"}]}}}}).result.then(function(selectedEntity){$scope.model.GuidCorrectiveWorkOrder=selectedEntity.Guid,$scope.saveAction("deviation.edit")})}}),"Closed"!==$scope.model.Status&&$scope.hasEditAccess("Deviation")&&!$scope.model.GuidCorrectiveWorkOrder&&options.push({ html:' '+translationService.translate("web-deviation-followUpContextMenu-closeDeviationDirectly","Lukk avvik direkte")+"",click:function(){$scope.closeOrPostponeDeviationDirectly(!0)}}),!$scope.hasEditAccess("Deviation")||"New"!==$scope.model.Status&&"InWorks"!==$scope.model.Status||options.push({html:' '+translationService.translate("web-deviation-followUpContextMenu-postponeDeviation","Utsett avviket")+"",click:function(){$scope.closeOrPostponeDeviationDirectly(!1)}}),0===options.length&&options.push({html:''+translationService.translate("web-deviation-followUpContextMenu-empty","Ingen aksjoner tilgjengelig")+"",enabled:!1}),options}}angular.module("Plania").controller("DeviationController",["$scope","Repository","$stateParams","$modalInstance","$modal","$localStorage","TranslationService","Constants","$rootScope","DeviationService","RegisteredFieldService",controller])}(),function(){function controller($scope,params,$modalInstance,translationService,registeredFieldService,repository){$scope.guidDeviation=_.clone(params.guid),$scope.close=_.clone(params.close),$scope.model={},function(){repository.getSingle(repository.apiData.deviation.url,$scope.guidDeviation).then(function(result){$scope.model=result.Data},function(error){repository.growl(error,"danger")})}(),$scope.isValid=function(){return!$scope.close||"Undefined"!==$scope.model.ClosedReason&&"Processed"!==$scope.model.ClosedReason},$scope.saveAction=function(){$scope.close?($scope.model.EndDate=(new Date).toISOString(),$scope.model.GuidUserClosedBy=repository.authService.getUserData().guidUser):$scope.model.Status="Postponed",repository.updateSingle(repository.apiData.deviation.url,$scope.model).then(function(result){swal($scope.close?translationService.translate("web-swal-deviation-success","Avviket ble lukket!"):translationService.translate("web-swal-deviation-postpone-success","Avviket ble utsatt!"),"","success"),$modalInstance.close($scope.close?"Avviket er lukket":"Avviket er utsatt")},function(error){error&&repository.growl(error,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CloseDeviationDirectlyModalController",["$scope","params","$modalInstance","TranslationService","RegisteredFieldService","Repository",controller])}(),function(){function controller($scope,$modal,ngTableParams,repository,$rootScope,translationService,$localStorage,Constants,deviationService){$scope.deviationsIsLoading=!0,$scope.search={};var updateAccess=function(){$scope.hasEditAccess=$rootScope.hasEditAccess("Deviation"),$scope.hasCreateAccess=$rootScope.hasCreateAccess("Deviation"),$scope.hasDeleteAccess=$rootScope.hasDeleteAccess("Deviation")};updateAccess();var filterTypes=[{value:"all",name:translationService.translate("web-deviation-filterType-all","Alle"),longName:translationService.translate("web-deviation-filterType-showAll","Vis alle avvik")},{value:"open",name:translationService.translate("web-deviation-filterType-open","Åpne"),longName:translationService.translate("web-deviation-filterType-showOpen","Vis åpne avvik")},{value:"closed",name:translationService.translate("web-deviation-filterType-closed","Lukkede"),longName:translationService.translate("web-deviation-filterType-showClosed","Vis lukkede avvik")}];$scope.currentSelectedFilterType=_.find(filterTypes,{value:"WorkOrder"===$scope.parentEntity?"all":"open"});var deviationIsClosed=function(deviation){return deviation&&"Closed"===deviation.Status};$scope.canDeleteDeviation=function(deviation){return!deviationIsClosed(deviation)&&deviation.GuidCorrectiveWorkOrder&&deviation.GuidCorrectiveWorkOrder===$scope.guid},$scope.canCloseDeviation=function(deviation){return!deviationIsClosed(deviation)&&($localStorage.generalOptions.CloseDeviationFromWoOnly?"WorkOrder"===$scope.parentEntity&&deviation.GuidWorkOrder===$scope.guid:"WorkOrder"!==$scope.parentEntity||deviation.GuidWorkOrder===$scope.guid)},$scope.$watch("reload",function(newValue,oldValue){$scope.reload&&!0===$scope.reload&&($scope.deviationTable.reload(),$scope.reload=!1)}),$scope.columns=[{Position:1,Title:translationService.translate("web-estate-id"),Property:"Estate.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-estate-description"),Property:"Estate.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-building-id"),Property:"Building.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-building-description"),Property:"Building.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-area-id"),Property:"Area.Id",PropertyType:"string"},{Position:6,Title:translationService.translate("web-area-description"),Property:"Area.Description",PropertyType:"string"},{Position:7,Title:translationService.translate("web-equipment-id"),Property:"Equipment.Id",PropertyType:"string"},{Position:8,Title:translationService.translate("web-equipment-description"),Property:"Equipment.Description",PropertyType:"string"},{Position:9,Title:translationService.translate("web-deviationType-id"),Property:"DeviationType.Id",PropertyType:"string"},{Position:10,Title:translationService.translate("web-deviationType-description"),Property:"DeviationType.Description",PropertyType:"string"},{Position:11,Title:translationService.translate("web-deviation-actioncomment","Kommentar"),Property:"ActionComment"},{Position:12,Title:translationService.translate("web-deviation-deadlinedate","Fristdato"),Property:"DeadlineDate",PropertyType:"date"},{Position:13,Title:translationService.translate("web-deviation-enddate","Lukket dato"),Property:"EndDate",PropertyType:"date"},{Position:14,Title:translationService.translate("web-deviation-status","Status"),Property:"Status",PropertyType:"string"}],$scope.getLowestEntityCaption=function(deviation){return deviation.Equipment?$rootScope.getEntityCaption(deviation.Equipment):deviation.Area?$rootScope.getEntityCaption(deviation.Area):deviation.Building?$rootScope.getEntityCaption(deviation.Building):deviation.Estate?$rootScope.getEntityCaption(deviation.Estate):void 0},$scope.getEntityCaption=function(object){return $rootScope.getEntityCaption(object)},$scope.getEntityIcon=function(deviation){return deviation.Equipment?"fa-gear c-bluegray":deviation.Area?"fa-layer-group c-lightblue":deviation.Building?"fa-building-columns c-brown":deviation.Estate?"fa-city c-teal":void 0},$scope.getStatusColor=function(status){switch(status){case"New":return"info";case"InWorks":return"warning";case"Closed":return"success";case"Canceled":return"danger";default:return}},$scope.deviationIsOverDeadline=function(deadlineDate){return!!moment(deadlineDate).isBefore(moment())},$scope.deviationTable=new ngTableParams({page:1,count:5,sorting:{Status:"asc",DeadlineDate:"asc"}},{total:0,counts:[5,10,20],filterDelay:50,paginationMaxBlocks:$scope.useList?6:8,getData:function($defer,params){var filter={PropertyFilter:[],SearchString:params.filter().searchString};if("WorkOrder"===$scope.parentEntity?filter.GuidWorkOrder=$scope.guid:filter.PropertyFilter=[{Property:"Guid"+$scope.parentEntity,Operator:"=",Value:$scope.guid}],"open"===$scope.currentSelectedFilterType.value?filter.active=!0:"closed"===$scope.currentSelectedFilterType.value&&filter.PropertyFilter.push({Property:"Status",Operator:"=",Value:"3"}),filter.PropertyFilter||filter.GuidWorkOrder){$scope.deviationsIsLoading=!0;var columns=[];$scope.columns.forEach(function(col){columns.push(col.Property)}),columns.push("Id"),columns.push("ImageCount"),columns.push("DocumentCount"),columns.push("EntityCommentCount"),repository.GetPaginated(repository.apiData.deviation.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){if($scope.deviationTable.settings().total=result.TotalCount,$scope.deviationTable.settings().filterDelay=500,$scope.deviations||($scope.deviations=[]),$scope.deviations)for(;$scope.deviations.length>0;)$scope.deviations.pop();result.List.forEach(function(deviation){$scope.deviations.push(deviation)}),$defer.resolve(result.List),$scope.deviationsIsLoading=!1},function(error){repository.growl(error,"danger")})}}}),$scope.setFilter=function(filterTypeValue){var selectedFilterType=_.find(filterTypes,{value:filterTypeValue});selectedFilterType&&filterTypeValue!==$scope.currentSelectedFilterType.value&&($scope.currentSelectedFilterType=selectedFilterType,$scope.deviationTable.reload())},$scope.create=function(){$modal.open({templateUrl:"app/deviation/views/editDeviationModal.html",controller:"DeviationController",resolve:{$stateParams:function(){var params={guid:"",isModal:!0,parentEntity:$scope.parentEntity,disableEntityInput:$scope.parentEntity&&"WorkOrder"!==$scope.parentEntity};return $scope.building&&(params.building={Caption:$scope.getEntityCaption($scope.building),guid:$scope.building.Guid}),$scope.estate&&(params.estate={Caption:$scope.getEntityCaption($scope.estate),guid:$scope.estate.Guid}),$scope.equipment&&(params.equipment={Caption:$scope.getEntityCaption($scope.equipment),guid:$scope.equipment.Guid}),$scope.area&&(params.area={Caption:$scope.getEntityCaption($scope.area),guid:$scope.area.Guid}),"WorkOrder"===$scope.parentEntity&&(params.GuidInspectionWorkOrder=$scope.guid),params}}}).result.then(function(){$scope.deviationTable.reload()},function(){$scope.deviationTable.reload()})},$scope.update=function(deviation){$modal.open({templateUrl:"app/deviation/views/editDeviationModal.html",controller:"DeviationController",resolve:{$stateParams:function(){return{guid:deviation.Guid,isModal:!0,parentEntity:$scope.parentEntity}}}}).result.then(function(){$scope.deviationTable.reload()},function(){})},$scope.closeDeviation=function(deviation){swal({title:translationService.translate("web-swal-close-Deviation","Bekreft lukking av avvik"),text:translationService.translate("web-swal-close-Deviation-message","Er avviket klar til å bli lukket?"),type:"info",showCancelButton:!0,confirmButtonColor:"#2196f3",confirmButtonText:translationService.translate("web-swal-deviation-button-confirm","Ja, Lukk avviket!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.runAction(repository.apiData.deviation.endpoint.close+deviation.Guid).then(function(result){swal(translationService.translate("web-swal-deviation-success","Avviket ble lukket!"),"","success"),deviation.Status="Closed",$scope.deviationTable.reload()},function(error){repository.growl(error,"danger")})})},$scope.createWorkOrder=function(deviation){deviationService.createWorkOrder(deviation)},$scope.remove=function(deviation){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-workOrder-deviation-message","Avviket vil bli fjernet fra arbeidsordren!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-workOrder-deviation-button-confirm","Ja, fjern avviket!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.runAction(repository.apiData.deviation.endpoint.resetCorrectiveWorkOrder+deviation.Guid).then(function(result){swal(translationService.translate("web-swal-workOrder-deviation-success","Avviket ble fjernet fra arbeidsordre!"),"Id -"+result.Caption,"success"),$scope.deviationTable.reload()},function(error){swal("Error",error,"error")})})},$scope.connectDeviation=function(){var columns=[{Position:1,Title:translationService.translate("web-deviation-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-deviation-deviationtype"),Property:"DeviationType.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-equipment-id"),Property:"Equipment.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-equipment-description"),Property:"Equipment.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-building-id"),Property:"Building.Id",PropertyType:"string"},{Position:6,Title:translationService.translate("web-building-description"),Property:"Building.Description",PropertyType:"string"},{Position:7,Title:translationService.translate("web-estate-id"),Property:"Estate.Id",PropertyType:"string"},{Position:8,Title:translationService.translate("web-estate-description"),Property:"Estate.Description",PropertyType:"string"},{Position:9,Title:translationService.translate("web-deviation-actioncomment"),Property:"ActionComment",PropertyType:"string"},{Property:"Remarks",Hidden:!0},{Property:"StartDate",Hidden:!0},{Property:"DeadlineDate",Hidden:!0},{Property:"ReportedEndDate",Hidden:!0},{Property:"EndDate",Hidden:!0},{Property:"Status",Hidden:!0},{Property:"StatusComment",Hidden:!0}],propertyFilter=[{Property:"GuidCorrectiveWorkOrder",Operator:"=",Value:null},{Property:"Status",Operator:"=",Value:0}];$localStorage.generalOptions.InspectedEntityLocation===Constants.inspectedEntityLocation.estate?(propertyFilter.push({Property:"GuidEstate",Operator:"=",Value:$scope.estate.Guid,allowToggle:!0,isDisabled:!1,filterValue:$scope.estate.Caption}),propertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:$scope.building.Guid,allowToggle:!0,isDisabled:!0,filterValue:$scope.building.Caption})):$localStorage.generalOptions.InspectedEntityLocation===Constants.inspectedEntityLocation.building?(propertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:$scope.building.Guid,allowToggle:!0,isDisabled:!1,filterValue:$scope.building.Caption}),propertyFilter.push({Property:"GuidEstate",Operator:"=",Value:$scope.estate.Guid,allowToggle:!0,isDisabled:!0,filterValue:$scope.estate.Caption})):(propertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:$scope.building.Guid,allowToggle:!0,isDisabled:!0,filterValue:$scope.building.Caption}),propertyFilter.push({Property:"GuidEstate",Operator:"=",Value:$scope.estate.Guid,allowToggle:!0,isDisabled:!0,filterValue:$scope.estate.Caption})),$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:translationService.translate("web-deviation-choose","Velg avvik"),columns:columns,useObjects:!0,url:repository.apiData.deviation.url,sorting:{Id:"asc"},filter:{PropertyFilter:propertyFilter}}}}}).result.then(function(deviations){deviations.length>0&&(deviationList=[],deviations.forEach(function(deviation){deviation.GuidCorrectiveWorkOrder=$scope.guid,deviationList.push(deviation)}),repository.updateMultiple(repository.apiData.deviation.url,deviationList).then(function(){repository.growl(translationService.translate("deviationList-addMultiple-success","Avvikene har blitt lagt til"),"success"),$scope.deviationTable.reload()},function(error){repository.growl(error,"danger"),$scope.deviationTable.reload()}))})},$scope.$on($rootScope.events.newSelection,function(){$scope.deviationTable.reload(),updateAccess()})}angular.module("Plania").directive("deviationDirective",function(){return{restrict:"E",scope:{isCollapsed:"=isCollapsed",reload:"=reload",deviations:"=deviations",disableActions:"=disableActions",estate:"=estate",building:"=building",area:"=area",equipment:"=equipment",parentEntity:"=parentEntity",guid:"=guid",restrictEdit:"=restrictEdit",showConnection:"@",useList:"=useList",inline:"=inline"},controller:["$scope","$modal","ngTableParams","Repository","$rootScope","TranslationService","$localStorage","Constants","DeviationService",controller],link:function(scope,element,attrs){},templateUrl:"app/deviation/views/deviationDirective.html"}})}(),function(){function deviationService(repository,translationService,$rootScope){var service={},getWoDefaultDescription=function(model){var deviationDesc=model.Id;return model.DeviationType&&model.DeviationType.Id&&(deviationDesc=model.Id+" - "+model.DeviationType.Id),translationService.translate("deviation-new-workOrder-description","Utbedring av")+" "+deviationDesc};return service.createWorkOrder=function(deviation){if(deviation.GuidCorrectiveWorkOrder)return void swal("Feilmelding","Du kan ikke generere arbeidsordre på et avvik som allerede har en arbeidsordre generert.","error");var estate=deviation.GuidEstate&&deviation.Estate?deviation.Estate.Caption:"",building=deviation.GuidBuilding&&deviation.Building?deviation.Building.Caption:"",equipment=deviation.GuidEquipment&&deviation.Equipment?deviation.Equipment.Caption:"",area=deviation.GuidArea&&deviation.Area?deviation.Area.Caption:"";repository.persistedData.setPersistedData("workOrder.create",{guidEstate:deviation.GuidEstate,estate:estate,guidBuilding:deviation.GuidBuilding,building:building,guidEquipment:deviation.GuidEquipment,equipment:equipment,guidArea:deviation.GuidArea,area:area,guidSelections:[deviation.Guid],fromDeviation:!0,fromCondition:!1,defaultDescription:getWoDefaultDescription(deviation),defaultText:deviation.ActionComment}),$rootScope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})},service}angular.module("Plania").factory("DeviationService",["Repository","TranslationService","$rootScope",deviationService])}(),function(){function controller($scope,repository,$stateParams,translationService,ngTableParams,$modal,listService,$localStorage){$scope.isUpdate="deviationType.edit"===$scope.navigation.current.name;var isOnCommonDataOwner,updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Deviation,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Deviation,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Deviation),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Deviation)};$scope.isUpdate?repository.getSingle(repository.apiData.deviationType.url,$stateParams.guid).then(function(response){$scope.model=response.Data,isOnCommonDataOwner=$localStorage.generalOptions.GuidCommonDataOwner===$scope.model.GuidDataOwner,$scope.fieldRules=response.FieldRules,$scope.reload=!0,updateAccess(),$scope.model.Recurrence&&($scope.rrule=RRule.fromString($scope.model.Recurrence))},function(error){repository.growl(error,"danger")}):repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix.DeviationType).then(function(result){$scope.fieldRules=result,$scope.reload=!0}),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-deviationType-success","Avvik har blitt oppdatert."):translationService.translate("create-deviationType-success","Avvik har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.deviationType.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.deviationType.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?")+(isOnCommonDataOwner?" (avvikstypen kan være i bruk på flere klienter)":""),text:translationService.translate("web-swal-deviationType-message","Avvik vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-deviationType-button-confirm","Ja, fjern Avvikstypen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.deviationType.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-deviationType-success","Avvikstypen ble fjernet!"),result,"success"),$scope.goBack("deviationType.list",{menuGuid:$scope.navigation.params.menuGuid})},function(error){var swalMessage=error.Message;error.IsDeactivateable&&(swalMessage+="

    Vil du deaktivere avvikstypen?"),swal({title:"Kunne ikke slette avvikstypen!",text:swalMessage,type:"error",html:!0,showCancelButton:!0,confirmButtonText:error.IsDeactivateable?"Deaktiver":"Ok",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.IsDeactivated=!0,$scope.model.Id=("#"+$scope.model.Id).substring(0,20),$scope.update("deviationType.list"))})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("DeviationTypeController",["$scope","Repository","$stateParams","TranslationService","ngTableParams","$modal","ListService","$localStorage",controller])}(),function(){function controller($scope,$modalInstance,parentParams,repository,ngTableParams,config,$filter,translationService,documentService){$scope.activateAutocomplete=!1,$scope.columns=[{Position:1,Title:translationService.translate("web-document-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-document-description"),Property:"Description",PropertyType:"string"}],$scope.documentsTable=new ngTableParams({page:1,count:10,sorting:{id:"asc"},filter:{isBuildingDependent:!1}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){var columns=_.map($scope.columns,function(item){return item.Property});repository.GetPaginated(repository.apiData.document.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){params.total(result.TotalCount);var sortedResult=params.sorting()?$filter("orderBy")(result.List,params.orderBy()):result.List;$defer.resolve(sortedResult),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})}}),$scope.documentUrl=config.baseUrlApi+"documentData/",$scope.selectedDocuments=[],$scope.saveDocument=function(){if(0===$scope.selectedDocuments.length)return void swal("Ingen valg",translationService.translate("web-addExistingDocument-saveDocument-emptySelection","Ingen dokumenter valgt. Velg en eller flere rader fra listen for å koble til ekisterende dokument."),"error");var documentXEntities=[];$scope.selectedDocuments.forEach(function(guid){documentXEntities.push({GuidDocument:guid,GuidEquipment:parentParams.guidEquipment,GuidArea:parentParams.guidArea,GuidWorkOrder:parentParams.guidWorkOrder,GuidBuilding:parentParams.guidBuilding,GuidEstate:parentParams.guidEstate,GuidCleaningTask:parentParams.guidCleaningTask,GuidCustomer:parentParams.guidCustomer,GuidRequest:parentParams.guidRequest,GuidPeriodicTask:parentParams.guidPeriodicTask,GuidPurchaseOrder:parentParams.guidPurchaseOrder,GuidCondition:parentParams.guidCondition,GuidDeviation:parentParams.guidDeviation,GuidComponent:parentParams.guidComponent,GuidSupplier:parentParams.guidSupplier,GuidProject:parentParams.guidProject,GuidCost:parentParams.guidCost,GuidPaymentOrder:parentParams.guidPaymentOrder,GuidContract:parentParams.guidContract,Entity:-1})}),repository.createMultiple(repository.apiData.documentXEntity.url,documentXEntities).then(function(result){repository.growl("Dokumentene har blitt lagt til","success"),$modalInstance.close("OK")}).catch(function(error){repository.growl(error,"danger")})},$scope.addDocument=function(guid){if(_.contains($scope.selectedDocuments,guid))for(var i=0;i<$scope.selectedDocuments.length;i++){var p=$scope.selectedDocuments[i];if(p===guid)return void $scope.selectedDocuments.splice(i,1)}else $scope.selectedDocuments.push(guid)},$scope.isDocumentSelected=function(guid){return _.contains($scope.selectedDocuments,guid)},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.openDocument=function(document){documentService.openDocument(document)},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"documentCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}return filter}}angular.module("Plania").controller("AddExistingDocumentController",["$scope","$modalInstance","params","Repository","ngTableParams","config","$filter","TranslationService","DocumentService",controller])}(),function(){function controller($scope,repository,$modalInstance,translationService){$scope.model={},$scope.isDynamicPropertiesCollapsed=!1,$scope.createDocumentXEntity=!1;var xrefProperty,xrefGuid,selectedDataOwner=repository.commonService.getFilterData().selectedDataOwner;selectedDataOwner.GuidDefaultDocumentType&&($scope.model.DocumentType={Guid:selectedDataOwner.GuidDefaultDocumentType,Caption:selectedDataOwner.DefaultDocumentTypeId},$scope.model.GuidDocumentType=selectedDataOwner.GuidDefaultDocumentType),$scope.checkbox={isRegulatoryCompilanceDocumentation:!1,isAttestationDocumentation:!1,isDescriptionDocumentation:!1,isOperationDocumentation:!1,isMaintenanceDocumentation:!1,isProductInfoDocumentation:!1,isInstructionDocumentation:!1,isProtocolDocumentation:!1,isIdentificationDocumentation:!1,isDrawingDocumentation:!1,isImageDocumentation:!1};var getCheckbox=function(){var checkbox=0;return $scope.checkbox.isRegulatoryCompilanceDocumentation&&(checkbox|=1),$scope.checkbox.isAttestationDocumentation&&(checkbox|=2),$scope.checkbox.isDescriptionDocumentation&&(checkbox|=4),$scope.checkbox.isOperationDocumentation&&(checkbox|=8),$scope.checkbox.isMaintenanceDocumentation&&(checkbox|=16),$scope.checkbox.isProductInfoDocumentation&&(checkbox|=32),$scope.checkbox.isInstructionDocumentation&&(checkbox|=64),$scope.checkbox.isProtocolDocumentation&&(checkbox|=128),$scope.checkbox.isIdentificationDocumentation&&(checkbox|=256),$scope.checkbox.isDrawingDocumentation&&(checkbox|=512),$scope.checkbox.isImageDocumentation&&(checkbox|=1024),checkbox};$scope.files=[],$scope.onFileSelect=function($files){$scope.files=$scope.files.concat($files)},$scope.removeFile=function(index){$scope.files.splice(index,1)},$scope.dragOverClass=function($event){var items=$event.dataTransfer.items,hasFile=!1;if(items){for(var i=0;i0){var xRefsCreated=0;savedFiles.forEach(function(file){var documentXEntity={GuidDocument:file,Entity:-1};documentXEntity["Guid"+xrefProperty]=xrefGuid,repository.createMultiple(repository.apiData.documentXEntity.url,[documentXEntity]).then(function(result){$scope.isUploading=!1,++xRefsCreated>=savedFiles.length&&$modalInstance.close(savedFiles)},function(error){repository.growl(error,"danger"),$scope.isUploading=!1})})}else $scope.isUploading=!1,allFilesUploaded&&$modalInstance.close(savedFiles)},function(error){repository.growl(error[0].error,"danger"),$scope.isUploading=!1,error.forEach(function(error){var identifiedFile=_.find($scope.files,function(f){return f.id===error.id});identifiedFile&&(identifiedFile.progressType="danger")})},function(file){var identifiedFile=_.find($scope.files,function(f){return f.id===file.id});identifiedFile&&(identifiedFile.total=file.total,identifiedFile.count=file.count,identifiedFile.progressType=file.count>=file.total?"success":"info")})}},$scope.onDocumentCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidDocumentCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidDocumentCategory=category.Guid};$scope.ok=function(){$modalInstance.close(savedFiles)},$scope.cancel=function(){ $modalInstance.dismiss("canceled")},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"documentCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}return filter}}angular.module("Plania").controller("CreateDocumentController",["$scope","Repository","$modalInstance","TranslationService",controller])}(),function(){function controller($scope,repository,$modalInstance,params,$filter,translationService){if($scope.isLoading=!1,$scope.createDocumentXEntity=!0,$scope.isModal=!0,$scope.model={},$scope.model.GuidArea=params.guidArea||"",$scope.model.GuidBuilding=params.guidBuilding||"",$scope.model.GuidCleaningTask=params.guidCleaningTask||"",$scope.model.GuidComponent=params.guidComponent||"",$scope.model.GuidCondition=params.guidCondition||"",$scope.model.GuidDeviation=params.guidDeviation||"",$scope.model.GuidCustomer=params.guidCustomer||"",$scope.model.GuidEquipment=params.guidEquipment||"",$scope.model.GuidEstate=params.guidEstate||"",$scope.model.GuidPeriodicTask=params.guidPeriodicTask||"",$scope.model.GuidPurchaseOrder=params.guidPurchaseOrder||"",$scope.model.GuidRequest=params.guidRequest||"",$scope.model.GuidWorkOrder=params.guidWorkOrder||"",$scope.model.GuidSupplier=params.guidSupplier||"",$scope.model.GuidCost=params.guidCost||"",$scope.model.GuidPaymentOrder=params.guidPaymentOrder||"",$scope.model.GuidContract=params.guidContract||"",$scope.model.GuidControlListXEntity=params.guidControlListXEntity||"",$scope.model.GuidControlListItemAnswer=params.guidControlListItemAnswer||"",$scope.model.GuidProject=params.guidProject||"",$scope.model.GuidDoorKey=params.guidDoorKey||"",$scope.model.GuidDoorLock=params.guidDoorLock||"",params.controlListItemAnswers){$scope.groupedControlListItemAnswers=[];var currentSection=null;params.controlListItemAnswers.forEach(function(controlListItemAnswer){"SectionHeader"===controlListItemAnswer.ControlListItem.Type?currentSection=controlListItemAnswer.ControlListItem.Name:"Info"!==controlListItemAnswer.ControlListItem.Type&&(currentSection&&(controlListItemAnswer.Section=currentSection),$scope.groupedControlListItemAnswers.push(controlListItemAnswer))})}$scope.checkbox={isRegulatoryCompilanceDocumentation:!1,isAttestationDocumentation:!1,isDescriptionDocumentation:!1,isOperationDocumentation:!1,isMaintenanceDocumentation:!1,isProductInfoDocumentation:!1,isInstructionDocumentation:!1,isProtocolDocumentation:!1,isIdentificationDocumentation:!1,isDrawingDocumentation:!1,isImageDocumentation:!1};var getCheckbox=function(){var checkbox=0;return $scope.checkbox.isRegulatoryCompilanceDocumentation&&(checkbox|=1),$scope.checkbox.isAttestationDocumentation&&(checkbox|=2),$scope.checkbox.isDescriptionDocumentation&&(checkbox|=4),$scope.checkbox.isOperationDocumentation&&(checkbox|=8),$scope.checkbox.isMaintenanceDocumentation&&(checkbox|=16),$scope.checkbox.isProductInfoDocumentation&&(checkbox|=32),$scope.checkbox.isInstructionDocumentation&&(checkbox|=64),$scope.checkbox.isProtocolDocumentation&&(checkbox|=128),$scope.checkbox.isIdentificationDocumentation&&(checkbox|=256),$scope.checkbox.isDrawingDocumentation&&(checkbox|=512),$scope.checkbox.isImageDocumentation&&(checkbox|=1024),checkbox};$scope.isDynamicPropertiesCollapsed=!1;var selectedDataOwner=repository.commonService.getFilterData().selectedDataOwner;selectedDataOwner.GuidDefaultDocumentType&&($scope.model.DocumentType={Guid:selectedDataOwner.GuidDefaultDocumentType,Caption:selectedDataOwner.DefaultDocumentTypeId},$scope.model.GuidDocumentType=selectedDataOwner.GuidDefaultDocumentType),params.defaultCategory&&($scope.model.GuidDocumentCategory=params.defaultCategory.Guid||"",$scope.model.DocumentCategory={Guid:$scope.model.GuidDocumentCategory,Caption:params.defaultCategory.Name},$scope.model.GuidDocumentCategory&&repository.getSingle(repository.apiData.documentCategory.url,$scope.model.GuidDocumentCategory).then(function(result){$scope.model.DynamicProperty=result.Data.DynamicProperty},function(error){repository.growl(error,"danger")})),$scope.files=[],$scope.onFileSelect=function($files){$scope.files=$scope.files.concat($files)},$scope.dragOverClass=function($event){var items=$event.dataTransfer.items,hasFile=!1;if(items){for(var i=0;i40){var totalSizeMessage=translationService.translate("web-image-upload-tooLarge-message","Du kan ikke laste opp mer enn 40 MB om gangen. Nåværende filstørrelse:");return totalSizeMessage+=" "+$filter("number")(totalSize/1048576,2)+" MB",void swal(translationService.translate("web-image-upload-tooLarge-title","For stor filstørrelse"),totalSizeMessage,"warning")}for(var totalFiles=$scope.files.length,processedCount=0,files=[],i=0;i<$scope.files.length;i++)handleFileUpload($scope.files[i])};var getFilesToUpload=function(allFiles){var files=_.reject(allFiles,function(file){return"success"===file.progressType});return files.forEach(function(file){file.id=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,16),file.count=0,file.progressType=null}),files},hasAllFilesBeenUploaded=function(allFiles){return!_.reject(allFiles,function(file){return"success"===file.progressType}).length};$scope.uploadDocument=function(){if(!$scope.isUploading){if($scope.files.length<1&&!$scope.model.IsExternalLink)return void swal(translationService.translate("web-document-error-noFiles","Ingen filer valgt"),translationService.translate("web-document-error-nofilesdescription","Du må velge en eller flere filer for å lagre"),"info");var filesToUpload=getFilesToUpload($scope.files);$scope.model.DocumentationContext=getCheckbox(),$scope.model.IsExternalLink&&0!==$scope.model.FilePath.indexOf("http")&&($scope.model.FilePath="https://"+$scope.model.FilePath),$scope.isUploading=!0,$scope.model.prefix=repository.apiData.document.prefix,repository.createSingleWithBinary(repository.apiData.document.urlChunk,$scope.model,filesToUpload).then(function(result){repository.growl(translationService.translate("web-document-upload-success","Dokumentet har blitt lagret"),"success"),$scope.isUploading=!1,$scope.alreadyUploaded=!0,hasAllFilesBeenUploaded($scope.files)&&$scope.ok(result)},function(errors){$scope.isUploading=!1,Array.isArray(errors)?(repository.growl(errors[0].error,"danger"),errors.forEach(function(error){var identifiedFile=_.find($scope.files,function(f){return f.id===error.id});identifiedFile&&(identifiedFile.progressType="danger")})):repository.growl(errors,"danger")},function(file){var identifiedFile=_.find($scope.files,function(f){return f.id===file.id});identifiedFile&&(identifiedFile.total=file.total,identifiedFile.count=file.count,identifiedFile.progressType=file.count>=file.total?"success":"info")})}},$scope.onDocumentCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidDocumentCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidDocumentCategory=category.Guid},$scope.ok=function(result){$modalInstance.close(result)};var getUploadedFiles=function(){return _.filter($scope.files,function(file){return"success"===file.progressType})};$scope.cancel=function(){var files=getUploadedFiles();files&&files.length>0&&$scope.ok(files),$modalInstance.dismiss("canceled")},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"documentCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}return filter}}angular.module("Plania").controller("CreateDocumentXEntityController",["$scope","Repository","$modalInstance","params","$filter","TranslationService",controller])}(),function(){function controller($scope,$rootScope,repository,ngTableParams,translationService,documentService,$modal,listService,listCompressionService){function resetColumnState(){$scope.columnState=angular.copy($scope.documentationContextColumns),$scope.rowState={};for(var col in $scope.columnState)$scope.columnState[col]=!1}function modifyResultFunc(list){$scope.rowState={},resetColumnState();for(var i=0;i-1&&(row.documentationContexts[key].Checked=!0,row.documentationContexts[key].OriginalChecked=!0)}}$scope.model={},$scope.viewMode=!0,$scope.filters={PropertyFilter:[]},$scope.documentSetting={listSetup:null,listOptions:null},$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.documentationContextColumns={RegulatoryCompliance:translationService.translate("web-enum-documentationContext-regulatoryCompliance","RegulatoryCompliance"),Operation:translationService.translate("web-enum-documentationContext-operation","Operation"),Maintenance:translationService.translate("web-enum-documentationContext-maintenance","Maintenance"),Identification:translationService.translate("web-enum-documentationContext-identification","Identification"),ProductInfo:translationService.translate("web-enum-documentationContext-ProductInfo","ProductInfo"),Attestation:translationService.translate("web-enum-documentationContext-Attestation","Attestation"),Instruction:translationService.translate("web-enum-documentationContext-Instruction","Instruction"),Description:translationService.translate("web-enum-documentationContext-Description","Description"),Drawing:translationService.translate("web-enum-documentationContext-Drawing","Drawing"),Protocol:translationService.translate("web-enum-documentationContext-Protocol","Protocol"),Image:translationService.translate("web-enum-documentationContext-Image","Image")},$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},resetColumnState(),$scope.columnChecked=function(column){return $scope.columnState[column]},$scope.toggleColumn=function(column){$scope.columnState[column]=!$scope.columnState[column],_.forEach($scope.documentTable.data,function(row){row.documentationContexts[column].Checked=$scope.columnState[column]})},$scope.checkCells=function(row,docContext){var rows=_.filter($scope.documentTable.data,function(item){return row.Guid!==item.Guid&&item.GuidDocument===row.GuidDocument});_.forEach(rows,function(r){r.documentationContexts[docContext.Key].Checked=!r.documentationContexts[docContext.Key].Checked})},$scope.rowChecked=function(row){return $scope.rowState[row.GuidDocument]},$scope.toggleRow=function(row){$scope.rowState[row.GuidDocument]=!$scope.rowState[row.GuidDocument];var rows=_.filter($scope.documentTable.data,function(item){return item.GuidDocument===row.GuidDocument});_.forEach(rows,function(r){_.forEach(r.documentationContexts,function(docContext){docContext.Checked=$scope.rowState[r.GuidDocument]})})},$scope.save=function(destination){var changedRows=_.filter($scope.documentTable.data,function(row){return _.some(row.documentationContexts,function(docContext){return docContext.Checked!==docContext.OriginalChecked})});if(0!==changedRows.length){var changeList=[];_.forEach(changedRows,function(row){var docContext=_.pluck(_.filter(row.documentationContexts,function(docContext){return!0===docContext.Checked}),"Key"),summarizedDocContext=documentService.getDocumentationContext(docContext),change={Guid:row.GuidDocument,DocumentationContext:summarizedDocContext};changeList.push(change)}),repository.patch(repository.apiData.document.url,null,changeList).then(function(result){repository.growl(translationService.translate("web-document-dataAcqTable-save-success","Informasjonstyper oppdatert"),"success"),destination?$scope.goBack(destination,{menuGuid:$scope.navigation.params.menuGuid}):$scope.documentTable.reload()},function(error){repository.showError(error)})}};var urlFilter=null,filterString=repository.location.search().filter;if(filterString)try{urlFilter=listCompressionService.decodeListUri(filterString)}catch(e){repository.growl(e,"danger")}urlFilter&&(urlFilter.filter?$scope.filters=urlFilter.filter:$scope.selectedListSetup.Filter&&($scope.filters=$scope.selectedListSetup.Filter));var ignoredFilterPropertiesForShowFilter=["PropertyFilter","searchString","ActivityStatus","CleaningStatus","isBuildingDependent","isCorrectiveAction","active","IsTemplate","GetAll"];if($scope.filters)for(var filter in $scope.filters)-1===ignoredFilterPropertiesForShowFilter.indexOf(filter)&&$scope.filters[filter]&&($scope.showFilter=!0);listService.getWebListViews(null,repository.apiData.documentXEntity.prefix,!1,planiaUtils.contextIds.dataAcquisitionDocXEntity,{}).then(function(result){$scope.documentSetting.listOptions=result.listOptions,$scope.documentSetting.listSetup=result.selectedListSetup;var entityData=angular.copy(repository.apiData.documentXEntity);entityData.contextId=planiaUtils.contextIds.dataAcquisitionDocXEntity,$scope.documentTable=listService.getNgTableParams($scope.documentSetting.listSetup,$scope.navigation,entityData,null,$scope.filters,modifyResultFunc)}),$scope.$watch("documentSetting.listSetup",function(newValue,oldValue){oldValue!==newValue&&$scope.documentTable&&($scope.documentTable.$params.sorting=$scope.documentSetting.listSetup.Sorting,$scope.documentTable.reload())}),$scope.equipmentTreeViewItems=new ngTableParams({page:1,count:20,sorting:{},filter:{}},{total:0,counts:[20,50,100,200],filterDelay:10,paginationMaxBlocks:8,getData:function($defer,params){repository.GetPaginated(repository.apiData.equipment.url,params.page()-1,params.count(),{},{},null,JSON.stringify(["Id","Description"])).then(function(result){$scope.equipmentTreeViewItems.settings().total=result.TotalCount,$scope.equipmentTreeViewItems.settings().filterDelay=500,0===result.List.length&&result.TotalCount>0&&$scope.equipmentTreeViewItems.page(1),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.menuOptions=function(docXRef){var options=[];return options.push({html:' '+translationService.translate("web-listview-contextMenu-document-view","Åpne dokument siden")+"",click:function($itemScope,$event,modelValue,text,$li){$rootScope.navigation.go("document.edit",{guid:docXRef.GuidDocument})}}),options.push({html:' '+translationService.translate("web-listview-contextMenu-document-openDocument","Åpne dokument fil")+"",click:function($itemScope,$event,modelValue,text,$li){documentService.openDocument({Guid:docXRef.GuidDocument,FilePath:docXRef.Document.FilePath})}}),options.push({html:' '+translationService.translate("web-listview-contextMenu-document-openEquipment","Åpne anlegg")+"",click:function($itemScope,$event,modelValue,text,$li){$rootScope.navigation.go("equipment.edit",{guid:docXRef.GuidEquipment})}}),options}}angular.module("Plania").controller("DocumentDataAcquisitionMatrixController",["$scope","$rootScope","Repository","ngTableParams","TranslationService","DocumentService","$modal","ListService","ListCompressionService",controller])}(),function(){function controller($scope,$rootScope,repository,ngTableParams,translationService,documentService,registeredFieldService,$q){function handleDocumentData(){var deferred=$q.defer();return $scope.buildingFilter||(repository.showError("Bygg mangler"),deferred.reject("Bygg mangler")),sectionIsValid(documentDataFields)||deferred.reject("Obligatoriske felt mangler"),deferred.resolve(!0),deferred.promise}function addDocumentationContexts(row){row.documentationContexts={};for(var key in $scope.documentationContextColumns)row.documentationContexts[key]={Key:key,Value:$scope.documentationContextColumns[key],Checked:!1}}function resetColumnState(){$scope.columnState=angular.copy($scope.documentationContextColumns),$scope.rowState={};for(var col in $scope.columnState)$scope.columnState[col]=!1}$scope.model={},$scope.buildingFilter={},$scope.missingMandatoryProperties=[],$scope.uploadSummary=[],$scope.steps=[{stepIndex:1,name:"documentData",hidden:!1,title:translationService.translate("web-dataAcquisition-wizard-stepTitle-documentData","Dokumentdata"),onNextStepClicked:handleDocumentData},{stepIndex:2,name:"fileUpload",hidden:!1,title:translationService.translate("web-dataAcquisition-wizard-stepTitle-chooseFiles","Last opp filer")}],$scope.currentStep=$scope.steps[0],registeredFieldService.getRegisteredField(repository.commonService.prefix.Document).then(function(result){$scope.fieldRules=result});var building=repository.commonService.getFilterData().selectedBuilding;building.Guid&&($scope.buildingFilter.Id=building.Name,$scope.buildingFilter.Guid=building.Guid),$scope.hasError=function(field){return!(!$scope.missingMandatoryProperties.includes(field)||$scope.model[field])||!(!$scope.missingMandatoryProperties.includes(field)||!$scope.model[field])&&(_.remove($scope.missingMandatoryProperties,function(property){return property===field}),!1)};var documentDataFields=["Description","GuidDocumentType","GuidDocumentCategory","GuidSupplier"],sectionIsValid=function(fields){return $scope.missingMandatoryProperties=[],fields.forEach(function(field){_.find($scope.fieldRules,{DomainFieldName:field,Mandatory:!0})&&!$scope.model[field]&&$scope.missingMandatoryProperties.push(field)}),!($scope.missingMandatoryProperties.length>0)},setCurrentStep=function(step){$scope.currentStep=step,(void 0===$scope.completedStepIndex||$scope.completedStepIndex<$scope.currentStep.stepIndex)&&($scope.completedStepIndex=$scope.currentStep.stepIndex),void 0!==$scope.currentStep.onStepAppearing&&$scope.currentStep.onStepAppearing()},onChangeStep=function(step){if(void 0===$scope.currentStep.onNextStepClicked)return void setCurrentStep(step);$scope.currentStep.onNextStepClicked().then(function(valid){valid&&setCurrentStep(step)})};$scope.onStepClick=function(step){step.stepIndex>$scope.completedStepIndex||setCurrentStep(step)},$scope.handlePreviousStep=function(){var step=_.find($scope.steps,function(step){return step.stepIndex===$scope.currentStep.stepIndex-1});step&&setCurrentStep(step)},$scope.handleNextStep=function(){var step=_.find($scope.steps,function(step){return step.stepIndex===$scope.currentStep.stepIndex+1});step&&onChangeStep(step)},$scope.documentationContextColumns={RegulatoryCompliance:translationService.translate("web-enum-documentationContext-regulatoryCompliance","RegulatoryCompliance"),Operation:translationService.translate("web-enum-documentationContext-operation","Operation"),Maintenance:translationService.translate("web-enum-documentationContext-maintenance","Maintenance"),Identification:translationService.translate("web-enum-documentationContext-identification","Identification"),ProductInfo:translationService.translate("web-enum-documentationContext-ProductInfo","ProductInfo"),Attestation:translationService.translate("web-enum-documentationContext-Attestation","Attestation"),Instruction:translationService.translate("web-enum-documentationContext-Instruction","Instruction"),Description:translationService.translate("web-enum-documentationContext-Description","Description"),Drawing:translationService.translate("web-enum-documentationContext-Drawing","Drawing"),Protocol:translationService.translate("web-enum-documentationContext-Protocol","Protocol"),Image:translationService.translate("web-enum-documentationContext-Image","Image")},$scope.files=[];var selectedDataOwner=repository.commonService.getFilterData().selectedDataOwner;selectedDataOwner.GuidDefaultDocumentType&&($scope.model.DocumentType={Guid:selectedDataOwner.GuidDefaultDocumentType,Caption:selectedDataOwner.DefaultDocumentTypeId},$scope.model.GuidDocumentType=selectedDataOwner.GuidDefaultDocumentType),$scope.onFileSelect=function($files){$scope.files=$scope.files.concat($files),_.forEach($scope.files,function(row){addDocumentationContexts(row),$scope.rowState[row.$$hashKey]=!1})},$scope.removeFile=function(index){$scope.files.splice(index,1)},$scope.dragOverClass=function($event){var items=$event.dataTransfer.items,hasFile=!1;if(items){for(var i=0;i=file.total?"success":"info")})})}},$scope.$on("$stateChangeSuccess",function(event,toState,toParams,fromState,fromParams){$scope.fromState=fromState.name})}angular.module("Plania").controller("DocumentDataAcquisitionUploadController",["$scope","$rootScope","Repository","ngTableParams","TranslationService","DocumentService","RegisteredFieldService","$q",controller])}(),function(){angular.module("Plania").controller("EditDocumentController",["$scope","Repository","$stateParams","authService","TranslationService","DocumentService","ngTableParams","$modal","$window","$modalStack","$rootScope",function($scope,repository,params,authService,translationService,documentService,ngTableParams,$modal,$window,$modalStack,$rootScope){function getRefListData(){var getListData=function(filter,entityType,columns){$scope.hasModule("DataAcquisition")&&columns.push("DataAcquisitionStatus"),supportsArchiving($scope.model.DocumentCategory)&&(columns.push("ArchiveStatus"),columns.push("JournalId"));var table=new ngTableParams({page:1,count:10,filter:{EntityType:entityType,PropertyFilter:[{Property:"GuidDocument",Operator:"=",Value:$scope.model.Guid},filter]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){repository.GetPaginated(repository.apiData.documentXEntity.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){table.settings().total=result.TotalCount,table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}});return table};$scope.equipmentTable=getListData({Property:"GuidEquipment",Operator:"<>",Value:""},repository.apiData.equipment.prefix,["Equipment.Id","Equipment.Description","Equipment.Building.Id","Equipment.Building.Description"]),$scope.periodicTaskTable=getListData({Property:"GuidPeriodicTask",Operator:"<>",Value:""},repository.apiData.periodicTask.prefix,["PeriodicTask.Id","PeriodicTask.Description"]),$scope.componentTable=getListData({Property:"GuidComponent",Operator:"<>",Value:""},repository.apiData.component.prefix,["Component.Id","Component.Description"]),$scope.estateTable=getListData({Property:"GuidEstate",Operator:"<>",Value:""},repository.apiData.estate.prefix,["Estate.Id","Estate.Description"]),$scope.buildingTable=getListData({Property:"GuidBuilding",Operator:"<>",Value:""},repository.apiData.building.prefix,["Building.Id","Building.Description","Building.BuildingCategory.Description"]),$scope.areaTable=getListData({Property:"GuidArea",Operator:"<>",Value:""},repository.apiData.area.prefix,["Area.Id","Area.Description","Area.AreaCategory.Description"]),$scope.deviationTable=getListData({Property:"GuidDeviation",Operator:"<>",Value:""},repository.apiData.deviation.prefix,["Deviation.Id","Deviation.ActionComment","Deviation.Building.Id","Deviation.Building.Description","Deviation.Equipment.Id","Deviation.Equipment.Description"]),$scope.conditionTable=getListData({Property:"GuidCondition",Operator:"<>",Value:""},repository.apiData.condition.prefix,["Condition.Id","Condition.ActionComment","Condition.Building.Id","Condition.Building.Description","Condition.Equipment.Id","Condition.Equipment.Description"]),$scope.supplierTable=getListData({Property:"GuidSupplier",Operator:"<>",Value:""},repository.apiData.supplier.prefix,["Supplier.Id","Supplier.Description"]),$scope.requestTable=getListData({Property:"GuidRequest",Operator:"<>",Value:""},repository.apiData.request.prefix,["Request.Id","Request.Description","Request.Building.Id","Request.Building.Description"]),$scope.workOrderTable=getListData({Property:"GuidWorkOrder",Operator:"<>",Value:""},repository.apiData.workOrder.prefix,["WorkOrder.Id","WorkOrder.Description","WorkOrder.Building.Id","WorkOrder.Building.Description","WorkOrder.Status"])}$scope.update=!0,$scope.restrictEdit=!authService.hasEditAccess("Document",!1),$scope.restrictDelete=!authService.hasDeleteAccess("Document",!1),$scope.model={Guid:params.guid},$scope.activateAutocomplete=!1,$scope.isModal=params.isModal,$scope.isDynamicPropertiesCollapsed=!1,$scope.modelDto={},$scope.search={},$scope.isModal?$scope.viewMode=!1:$scope.viewMode=!!$scope.update,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var supportsArchiving=function(documentCategory){return!!documentCategory&&("Archivable"===documentCategory.ArchiveType||"AutomaticArchiving"===documentCategory.ArchiveType)};$scope.openDocument=function(document){documentService.openDocument(document)},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"documentCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}return filter},$scope.replaceDocument=function(){$modal.open({templateUrl:"app/document/views/replaceDocumentModal.html",controller:"ReplaceDocumentController",size:"md",resolve:{params:function(){return{model:$scope.model}}}}).result.then(function(filename){filename&&($scope.model.FilePath=filename)},function(){})};var reloadTable=function(prefix,all){("Equipment"===prefix||all)&&$scope.equipmentTable.reload(), ("PeriodicTask"===prefix||all)&&$scope.periodicTaskTable.reload(),("Component"===prefix||all)&&$scope.componentTable.reload(),("Area"===prefix||all)&&$scope.areaTable.reload(),("Building"===prefix||all)&&$scope.buildingTable.reload(),("Estate"===prefix||all)&&$scope.estateTable.reload(),("Deviation"===prefix||all)&&$scope.deviationTable.reload(),("Condition"===prefix||all)&&$scope.conditionTable.reload(),("Supplier"===prefix||all)&&$scope.supplierTable.reload(),("Request"===prefix||all)&&$scope.requestTable.reload(),("WorkOrder"===prefix||all)&&$scope.workOrderTable.reload()};$scope.approveAllDocumentXEntity=function(){swal({title:translationService.translate("web-swal-document-approvalAll-title","Vil du godkjenne dokument og alle referanser?"),text:translationService.translate("web-swal-equipment-approval-message",'Dokumentet og alle eksisterende referanser vil bli godkjent"'),type:"info",showCancelButton:!0,confirmButtonColor:"#337ab7",confirmButtonText:translationService.translate("web-swal-equipment-button-confirm-approval","Ja, godkjenn!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null;var success=function(result){reloadTable("Building",!0),repository.growl(translationService.translate("web-document-approveAll-sent-confirmation","Dokumentet med eksisterende referanser har blitt godkjent!"),"success")},updateError=function(result){repository.growl(result,"danger")};repository.runAction(repository.apiData.document.endpoint.approveAllDocumentXEntity+$scope.model.Guid).then(success,updateError)})},$scope.setDataAcquisitionStatus=function(xref,status,prefix){swal({title:translationService.translate("web-swal-document-setStatus-title","Vil du sette datafangst status til "+translationService.translate("web-enum-DataAcquisitionStatus-"+status,status)+"?"),text:translationService.translate("web-swal-equipment-approval-message","Status vil bli til "+translationService.translate("web-enum-DataAcquisitionStatus-"+status,status)+"!"),type:"info",showCancelButton:!0,confirmButtonColor:"#337ab7",confirmButtonText:translationService.translate("web-swal-equipment-button-confirm-set-dataAcquisitionStatus","Ja, sett status!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null;var success=function(result){reloadTable(prefix,!1),repository.growl(translationService.translate("web-document-dataAcquisition-status-updated","Status har blitt satt!"),"success")},updateError=function(result){repository.growl(result,"danger")};repository.runAction(repository.apiData.documentXEntity.endpoint.setDataAcquisitionStatus+xref.Guid,null,"status="+status).then(success,updateError)})},$scope.setArchiveStatus=function(xref,status,prefix){var properties={ArchiveStatus:status};repository.patch(repository.apiData.documentXEntity.url,xref.Guid,properties).then(function(result){reloadTable(prefix,!1),repository.growl("Arkivstatus oppdatert","success")},function(error){repository.growl(error,"danger")})},$scope.checkbox={isRegulatoryCompilanceDocumentation:!1,isAttestationDocumentation:!1,isDescriptionDocumentation:!1,isOperationDocumentation:!1,isMaintenanceDocumentation:!1,isProductInfoDocumentation:!1,isInstructionDocumentation:!1,isProtocolDocumentation:!1,isIdentificationDocumentation:!1,isDrawingDocumentation:!1,isImageDocumentation:!1};var getCheckbox=function(){var checkbox=0;return $scope.model.isRegulatoryCompilanceDocumentation&&(checkbox|=1),$scope.model.isAttestationDocumentation&&(checkbox|=2),$scope.model.isDescriptionDocumentation&&(checkbox|=4),$scope.model.isOperationDocumentation&&(checkbox|=8),$scope.model.isMaintenanceDocumentation&&(checkbox|=16),$scope.model.isProductInfoDocumentation&&(checkbox|=32),$scope.model.isInstructionDocumentation&&(checkbox|=64),$scope.model.isProtocolDocumentation&&(checkbox|=128),$scope.model.isIdentificationDocumentation&&(checkbox|=256),$scope.model.isDrawingDocumentation&&(checkbox|=512),$scope.model.isImageDocumentation&&(checkbox|=1024),checkbox},columns=["DocumentCategory.Description","DocumentType.Id","Supplier.Id","Supplier.Description","DocumentCategory.ArchiveType"];repository.getMainModel(repository.apiData.document.url,params.guid,JSON.stringify(columns)).then(function(response){var document=response.Data;$scope.reload=!0,$scope.model=document,$scope.model.Supplier&&($scope.modelDto.supplier=$scope.getEntityCaption($scope.model.Supplier));var isDocumentOtherDataOwner=repository.commonService.getFilterData().selectedDataOwner.Guid!==$scope.model.GuidDataOwner;$scope.restrictEdit=!authService.hasEditAccess("Document",isDocumentOtherDataOwner)||$scope.model.IsArchived,$scope.restrictDelete=!authService.hasDeleteAccess("Document",isDocumentOtherDataOwner)||$scope.model.IsArchived,setTimeout(function(){$scope.activateAutocomplete=!0},250),$scope.isModal||getRefListData()},function(error){repository.growl(error.Data?error.Data.message:error.Message,"danger")}),$scope.menuOptions=function(prefix,xRef,guidProperty){var options=[];return $scope.hasReadAccess(prefix)&&$rootScope.userInfo.enableWebNavigation&&options.push({html:''+translationService.translate("web-navigation-goto"+prefix,"Gå til "+translationService.translate("web-enum-prefix-"+prefix))+"",click:function(){$scope.navigation.transitionTo(prefix.charAt(0).toLowerCase()+prefix.substring(1)+".edit",{guid:xRef[guidProperty]})}}),$scope.hasDeleteAccess("DocumentXEntity",prefix,!1)&&options.push({html:''+translationService.translate("web-document-deleteXref","Slett")+"",click:function(){$scope.removeXEntity(xRef.Guid,prefix)}}),$scope.userInfo.canChangeDataAcquisitionStatus&&(options.push({html:''+translationService.translate("web-document-dataAcquisitionStatus-approve","Godkjenn")+"",click:function(){$scope.setDataAcquisitionStatus(xRef,"Approved",prefix)}}),options.push({html:''+translationService.translate("web-document-dataAcquisitionStatus-reject","Avslått")+"",click:function(){$scope.setDataAcquisitionStatus(xRef,"Rejected",prefix)}})),"Archived"===xRef.ArchiveStatus&&options.push({html:''+translationService.translate("web-document-archive-Show","Åpne i arkivsystemet")+"",click:function(){$scope.openDocumentInArchiveSystem(xRef)}}),options},$scope.editDocument=function(destination){if(!$scope.model)return void repository.growl("Could not save document","danger");$scope.model.DocumentationContext=getCheckbox(),repository.updateSingle(repository.apiData.document.url,$scope.model).then(function(){repository.growl("Dokumentet ble lagret","success"),repository.commonService.setLastRegisterGuid(destination,$scope.model.Guid),$scope.isModal?$modalStack.dismissAll(!0):$scope.goBack(destination,{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})},function(error){repository.growl("Kunne ikke lagre dokumentet - "+error,"danger")})},$scope.onDocumentCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidDocumentCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidDocumentCategory=category.Guid},$scope.cancel=function(){repository.commonService.setLastRegisterGuid("document",$scope.model.Guid),$modalStack.dismissAll()};$scope.removeDocument=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-document-message","Dokumentet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-document-button-confirm","Ja, fjern dokumentet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.document.url,$scope.model.Guid).then(function(result){"Dokumentet ble ikke slettet, grunnet bindinger."===result?swal("Feil!",result,"error"):swal("Suksess",translationService.translate("web-swal-document-success","Dokumentet ble fjernet!"),"success"),$scope.isModal?$modalStack.dismissAll():$scope.goBack("document.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.removeXEntity=function(guidXRef,prefix){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-document-xEntity-message","Referansen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-document-xEntity-button-confirm","Ja, fjern referansen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.documentXEntity.url,guidXRef).then(function(result){swal(translationService.translate("web-swal-document-xEntity-success","Referansen ble fjernet!"),result,"success"),repository.growl("Referansen har blitt fjernet","success"),reloadTable(prefix,!1)},function(error){repository.growl(error,"danger"),swal("Error!",error,"error")})})};var enhanceCreateParams=function(params){return params.filter||(params.filter={}),params.filter.FilterModel||(params.filter.FilterModel={}),params.filter.FilterModel.Condition||(params.filter.FilterModel.Condition="and"),params.filter.FilterModel.Rules||(params.filter.FilterModel.Rules=[]),params.filter.FilterModel.Rules.push({Property:"DocumentXEntities.GuidDocument",Operator:"<>",Value:$scope.model.Guid,CollectionOperator:"all"}),params},addEquipmentModalParams=enhanceCreateParams({title:"Legg til anlegg",columns:[{Title:"Byggnr.",Property:"Building.Id"},{Title:"Byggnavn",Property:"Building.Description"},{Title:"Anleggsnr",Property:"Id"},{Title:"Anleggsnavn",Property:"Description"}],url:repository.apiData.equipment.url,sorting:{Id:"asc"}}),addPeriodicTaskModalParams=enhanceCreateParams({title:"Legg til periodisk rutine",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.periodicTask.url,sorting:{Id:"asc"}}),addComponentModalParams=enhanceCreateParams({title:"Legg til Komponent",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.component.url,sorting:{Id:"asc"}}),addBuildingModalParams=enhanceCreateParams({title:"Legg til Byggning",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.building.url,sorting:{Id:"asc"},filter:{FilterModel:{Condition:"and",Rules:[{Property:"IsTemplate",Operator:"=",Value:!1}]}}}),addAreaModalParams=enhanceCreateParams({title:"Legg til Rom",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.area.url,sorting:{Id:"asc"}}),addEstateModalParams=enhanceCreateParams({title:"Legg til Eiendom",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.estate.url,sorting:{Id:"asc"}}),addDeviationModalParams=enhanceCreateParams({title:"Legg til Avvik",columns:[{Title:"Id",Property:"Id"},{Title:translationService.translate("web-deviation-actionComment"),Property:"ActionComment"},{Title:"Byggnr.",Property:"Building.Id"},{Title:"Byggnavn",Property:"Building.Description"},{Title:"Anleggsnr",Property:"Equipment.Id"},{Title:"Anleggsnavn",Property:"Equipment.Description"}],url:repository.apiData.deviation.url,sorting:{Id:"desc"}}),addConditionModalParams=enhanceCreateParams({title:"Legg til Tilstand/Tiltak",columns:[{Title:"Id",Property:"Id"},{Title:"Tiltaksbeskrivelse",Property:"ActionComment"},{Title:"Byggnr.",Property:"Building.Id"},{Title:"Byggnavn",Property:"Building.Description"},{Title:"Anleggsnr",Property:"Equipment.Id"},{Title:"Anleggsnavn",Property:"Equipment.Description"}],url:repository.apiData.condition.url,sorting:{Id:"desc"}}),addSupplierModalParams=enhanceCreateParams({title:"Legg til leverandør",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.supplier.url,sorting:{Id:"desc"}}),addRequestModalParams=enhanceCreateParams({title:"Legg til melding",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"},{Title:"Byggnr.",Property:"Building.Id"},{Title:"Byggnavn",Property:"Building.Description"}],url:repository.apiData.request.url,sorting:{Id:"desc"}}),addWorkOrderModalParams=enhanceCreateParams({title:"Legg til Arbeidsordre",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"},{Title:"Byggnr.",Property:"Building.Id"},{Title:"Byggnavn",Property:"Building.Description"}],url:repository.apiData.workOrder.url,sorting:{Id:"desc"}});$scope.openDocumentInArchiveSystem=function(xRef){$window.open(xRef.JournalId,"_blank")},$scope.addXEntity=function(entity){var size="md";"Deviation"!==entity&&"Condition"!==entity&&"Request"!==entity&&"WorkOrder"!==entity||(size="lg"),$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:size,resolve:{modalParams:function(){switch(entity){case"Equipment":return addEquipmentModalParams;case"PeriodicTask":return addPeriodicTaskModalParams;case"Component":return addComponentModalParams;case"Building":return addBuildingModalParams;case"Area":return addAreaModalParams;case"Estate":return addEstateModalParams;case"Deviation":return addDeviationModalParams;case"Condition":return addConditionModalParams;case"Supplier":return addSupplierModalParams;case"Request":return addRequestModalParams;case"WorkOrder":return addWorkOrderModalParams}}}}).result.then(function(selectedGuids){var documentXEntities=[];selectedGuids.forEach(function(guid){var xEntity={GuidDocument:$scope.model.Guid,Entity:-1};"Equipment"===entity&&(xEntity.GuidEquipment=guid),"PeriodicTask"===entity&&(xEntity.GuidPeriodicTask=guid),"Component"===entity&&(xEntity.GuidComponent=guid),"Building"===entity&&(xEntity.GuidBuilding=guid),"Area"===entity&&(xEntity.GuidArea=guid),"Estate"===entity&&(xEntity.GuidEstate=guid),"Deviation"===entity&&(xEntity.GuidDeviation=guid),"Condition"===entity&&(xEntity.GuidCondition=guid),"Supplier"===entity&&(xEntity.GuidSupplier=guid),"Request"===entity&&(xEntity.GuidRequest=guid),"WorkOrder"===entity&&(xEntity.GuidWorkOrder=guid),documentXEntities.push(xEntity)}),repository.createMultiple(repository.apiData.documentXEntity.url,documentXEntities).then(function(result){repository.growl("Referansene har blitt lagt til","success"),reloadTable(entity,!1)},function(result){repository.growl(result,"danger"),reloadTable(entity,!1)})},function(){})}}])}(),function(){function controller($scope,repository,params,authService,$modalInstance){$scope.update=!0,$scope.restrictDelete=!0,$scope.hideClose=!0,repository.getSingle(repository.apiData.document.url,params.guid).then(function(response){$scope.model=response.Data,$scope.restrictEdit=!authService.hasEditAccess("Document")},function(error){repository.growl(error.Data?error.Data.message:error.Message,"danger")}),$scope.editDocument=function(){$scope.model||repository.growl("Could not save document","danger"),repository.updateSingle(repository.apiData.document.url,$scope.model).then(function(){repository.growl("Dokumentet ble lagret","success"),$modalInstance.close("Ok")},function(error){repository.growl("Kunne ikke lagre dokumentet - "+error.message,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("EditDocumentXEntityController",["$scope","Repository","params","authService","$modalInstance",controller])}(),function(){function controller($scope,repository,params,config,$modalInstance,translationService,$localStorage){$scope.model=angular.copy(params.image),$scope.viewOnly=params.viewOnly,$scope.entityType=params.entityType,$scope.imageXEntity={},$scope.imageApiUrl=config.baseUrlApi+repository.apiData.image.url,$scope.deleteAccess=params.deleteAccess,$scope.isRunningAction=!1;var supportedAttachmentTypes=["PurchaseOrder","Request","WorkOrder"];$localStorage.generalOptions.IsBBY&&(supportedAttachmentTypes.push("Condition"),supportedAttachmentTypes.push("Deviation")),$scope.canMarkAsAttachment=$localStorage.generalOptions.CanSetDocumentAsAttachment&&supportedAttachmentTypes.includes($scope.entityType),$scope.editMode=!1,$scope.imageChanged=!1,$scope.imageSrc=$scope.imageApiUrl+$scope.model.Guid+"?"+$scope.model.timestamp;var cropper;$scope.toggleEdit=function(val){val&&"abort"===val?($scope.editMode=!1,cropper.destroy()):val?($scope.editMode=val,onLoadFunction()):($scope.editMode=val,$scope.imageChanged=!0,onEditEnd())};var onEditEnd=function(){if($scope.imageChanged){$scope.imageSrc="";var updateImageSource=new Promise(function(resolve,reject){cropper.getCroppedCanvas({imageSmoothingEnabled:!0,imageSmoothingQuality:"low"}).toBlob(function(blob){var reader=new FileReader;reader.onload=function(e){try{$scope.imageSrc=e.target.result,document.getElementById("imageCropperTarget").src=e.target.result,resolve()}catch(error){repository.growl(error)}},reader.readAsDataURL(blob)},"image/jpeg")});Promise.allSettled([updateImageSource]).then(clearCropper)}else cropper.destroy()},clearCropper=function(){cropper.destroy()},onLoadFunction=function(){var image=document.getElementById("imageCropperTarget");cropper=new Cropper(image,{viewMode:2,autoCrop:!1})};$scope.onIsDefaultChange=function(state){if(!$scope.isRunningAction&&$scope.hasEditAccess("ImageXEntity")){var urlParams="guidImage="+$scope.model.Guid+"&guidEntity="+params.guidEntity+"&state="+state;$scope.isRunningAction=!0,repository.runAction(repository.apiData.imageXEntity.endpoint.toggleIsDefault,null,urlParams,!1).then(function(result){params.onChange&&"function"==typeof params.onChange&¶ms.onChange($scope.model),$scope.isRunningAction=!1},function(error){$scope.isRunningAction=!1,$scope.model.IsStandard=!1,repository.growl(error,"danger")})}},$scope.onIsAttachmentChange=function(state){if($scope.canMarkAsAttachment&&!$scope.isRunningAction&&$scope.hasEditAccess("ImageXEntity")){var urlParams="guidImage="+$scope.model.Guid+"&guidEntity="+params.guidEntity+"&state="+state;$scope.isRunningAction=!0,repository.runAction(repository.apiData.imageXEntity.endpoint.toggleIsAttachment,null,urlParams,!1).then(function(result){params.onChange&&"function"==typeof params.onChange&¶ms.onChange($scope.model),$scope.isRunningAction=!1},function(error){$scope.isRunningAction=!1,repository.growl(error,"danger")})}},$scope.editImage=function(){var imageViewModel={ImageSrc:null,Description:$scope.model.Description};$scope.imageSrc.substr(0,$scope.imageSrc.indexOf("?"))!==$scope.imageApiUrl+$scope.model.Guid&&(imageViewModel.ImageSrc=$scope.imageSrc.substr($scope.imageSrc.indexOf("base64,")+"base64,".length)),repository.updateSingle(repository.apiData.image.url+"updateFullImage/",imageViewModel,"guid="+$scope.model.Guid).then(function(){repository.growl("Bilde ble lagret","success");var result=$scope.model;result.timestamp=(new Date).toISOString(),$modalInstance.close(result)},function(error){error.Message?repository.growl("Kunne ikke lagre bilde - "+error.Message,"danger"):repository.growl("Kunne ikke lagre bilde - "+error,"danger")})},$scope.rotateImageClockWise=function(){cropper.rotate(90),$scope.imageChanged=!0},$scope.rotateImageCounterClockWise=function(){cropper.rotate(-90),$scope.imageChanged=!0},$scope.reset=function(){cropper.reset(),cropper.replace($scope.imageApiUrl+$scope.model.Guid),$scope.imageSrc=$scope.imageApiUrl+$scope.model.Guid,document.getElementById("imageCropperTarget").src=$scope.imageApiUrl+$scope.model.Guid},$scope.deleteImage=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-image-message","Bildet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-image-button-confirm","Ja, fjern bildet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.image.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-image-success","Bildet ble fjernet!"),result,"success"),$modalInstance.close("Deleted")},function(error){error.Message?repository.growl("Kunne ikke slette bilde - "+error.Message,"danger"):repository.growl("Kunne ikke slette bilde - "+error,"danger")})})}}angular.module("Plania").controller("EditImageController",["$scope","Repository","params","config","$modalInstance","TranslationService","$localStorage",controller])}(),function(){function controller($scope,repository,$modalInstance,params,translationService){var model=params.model;$scope.files=[],$scope.onFileSelect=function($files){$scope.files=$scope.files.concat($files)},$scope.dragOverClass=function($event){var items=$event.dataTransfer.items,hasFile=!1;if(items){for(var i=0;i=file.total?"success":"info")})}},$scope.ok=function(){$modalInstance.close(null)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("ReplaceDocumentController",["$scope","Repository","$modalInstance","params","TranslationService",controller])}(),function(){function controller($scope,repository,config){$scope.isLoaded=!1;var menuParams={};$scope.navigation.params.menuGuid&&(menuParams=repository.getMenuParameters($scope.navigation.params.menuGuid));var guidDocument=menuParams.GuidDocument;repository.createSingle(repository.apiData.documentData.url,{GuidDocument:guidDocument}).then(function(result){var dataOwner=repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.documentUrl=config.baseUrlApi+repository.apiData.documentData.url+result.Data.GuidDocumentResponse+"?dataOwner="+dataOwner+"&token="+result.Data.Token,$scope.isLoaded=!0})}angular.module("Plania").controller("ViewPdfDocumentController",["$scope","Repository","config",controller])}(),function(){function controller($scope,ngTableParams,listService,repository,translationService){$scope.archiveStatusFilterList=null,$scope.newArchiveStatus=null,$scope.validNextArchiveSteps=[],$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.$watchCollection("archiveList.selectedItems",function(arrayValues){var archiveSteps=_.pluck(arrayValues,"NextValidArchiveSteps"),commonArchiveSteps=_.intersection.apply(null,archiveSteps),uniqueCommonArchiveSteps=_.uniq(commonArchiveSteps);$scope.validNextArchiveSteps=uniqueCommonArchiveSteps}),$scope.$watch("archiveStatusFilterList",function(newValue,oldValue){(newValue||oldValue)&&newValue!==oldValue&&($scope.archiveList.archiveStatusFilterList=newValue,$scope.archiveList.clearSelectedItems(),$scope.archiveList.table.reload())}),$scope.updateArchiveDocuments=function(){if(0!==$scope.archiveList.selectedItems.length){var changeList=[];$scope.archiveList.selectedItems.forEach(function(item){changeList.push({Guid:item.Guid,ArchiveStatus:$scope.newArchiveStatus})}),repository.patch(repository.apiData.documentXEntity.url,null,changeList).then(function(result){repository.growl("Arkivstatus oppdatert","success"),$scope.archiveList.table.reload(),$scope.archiveList.clearSelectedItems()},function(error){repository.growl(error,"danger")})}},$scope.setArchiveStatus=function(item,archiveStatus){var properties={ArchiveStatus:archiveStatus};repository.patch(repository.apiData.documentXEntity.url,item.Guid,properties).then(function(result){repository.growl("Arkivstatus oppdatert","success"),$scope.archiveList.table.reload()},function(error){repository.growl(error,"danger")})},$scope.archiveList=new function(){var me=this;this.apiData=repository.apiData.documentXEntity,this.jsPrefix=_.camelCase(this.apiData.prefix),this.url=this.apiData.url,this.selectedItems=[],this.allSelected=!1,this.archiveStatusFilterList=null,this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:50,sorting:{UpdatedDate:"desc"},filter:{}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];params.filter().PropertyFilter=[],params.filter().PropertyFilter.push({Property:"Document.DocumentCategory.ArchiveType",Operator:"IN",Value:"1,2"}),me.archiveStatusFilterList&&me.archiveStatusFilterList.length>0&¶ms.filter().PropertyFilter.push({Property:"ArchiveStatus",Operator:"IN",Value:me.archiveStatusFilterList.join(",")}),me.listSetup.Columns.forEach(function(col){columns.push(col.Property),col.Filter&&col.Filter.forEach(function(filter){params.filter().PropertyFilter.push(filter)})}),columns.push("ArchiveStatus"),repository.GetPaginated(me.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),this.onClick=function(item,event){var itemGuid=item.GuidDocument;$scope.navigation.go("document.edit",{guid:itemGuid,menuGuid:$scope.navigation.params.menuGuid},event)},this.selectAllRows=function(){this.allSelected?this.clearSelectedItems():this.table.data.forEach(function(row){me.isSelected(row)||me.selectItem(row)}),this.allSelected=!this.allSelected},this.clearSelectedItems=function(){_.remove(this.selectedItems,function(){return!0})},this.selectItem=function(item){_.some(this.selectedItems,function(i){return i.Guid===item.Guid})?_.remove(this.selectedItems,function(i){return i.Guid===item.Guid}):this.selectedItems.push(item)},this.isSelected=function(item){return _.find(this.selectedItems,function(i){return i.Guid===item.Guid})},this.optionsMenu=function(item){var optionsMenu=[];return item.NextValidArchiveSteps.forEach(function(archiveStep){var changeStatus=translationService.translate("web-archiveList-changeTo-helpText","Ny status:"),translation=changeStatus+" "+translationService.translate("web-enum-archivestatus-"+archiveStep,"");optionsMenu.push({html:''+translation+"",click:function(){$scope.setArchiveStatus(item,archiveStep)}})}),0===optionsMenu.length&&optionsMenu.push({html:'Ingen gyldige arkivstatuser å sette'}),optionsMenu})},listService.getWebListViews(null,this.apiData.prefix,!1,null,{}).then(function(result){me.listOptions=result.listOptions,me.listSetup=result.selectedListSetup,$scope.archiveList.initTable()})}}angular.module("Plania").controller("ArchiveListController",["$scope","ngTableParams","ListService","Repository","TranslationService",controller])}(),angular.module("Plania").factory("ActivityThemeService",["$modal","Repository","$q","TranslationService","DwgMarkerService","DwgThemeService",function($modal,repository,$q,translationService,markerService,dwgThemeService){var service={},hasActiveWorkOrder="#428bca",isOverDeadline="#d9534f",updateIndicatorColours=function(workorders){workorders.forEach(function(workOrder){var elements=$("#"+workOrder.GuidArea).children();if(elements[0]){var path=elements[0];$(path).attr("stroke",hasActiveWorkOrder),$(path).attr("fill",hasActiveWorkOrder),$(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("fill-opacity","0.3"),$(path).attr("stroke-dasharray",""),$(path).attr("stroke-linecap","");var overDeadlineDate=new Date(workOrder.DueDate);new Date>overDeadlineDate&&($(path).attr("stroke",isOverDeadline),$(path).attr("fill",isOverDeadline),$(path).attr("fill-opacity","0.3"))}})};service.hideMarkers=function(){$("#marker-coordinates").attr("visibility","hidden")},service.showMarkers=function(){$("#marker-coordinates").attr("visibility","visible")};var updateMarkers=function(areaGuids){areaGuids.forEach(function(guid){var elements=$("#"+guid).children();if(elements[0]){var path=elements[0];markerService.addRequestMarker(path,guid)}})};return service.getLegends=function(){return[{label:translationService.translate("web-dwg-legend-activity-overdeadline","AO over tidsfrist"),legendClass:"legend-danger"},{label:translationService.translate("web-dwg-legend-activity-activeWorkorder","Aktive arbeidsordre"),legendClass:"legend-primary"},{label:translationService.translate("web-dwg-legend-activity-activeRequests","Aktive meldinger"),imageSrc:"images/svg-marker.png"}]},service.onClick=function(guid,type){var deferred=$q.defer();return"marker"===type?$modal.open({templateUrl:"app/request/views/requestModal.html",controller:"RequestModalController",animation:!1,resolve:{params:function(){return{guidArea:guid}}}}).result.then(function(result){deferred.resolve({})}):$modal.open({templateUrl:"app/dwg/views/workOrderModal.html",size:"lg",controller:"DwgWorkOrderController",animation:!1,resolve:{params:function(){return{guid:guid}}}}).result.then(function(result){deferred.resolve({})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()}),deferred.promise},service.getStatus=function(areas,guidDrawing){dwgThemeService.removeCategoryLabels(areas);var filter={ActivityStatus:"Active",PropertyFilter:[{Property:"Area.GuidDrawing",Operator:"=",Value:guidDrawing}]},requestFilter={FilterModel:{Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"Status",Operator:"=",Value:"0"},{Property:"Status",Operator:"=",Value:"1"}]},{Property:"WorkOrder.EndDate",Operator:"=", Value:""},{Property:"Area.GuidDrawing",Operator:"=",Value:guidDrawing}]}};return repository.GetPaginated(repository.apiData.request.url,0,1e3,{},requestFilter,"",JSON.stringify(["Guid"])).then(function(result){dwgThemeService.removePeriodicMarkers(areas),dwgThemeService.removeRequestMarkers(areas);var areaGuids=[];result.List.forEach(function(request){_.contains(areaGuids,request.GuidArea)||areaGuids.push(request.GuidArea)}),updateMarkers(areaGuids)},function(error){repository.growl(error,"danger")}),repository.GetPaginated(repository.apiData.workOrder.url,0,1e3,{DueDate:"asc"},filter,"",JSON.stringify(["DueDate"])).then(function(result){return dwgThemeService.removeAreaIndicators(areas),updateIndicatorColours(result.List),result})},service}]),angular.module("Plania").factory("CleaningMaintenanceThemeService",["$modal","Repository","$q","TranslationService","DwgMarkerService","$rootScope","DwgThemeService",function($modal,repository,$q,translationService,markerService,$rootScope,dwgThemeService){var service={},hasCleaningToday="#2196F3",hasCleaning="#9E9E9E",isCleaningTodayCompleted="#5cb85c",hasInfectionCleaning="#FFC107",hasExitCleaning="#00BCD4",exitCleaningDischarged="#000000",hasPausedCleaning="#FF9800",updateIndicatorColours=function(statuses){statuses.forEach(function(status){for(var elements=$("#"+status.GuidArea).children(),i=0;ibeforeDeadlineDate&&($(path).attr("stroke",beforeDeadline),$(path).attr("fill",beforeDeadline),$(path).attr("fill-opacity","0.2")),new Date>overDeadlineDate&&($(path).attr("stroke",overDeadline),$(path).attr("fill",overDeadline),$(path).attr("fill-opacity","0.3"))}})};return service.setAlertDays=function(newAlertDays){alertDays=newAlertDays,updateIndicatorColours()},service.onClick=function(guid){var deferred=$q.defer(),tabs={area:{visible:$rootScope.hasReadAccess(repository.apiData.area.prefix),active:!1},controlList:{visible:!0,active:!0}};return $modal.open({templateUrl:"app/dwg/views/dwgSelectionModal.html",size:"lg",animation:!1,controller:"DwgSelectionModalController",resolve:{params:function(){return{guid:guid,tabInfo:tabs}}}}).result.then(function(result){deferred.resolve({})},function(){deferred.resolve({update:!0})}),deferred.promise},service.getStatus=function(areas,guidDrawing){dwgThemeService.removePeriodicMarkers(areas),dwgThemeService.removeRequestMarkers(areas),dwgThemeService.removeCategoryLabels(areas);var areaGuids=areas.map(function(area){return area.GuidArea});return repository.runAction(repository.apiData.controlListXEntity.endpoint.getEarliestControlListDueDates,areaGuids).then(function(result){return dwgThemeService.removeAreaIndicators(areas),statuses=result,updateIndicatorColours(),result})},service}]),angular.module("Plania").factory("DoorLockThemeService",["$modal","Repository","$q","TranslationService","DwgMarkerService","$filter","DwgThemeService",function($modal,repository,$q,translationService,markerService,$filter,dwgThemeService){var service={},hasCleaningToday="#2196F3";service.getLegends=function(){return[{label:translationService.translate("web-doorLockTheme-legend-hasDoorLock","Rom med sylindre"),legendClass:"legend-primary"}]};var updateIndicatorColours=function(groupedAreas){if(groupedAreas){Object.keys(groupedAreas).forEach(function(key){var elements=$("#"+key).children();if(elements[0]){var path=elements[0];$(path).attr("stroke-dasharray",""),$(path).attr("stroke-linecap",""),$(path).attr("stroke",hasCleaningToday),$(path).attr("fill",hasCleaningToday),$(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("fill-opacity","0.3")}})}};service.onClick=function(guid){var deferred=$q.defer(),tabs={area:{visible:repository.authService.hasReadAccess(repository.apiData.area.prefix),active:!0}};return $modal.open({templateUrl:"app/dwg/views/dwgSelectionModal.html",size:"lg",controller:"DwgSelectionModalController",animation:!1,resolve:{params:function(){return{guid:guid,tabInfo:tabs}}}}).result.then(function(result){deferred.resolve({})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()}),deferred.promise};var drawLabelOnAreas=function(groupedAreas,categoryStyle){if(groupedAreas){Object.keys(groupedAreas).forEach(function(key){var elements=$("#"+key).children();if(elements[0]){var path=elements[0];markerService.addDoorLockLabels(path,groupedAreas[key],categoryStyle)}})}};return service.getStatus=function(areas,guidDrawing,selectedDoorLocks,doorLockColors){dwgThemeService.removeAreaIndicators(areas),dwgThemeService.removeRequestMarkers(areas),dwgThemeService.removePeriodicMarkers(areas),dwgThemeService.removeEquipmentCategoryLabels(areas);var defer=$q.defer();if(!selectedDoorLocks||0===selectedDoorLocks.length)return dwgThemeService.removeDoorLockLabels(areas),$.Deferred().resolve().promise();var doorLockXAreaFilter={PropertyFilter:[{Property:"GuidDoorLock",Operator:"in",Value:selectedDoorLocks.map(function(cat){return cat.Guid}).join(",")},{Property:"Area.GuidDrawing",Operator:"=",Value:guidDrawing}]};return repository.GetPaginated(repository.apiData.doorLockXArea.url,0,-1,{"Area.Id":"asc"},doorLockXAreaFilter,null,JSON.stringify(["Id","Description","Area.Id","DoorLock.Id"])).then(function(result){dwgThemeService.removeDoorLockLabels(areas),drawLabelOnAreas($filter("groupBy")(result.List,"GuidArea"),doorLockColors),updateIndicatorColours($filter("groupBy")(result.List,"GuidArea")),defer.resolve()},function(error){defer.reject()}),defer.promise},service.selectDoorLocks=function(selectedDoorLocks,guidDrawing){var defer=$q.defer(),filterModel={Condition:"and",Rules:[{Property:"DoorLockXAreas.Area.GuidDrawing",Operator:"=",Value:guidDrawing}]};return $modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",animation:!1,resolve:{modalParams:function(){return{title:translationService.translate("web-doorLock-id","Velg sylinder"),columns:[{Title:translationService.translate("web-doorLock-id"),Property:"Id"},{Title:translationService.translate("web-doorLock-Description"),Property:"Description"}],useObjects:!0,url:repository.apiData.doorLock.url,sorting:{Description:"asc"},filter:{FilterModel:filterModel},alreadySavedGuids:function(){var selectedGuids=[];return selectedDoorLocks&&selectedDoorLocks.forEach(function(entity){selectedGuids.push(entity.Guid)}),selectedGuids}()}}}}).result.then(function(newlySelected){var returnArray=[];newlySelected.forEach(function(type){_.find(selectedDoorLocks,function(o){return o.Guid===type.Guid})||returnArray.push(type)}),defer.resolve(returnArray)},function(error){defer.reject()}),defer.promise},service}]),function(){function controller($scope,repository,stateParams,$rootScope,$location,$timeout,signalR){$scope.showNetAreal=!0,$scope.guidDrawing=stateParams.guid,$scope.alertDays=15,$scope.themeSelections=[],$scope.guidQualityControl=stateParams.guidQualityControl,$scope.guidArea=stateParams.guidArea,$scope.update=!1;var urlParams=$location.search(),preparingUpdate=!1,menuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);$scope.userInfo.guidPerson&&repository.getSingle(repository.apiData.person.url,$scope.userInfo.guidPerson).then(function(result){$scope.doesCleaningTasks=result.Data.DoesCleaningTasks,$scope.doesCleaningTasks&&($scope.isStaticTheme=!0,$scope.selectedTheme="cleaning",$timeout(function(){$location.search("theme",null),$location.search("selectedTheme",$scope.selectedTheme).replace()},150))}),menuParams.selectedTheme||stateParams.selectedTheme||urlParams.selectedTheme?($scope.isStaticTheme=!0,$scope.selectedTheme=menuParams.selectedTheme?menuParams.selectedTheme:stateParams.selectedTheme?stateParams.selectedTheme:urlParams.selectedTheme,$timeout(function(){$location.search("selectedTheme",$scope.selectedTheme).replace()},50)):stateParams.theme?($scope.selectedTheme=stateParams.theme,$timeout(function(){$location.search("theme",$scope.selectedTheme).replace()},50)):urlParams&&urlParams.theme&&($scope.selectedTheme=urlParams.theme),$scope.$watch("selectedTheme",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){$location.search("theme",newVal).replace()},50)});var updateDwg=function(){preparingUpdate||(preparingUpdate=!0,$timeout(function(){"cleaning"!==$scope.selectedTheme&&"cleaningMaintenance"!==$scope.selectedTheme&&"request"!==$scope.selectedTheme||($scope.update=!$scope.update),preparingUpdate=!1},500))};signalR.on("UpdatedAreaXCleaningTask"+$scope.guidDrawing,function(){updateDwg()}),signalR.on("UpdatedCleaningCompletion"+$scope.guidDrawing,function(){updateDwg()}),$scope.$on("$destroy",function(){signalR.off("UpdatedAreaXCleaningTask"+$scope.guidDrawing),signalR.off("UpdatedCleaningCompletion"+$scope.guidDrawing)}),window.scrollTo(0,0)}angular.module("Plania").controller("DwgController",["$scope","Repository","$stateParams","$rootScope","$location","$timeout","SignalR",controller])}(),angular.module("Plania").directive("dwg",["$injector","$state","$interval","DwgMarkerService","TranslationService",function($injector,$state,$interval,markerService,translationService){return{restrict:"E",replace:!0,scope:{showNetAreal:"=showNetAreal",guidDrawing:"=guidDrawing",showFilter:"=showFilter",selectedTheme:"=selectedTheme",isStaticTheme:"=isStaticTheme",shouldStopInterval:"=shouldStopInterval",alertDays:"=alertDays",guidQualityControl:"=guidQualityControl",highligthArea:"=highlightArea",update:"=update"},link:function(scope,element,attrs){function selectArea(guid){var path=$("#"+guid).children()[0];if(_.find(selectedAreas,{guid:guid}))for(var i=0;i"),result.BuildingCaption&&(title+=' '+result.BuildingCaption+"
    "),title+=' '+result.Id},getDrawing=function(){if(!scope.guidDrawing)return document.getElementById("dwgDrawing")&&(svgPanZoom("#dwgDrawing").destroy(),$("#dwgDrawing").svg("destroy")),void(scope.title="");repository.getSingleWithNoParameter(repository.apiData.drawing.url+scope.guidDrawing+"/svg").then(function(result){document.getElementById("dwgDrawing")&&(svgPanZoom("#dwgDrawing").destroy(),$("#dwgDrawing").svg("destroy")),scope.title=getTitle(result),drawingGuidEstate=result.GuidEstate,result.Svg&&(result=result.Svg.replace("breakPointValue&&(corner.x=cord.x,corner.y=cord.y,breakPointValue=value)}),corner}var service={},getCoordinatesFromElement=function(element){var areaPathString=$(element).attr("d").replace("Z",""),areaPaths=areaPathString.split(/(?=[LMC])/),coordinates=[],count=0;return areaPaths.forEach(function(area){if("L"===area[0]||"l"===area[0]||"M"===area[0]||"m"===area[0]){area=area.substring(1,area.length-1).trim();var xy=area.split(/[ ,]/);count++,coordinates.push({x:Number(xy[0]),y:Number(xy[1])})}}),coordinates};service.addPeriodicIcon=function(p,guidArea,progress){var center={x:0,y:0},scale=55,bBox=p.getBBox();center.x=(bBox.x+bBox.width/2)/scale,center.y=(bBox.y+bBox.height/2)/scale;var svg=$("#dwgDrawing").svg("get"),transformString="rotate(-90) scale("+-1*scale+", "+scale+") translate("+center.y+","+center.x+")",markerGroup=svg.group($("#periodicMarker-coordinates"),guidArea+"_periodicMarker",{class:"periodicMarker"}),strokePercentage=15.71*progress/100,color=progress<=50?"green":progress<=75?"yellow":"red";svg.circle(markerGroup,0,0,2.5,{fill:"transparent",stroke:color,strokeWidth:5,transform:transformString,strokeDashArray:strokePercentage+", 15.71"}),svg.circle(markerGroup,0,0,5,{fill:"transparent",stroke:"#103748",strokeWidth:1,transform:transformString})},service.addRequestMarker=function(p,guidArea){var areaPathString=$(p).attr("d").replace("Z",""),areaPaths=areaPathString.split(/(?=[LMC])/),coordinates=[],count=0;areaPaths.forEach(function(area){if("L"===area[0]||"l"===area[0]||"M"===area[0]||"m"===area[0]){area=area.substring(1,area.length-1).trim();var xy=area.split(/[ ,]/);count++,coordinates.push({x:Number(xy[0]),y:Number(xy[1])})}});var center={x:0,y:0},scale=35,bBox=p.getBBox();center.x=(bBox.x+bBox.width/2)/scale*-1,center.y=-1*((bBox.y+bBox.height/2)/scale+40);var svg=$("#dwgDrawing").svg("get"),path=svg.createPath(),transformString="rotate(180) scale("+scale+", "+scale+") translate("+center.x+","+center.y+")",markerGroup=svg.group($("#marker-coordinates"),guidArea+"_marker",{class:"marker"});svg.path(markerGroup,path.move(0,40).curveQ(0,40,-10,15).curveC(-16,-7,16,-7,10,15).curveQ(0,40,0,40),{fill:"url("+location.href+"#markerGradient)",stroke:"#103748","stroke-width":1.2,class:"marker-path",transform:transformString}),svg.circle(markerGroup,0,6,1.4,{fill:"white",stroke:"none",class:"marker-circle",transform:transformString}),svg.rect(markerGroup,-1,10,2,10,0,0,{fill:"white",stroke:"none",class:"marker-rect",transform:transformString})};var getTransformString=function(p,scale){var coordinates=getCoordinatesFromElement(p),topLeftCorner=getCorner(coordinates,"topLeft"),topLeft={x:0,y:0};return topLeft.x=topLeftCorner.x/scale+7.5,topLeft.y=-1*(topLeftCorner.y/scale-15),"rotate(180) scale("+-1*scale+", "+scale+") translate("+topLeft.x+","+topLeft.y+")"},getContainerWidthForText=function(context,longestText){return 1.1*(context.measureText(longestText).width+10)};return service.addDoorLockLabels=function(p,doorLockXArea,style){function sortFunction(a,b){return a.textb.text?1:0}var svg=$("#dwgDrawing").svg("get"),markerGroup=svg.group($("#doorlock-coordinates"),doorLockXArea[0].GuidArea+"_doorLockLabel",{class:"doorLockLabel"}),offset=12,svgText=svg.createText(),idLabels=[],longestText="";doorLockXArea.forEach(function(doorLockXArea){var icon="██ ",text=doorLockXArea.DoorLock.Id;idLabels.push({text:text,icon:icon,guidDoorLock:doorLockXArea.GuidDoorLock}),(icon+text).length>longestText.length&&(longestText=icon+text)});var scale=35,canvas=document.createElement("canvas"),context=canvas.getContext("2d");context.font="x-small FontAwesome",context.scale=scale;var width=getContainerWidthForText(context,longestText),height=offset*idLabels.length+6,transformString=getTransformString(p,scale);svg.rect(markerGroup,0,0,width,height,0,0,{fill:"white",stroke:"black","stroke-width":"0.5",transform:transformString}),idLabels.sort(sortFunction).forEach(function(item){svgText.span(item.icon,{dx:3,guidDoorLock:item.guidDoorLock,fill:style[item.guidDoorLock]}),svgText.span(item.text,{fill:"black"}),svg.text(markerGroup,null,offset,svgText,{stroke:"#103748",class:"marker-path","stroke-width":"0px","font-size":"x-small","font-family":"Inter",transform:transformString}),svgText.reset(),offset+=12})},service.addEquipmentLabels=function(p,equipments,equipmentStyle){var svg=$("#dwgDrawing").svg("get"),markerGroup=svg.group($("#"+equipments[0].GuidArea),equipments[0].GuidArea+"_equipmentLabel",{class:"equipmentLabel"}),offset=12,svgText=svg.createText(),equipmentsIdsText=[],longestText="";equipments.forEach(function(equipment){var text="██ "+equipment.Id;equipmentsIdsText.push({text:text,guid:equipment.GuidEquipmentCategory}),text.length>longestText.length&&(longestText=text)});var scale=35,canvas=document.createElement("canvas"),context=canvas.getContext("2d");context.font="x-small FontAwesome",context.scale=scale;var width=getContainerWidthForText(context,longestText),height=offset*equipmentsIdsText.length+6,transformString=getTransformString(p,scale);svg.rect(markerGroup,0,0,width,height,0,0,{fill:"white",stroke:"black","stroke-width":"0.5",transform:transformString}),equipmentsIdsText.forEach(function(equipment){svgText.span(equipment.text,{dx:3,guidEquipmentCategory:equipment.guid,fill:equipmentStyle[equipment.guid]}),svg.text(markerGroup,null,offset,svgText,{stroke:"#103748",class:"marker-path","stroke-width":"0px","font-size":"x-small","font-family":"Inter",transform:transformString}),svgText.reset(),offset+=12})},service.addAreaIdLabel=function(p,area){var coordinates=getCoordinatesFromElement(p),topLeft={x:0,y:0},scale=35,topLeftCorner=getCorner(coordinates,"topLeft");topLeft.x=topLeftCorner.x/scale+2,topLeft.y=-1*(topLeftCorner.y/scale-10);var svg=$("#dwgDrawing").svg("get"),transformString="rotate(180) scale("+-scale+", "+scale+") translate("+topLeft.x+","+topLeft.y+")",markerGroup=svg.group($("#areaId-label-coordinates"),area.GuidArea+"_areaIdLabel",{class:"areaIdLabel"});svg.text(markerGroup,null,null,area.AreaId,{fill:"url("+location.href+"#markerGradient)",stroke:"#103748",class:"marker-path","stroke-width":"0px","font-size":"x-small","font-family":"Inter",transform:transformString})},service}]),angular.module("Plania").directive("dwgSelection",["$injector","$interval","$rootScope","$timeout",function($injector,$interval,$rootScope,$timeout){return{restrict:"E",scope:{drawings:"=drawings",selectedDrawing:"=selectedDrawing",rotation:"=rotation",refresh:"=refresh",shouldStopInterval:"=shouldStopInterval",updateFunction:"=updateFunction"},link:function(scope){function setRefreshInterval(){scope.refresh&&(scope.refresh.interval&&scope.refresh.active?(refreshInterval&&cancelInterval(refreshInterval),refreshInterval=$interval(function(){scope.updateFunction&&"function"==typeof scope.updateFunction&&scope.updateFunction()},1e3*scope.refresh.interval),scope.$on("$destroy",function(){cancelInterval(refreshInterval)})):refreshInterval&&cancelInterval(refreshInterval))}function setRotationInterval(){scope.rotation&&(scope.rotation.interval&&scope.rotation.active?(rotationInterval&&cancelInterval(rotationInterval),rotationInterval=$interval(function(){var idx=scope.drawings.indexOf(scope.selectedDrawing);idx===scope.drawings.length-1?idx=0:idx++,scope.selectedDrawing=scope.drawings[idx],$("slick").slick("slickGoTo",idx)},1e3*scope.rotation.interval),scope.$on("$destroy",function(){cancelInterval(rotationInterval)})):rotationInterval&&cancelInterval(rotationInterval))}function cancelInterval(interval){$interval.cancel(interval),interval=void 0}var rotationInterval,refreshInterval;scope.setSelectedDrawing=function(dwg){$timeout(function(){scope.selectedDrawing=dwg,setRotationInterval()},10)},scope.responsiveSliderBreakpoints=[{breakpoint:1024,settings:{slidesToShow:3,slidesToScroll:3,infinite:!0,dots:!1}},{breakpoint:600,settings:{slidesToShow:2,slidesToScroll:2}},{breakpoint:480,settings:{slidesToShow:1,slidesToScroll:1}}],scope.hasReadAccess=$rootScope.hasReadAccess,scope.$watchGroup(["rotation.active","rotation.interval"],function(newValues,oldValues,scope){newValues[0]===oldValues[0]&&newValues[1]===oldValues[1]||setRotationInterval()}),scope.$watchGroup(["refresh.active","refresh.interval"],function(newValues,oldValues,scope){newValues[0]===oldValues[0]&&newValues[1]===oldValues[1]||setRefreshInterval()}),scope.$watch("shouldStopInterval",function(newValue,oldValue){newValue!==oldValue&&(newValue?(cancelInterval(rotationInterval),cancelInterval(refreshInterval)):(setRotationInterval(),setRefreshInterval()))}),scope.$watch("selectedDrawing",function(newValue,oldValue){newValue!==oldValue&&newValue&&scope.setSelectedDrawing(newValue)});var repository=$injector.get("Repository");scope.svg={};var drawingStates={},getDrawings=function(){scope.drawings&&scope.drawings.forEach(function(drawing){drawingStates[drawing.Guid]||(drawingStates[drawing.Guid]=!0,repository.getSingleWithNoParameter(repository.apiData.drawing.url+drawing.Guid+"/thumbnail").then(function(result){scope.svg[result.Guid]="data:image/png;base64,"+result.Thumbnail},function(error){repository.showError(error)}))})};setRotationInterval(),setRefreshInterval(),getDrawings(),scope.$watch("drawings",function(){getDrawings()}),$timeout(function(){$(".slick-slider").on("click",".slick-slide",function(){$("#"+scope.selectedDrawing.Guid+" .dwg-thumbnail").removeClass("selected");var guidDrawing=$(this).attr("id");if(guidDrawing){var drawing=scope.drawings.find(function(dwg){return dwg.Guid===guidDrawing});drawing&&scope.setSelectedDrawing(drawing)}})},100),scope.$on("$destroy",function(){$(".slick-slider").off("click",".slick-slide")})},templateUrl:"/app/dwg/views/dwgSelectionDirective.html"}}]),function(){function controller($scope,repository,params,$stateParams,modalInstance,translationService,$state,$rootScope){if($scope.model={},$scope.showChecklistList=!0,$scope.hasReadAccess=$rootScope.hasReadAccess,$stateParams.guid=params.guid,$stateParams.isModal=!0,$scope.guidArea=params.guid,$scope.task=params.task,$scope.tab=params.tabInfo,$scope.extraData=params.data,$scope.select=function(tabName){for(var key in $scope.tab)$scope.tab.hasOwnProperty(key)&&($scope.tab[key].active=!1);$scope.tab[tabName].active=!0},repository.getSingle(repository.apiData.area.url,$scope.guidArea).then(function(result){$scope.model=result.Data}),repository.getSingle(repository.apiData.person.url,$scope.userInfo.guidPerson,JSON.stringify(["ResourceGroup.Id"])).then(function(result){$scope.person=result.Data}),$scope.tab.controlList){$scope.controlListParams={guidArea:$scope.guidArea};var filter={FilterModel:{Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"WorkOrder.StartDate",Operator:"<=",Value:moment().endOf("day").toISOString()},{Property:"WorkOrder.StartDate",Operator:"=",Value:""}]},{Property:"GuidArea",Operator:"=",Value:$scope.guidArea},{Property:"GuidWorkOrder",Operator:"<>",Value:null},{Property:"WorkOrder.EndDate",Operator:"=",Value:""}]}};repository.GetPaginated(repository.apiData.controlListXEntity.url,0,10,{},filter).then(function(result){$scope.controlLists=result.List},function(error){repository.growl(error,"danger")})}$scope.checklistCompleted=function(completionParams){$scope.ok(completionParams)},$scope.ok=function(result){modalInstance.close(result)},$scope.cancel=function(){modalInstance.dismiss("cancel")},$scope.toggleParentReload=function(){$scope.parentReload=!$scope.parentReload}}angular.module("Plania").controller("DwgSelectionModalController",["$scope","Repository","params","$stateParams","$modalInstance","TranslationService","$state","$rootScope",controller])}(),angular.module("Plania").factory("DwgThemeService",["$modal","Repository","$rootScope","TranslationService","$localStorage",function($modal,repository,rootScope,translationService,$localStorage){var service={},getAreaGuids=function(areas){var guids=[];return areas&&0!==areas.length?guids=areas[0].GuidArea?areas.map(function(areaObject){return areaObject.GuidArea}):areas:guids};return service.removeAreaIndicators=function(areas){getAreaGuids(areas).forEach(function(guidArea){var path=$("#"+guidArea).children()[0];$(path).attr("fill","rgb(0,255,0)"),$(path).attr("stroke-width","0"),$(path).attr("stroke-opacity","0"),$(path).attr("fill-opacity","0"),$(path).attr("style","transition: none;")})},service.removePeriodicMarkers=function(areas){getAreaGuids(areas).forEach(function(guidArea){var markerGroup=$("#"+guidArea+"_periodicMarker")[0];markerGroup&&$("#dwgDrawing").svg("get").remove(markerGroup)})},service.removeRequestMarkers=function(areas){getAreaGuids(areas).forEach(function(guidArea){var markerGroup=$("#"+guidArea+"_marker")[0];markerGroup&&$("#dwgDrawing").svg("get").remove(markerGroup)})},service.removeAreaIdLabels=function(areas){getAreaGuids(areas).forEach(function(guidArea){var markerGroup=$("#"+guidArea+"_areaIdLabel")[0];markerGroup&&$("#dwgDrawing").svg("get").remove(markerGroup)})},service.removeEquipmentCategoryLabels=function(areas){getAreaGuids(areas).forEach(function(guidArea){var markerGroup=$("#"+guidArea+"_equipmentLabel")[0];markerGroup&&$("#dwgDrawing").svg("get").remove(markerGroup)})},service.removeDoorLockLabels=function(areas){getAreaGuids(areas).forEach(function(guidArea){var markerGroup=$("#"+guidArea+"_doorLockLabel")[0];markerGroup&&$("#dwgDrawing").svg("get").remove(markerGroup)})},service.removeCategoryLabels=function(areas){service.removeEquipmentCategoryLabels(areas),service.removeDoorLockLabels(areas)},service.getAvailableThemes=function(selectedTheme,isStaticTheme){var themes=[];if(selectedTheme&&isStaticTheme)switch(selectedTheme){case"activity":themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-activity","Vedlikehold"),value:"activity"});break;case"controlList":themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-ControlList","Kontrolliste"),value:"controlList"});break;case"cleaning":themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-Cleaning","Renhold"),value:"cleaning"});break;case"cleaningQualityControl":themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-CleaningQualityControl","INSTA-kontroll"),value:"cleaningQualityControl"});break;case"cleaningMaintenance":themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-CleaningMaintenance","Renholdsvedlikehold"),value:"cleaningMaintenance"});break;case"request":themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-CleaningRequest","Innmelding"),value:"request"});break;case"equipment":themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-equipment","Anlegg"),value:"equipment"});break;case"doorLock":themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-doorLock","Sylinder"),value:"doorLock"});break;default:themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-Standard","Standard"),value:"standard"})}else themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-Standard","Standard"),value:"standard"}),rootScope.hasModule("Activity")&&(rootScope.hasReadAccess(repository.apiData.workOrder.prefix)&&rootScope.hasReadAccess(repository.apiData.request.prefix)&&themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-activity","Vedlikehold"),value:"activity"}),rootScope.hasReadAccess(repository.apiData.deviation.prefix)&&themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-ControlList","ControlList"),value:"controlList"}),rootScope.hasReadAccess(repository.apiData.equipment.prefix)&&themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-equipment","Anlegg"),value:"equipment"}),rootScope.hasReadAccess(repository.apiData.doorLockXArea.prefix)&&themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-doorLock","Sylinder"),value:"doorLock"})),rootScope.hasModule("CleaningWeb")&&rootScope.hasReadAccess(repository.apiData.area.prefix)&&(themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-Cleaning","Renhold"),value:"cleaning"}),themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-CleaningQualityControl","INSTA-kontroll"),value:"cleaningQualityControl"}),themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-CleaningMaintenance","Renholdsvedlikehold"),value:"cleaningMaintenance"}),themes.push({label:translationService.translate("web-dwg-toolbar-selectTheme-CleaningRequest","Innmelding"),value:"request"}));return themes},service}]),function(){function controller($scope,repository,params,ngTableParams,modalInstance,translationService){$scope.model={};var columns=["Building.Id","Building.Description","Building.Estate.Id","Building.Estate.Description","Building.Estate.Guid","Building.GuidEstate"];repository.getMainModel(repository.apiData.area.url,params.guid,JSON.stringify(columns)).then(function(result){$scope.model=result.Data,$scope.workOrderTable=new ngTableParams({page:1,count:10,filter:{ActivityStatus:"Active",PropertyFilter:[{Property:"GuidArea",Operator:"=",Value:params.guid}]},sorting:{Id:"asc"}},{total:0,counts:[],paginationMaxBlocks:6,getData:function($defer,params){repository.GetPaginated(repository.apiData.workOrder.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(["Id","Description","DueDate"])).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){$scope.isLoading=!1,repository.growl(error,"danger")})}})}),$scope.addNewWorkOrder=function(){repository.persistedData.setPersistedData("workOrder.create",{guidEstate:$scope.model.Building.Estate.Guid,estate:$scope.model.Building.Estate.Id+" - "+$scope.model.Building.Estate.Description,guidBuilding:$scope.model.GuidBuilding,building:$scope.model.Building.Id+" - "+$scope.model.Building.Description,guidArea:$scope.model.Guid,area:$scope.model.Id+" - "+$scope.model.Description}),$scope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0}),$scope.ok()},$scope.navigate=function(destination,guid){$scope.ok({}),$scope.navigation.transitionTo(destination,{guid:guid})},$scope.ok=function(result){modalInstance.close(result)},$scope.cancel=function(){modalInstance.dismiss("cancel")}}angular.module("Plania").controller("DwgWorkOrderController",["$scope","Repository","params","NgTableParams","$modalInstance","TranslationService",controller])}(),angular.module("Plania").factory("EquipmentThemeService",["$modal","Repository","$q","TranslationService","DwgMarkerService","$filter","DwgThemeService",function($modal,repository,$q,translationService,markerService,$filter,dwgThemeService){var service={};service.getLegends=function(){return null},service.onClick=function(guid){var deferred=$q.defer(),tabs={area:{visible:repository.authService.hasReadAccess(repository.apiData.area.prefix),active:!0}};return $modal.open({templateUrl:"app/dwg/views/dwgSelectionModal.html",size:"lg",controller:"DwgSelectionModalController",animation:!1,resolve:{params:function(){return{guid:guid,tabInfo:tabs}}}}).result.then(function(result){deferred.resolve({})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()}),deferred.promise};var drawLabelOnAreas=function(groupedAreas,equipmentCategoryStyle){if(!groupedAreas)return!1;Object.keys(groupedAreas).forEach(function(key){var elements=$("#"+key).children();if(elements[0]){var path=elements[0];markerService.addEquipmentLabels(path,groupedAreas[key],equipmentCategoryStyle)}}),$(".equipmentLabel").on("mouseenter",function(e){}),$(".equipmentLabel").on("mouseleave",function(e){})};return service.getStatus=function(areas,guidDrawing,selectedCategories,categoryColors){dwgThemeService.removeAreaIndicators(areas),dwgThemeService.removeRequestMarkers(areas),dwgThemeService.removePeriodicMarkers(areas),dwgThemeService.removeDoorLockLabels(areas);var defer=$q.defer();if(!selectedCategories||0===selectedCategories.length)return dwgThemeService.removeEquipmentCategoryLabels(areas),$.Deferred().resolve().promise();var equipmentFilter={PropertyFilter:[{Property:"GuidEquipmentCategory",Operator:"in",Value:selectedCategories.map(function(cat){return cat.Guid}).join(",")},{Property:"Area.GuidDrawing",Operator:"=",Value:guidDrawing}]};return repository.GetPaginated(repository.apiData.equipment.url,0,-1,{"EquipmentCategory.Description":"asc"},equipmentFilter,null,JSON.stringify(["Id","Description","Area.Id"])).then(function(result){dwgThemeService.removeEquipmentCategoryLabels(areas),drawLabelOnAreas($filter("groupBy")(result.List,"GuidArea"),categoryColors),defer.resolve()},function(error){defer.reject()}),defer.promise},service.selectEquipmentCategories=function(selectedEquipmentCategories){var defer=$q.defer();return $modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",animation:!1,resolve:{modalParams:function(){return{title:"Velg anleggkategorier",columns:[{Title:translationService.translate("web-equipmentCategory-Description"),Property:"Description"}],useObjects:!0,url:repository.apiData.equipmentCategory.url,sorting:{Description:"asc"},filter:{},alreadySavedGuids:function(){var selectedGuids=[];return selectedEquipmentCategories&&selectedEquipmentCategories.forEach(function(entity){selectedGuids.push(entity.Guid)}),selectedGuids}()}}}}).result.then(function(selectedCategories){var returnArray=[];selectedCategories.forEach(function(type){_.find(selectedEquipmentCategories,function(o){return o.Guid===type.Guid })||returnArray.push(type)}),defer.resolve(returnArray)},function(error){defer.reject()}),defer.promise},service}]),angular.module("Plania").factory("RequestThemeService",["$modal","Repository","$q","DwgMarkerService","$timeout","DwgThemeService",function($modal,repository,$q,markerService,$timeout,dwgThemeService){var service={},hasExtraCleaningTask="#428bca",hasInfectionCleaning="#FFC107",hasExitCleaning="#00BCD4",exitCleaningDischarged="#000000",updateIndicatorColours=function(statuses){statuses.forEach(function(status){for(var elements=$("#"+status.GuidArea).children(),i=0;i'+url+" ")}})}}}angular.module("Plania").controller("EmailTemplateController",["$scope","Repository","$stateParams","TranslationService","$modal",controller])}(),function(){function controller($scope,$modalInstance,params,translationService,repository,ngTableParams,listService,$sce,$filter){$scope.prefix=params.prefix,$scope.body=params.body;var propertiesFromBody=[],userProperties=[],columnsFromBody=[],dottedColumns=[],customProperties=[];propertiesFromBody=$scope.body.match(/{{\s*[\w\.]+\s*}}/g),userProperties=$scope.body.match(/{{\@\s*[\w\.]+\s*}}/g),customProperties=$scope.body.match(/{{\#\s*[\w\.]+\s*}}/g),propertiesFromBody&&(columnsFromBody=propertiesFromBody.map(function(x){return x.match(/[\w\.]+/)[0]}),dottedColumns=_.filter(columnsFromBody,function(o){return-1!==o.indexOf(".")})),$scope.tabs=[{heading:translationService.translate("web-emailPreview-selectEntity","Velg objekt"),step:0},{heading:translationService.translate("web-emailPreview-preview","Forhåndsvisning"),step:1}],$scope.steps=["one","two"],$scope.step=0,$scope.isCurrentStep=function(step){return $scope.step===step},$scope.setCurrentStep=function(step){$(".tab-content").css("overflow","hidden"),setTimeout(function(){$(".tab-content").css("overflow","visible")},500),$scope.step=step};var camelCasePrefix=_.camelCase(params.prefix),url=repository.apiData[camelCasePrefix].url;$scope.entityColumns=[{Position:1,Title:"Id",Property:"Id"},{Position:2,Title:"Beskrivelse",Property:"Description"}],$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)},$scope.entityTable=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{active:!0}},{total:0,counts:[10,25,50],paginationMaxBlocks:10,getData:function($defer,params){var columns=[];$scope.entityColumns.forEach(function(column){columns.push(column.Property)}),repository.GetPaginated(url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.selectEntity=function(entity){if(!$scope.isSaving){var selectedEntity=entity;repository.getSingle(url,selectedEntity.Guid,JSON.stringify(dottedColumns)).then(function(response){$scope.model=response.Data,$scope.setCurrentStep(1)})}};var customPropertyFunctions=[{property:"#web_base_url",getValue:function(){return window.location.protocol+"//"+window.location.host}}];$scope.getEmailBodyWithValues=function(string){if(!string)return"";var properties=propertiesFromBody;properties||(properties=[]);for(var mappedProperties=properties.map(function(x){return x.match(/[\w\.]+/)[0]}),tmpString=string,i=0;i0)for(var mappedUserProperties=userProperties.map(function(x){return x.match(/[\@\w\.]+/)[0]}),j=0;j0)for(var mappedCustomProperties=customProperties.map(function(x){return x.match(/[\#\w\.]+/)[0]}),k=0;knameB?1:0}),$scope.availableFieldNames=options.filter(function(y){return y.PreFix===$scope.model.EntityType}).map(function(x){return{FieldName:x.FieldName,TranslatedFieldName:x.TranslatedFieldName}}),$scope.model.FieldName=""},function(error){repository.growl(error,"danger")})},$scope.$watch("model.EntityType",function(newVal,oldVal){params.guid||getAvailableFieldNames()}),$scope.prefillValue=function(){var item=$scope.availableList.find(function(x){return x.PreFix===$scope.model.EntityType&&x.FieldName===$scope.model.FieldName});item&&($scope.model.Value=item.Max)},getAvailableFieldNames=function(){$scope.model.FieldName="";var newAvailableFieldNames=[];newAvailableFieldNames=$scope.availableList.filter(function(y){return y.PreFix===$scope.model.EntityType}).map(function(x){return{PreFix:x.PreFix,FieldName:x.FieldName,TranslatedFieldName:x.TranslatedFieldName}}),1===newAvailableFieldNames.length&&($scope.model.FieldName=newAvailableFieldNames[0].FieldName,$scope.prefillValue()),$scope.availableFieldNames=newAvailableFieldNames.sort(function(a,b){var nameA=a.TranslatedFieldName.toUpperCase(),nameB=b.TranslatedFieldName.toUpperCase();return nameAnameB?1:0})},params.guid?getModel():($scope.model={},getAvailableEntityTypes(),updateAccess(),$scope.activateAutocomplete=!0),$scope.delete=function(){params.guid&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-entitycounter-message","Autonummereringen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-entitycounter-delete-button-confirm","Ja, fjern autonummereringen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.entityCounter.url,params.guid).then(function(result){swal(translationService.translate("web-entityCounter-deleted","Autonummerering slettet"),result,"success"),$modalInstance.close("ok")}).catch(function(error){repository.growl(error,"danger")})})},$scope.save=function(action){var saveDto=angular.copy($scope.model);delete saveDto.LinkedDataOwner,params.guid?repository.updateSingle(repository.apiData.entityCounter.url,saveDto).then(function(result){repository.growl(translationService.translate("web-entityCounter-updated","Autonummerering oppdatert"),"success"),$modalInstance.close("ok")}).catch(function(error){repository.growl(error,"danger")}):repository.createSingle(repository.apiData.entityCounter.url,saveDto).then(function(result){repository.growl(translationService.translate("web-entityCounter-created","Autonummereringen ble lagt til"),"success"),$modalInstance.close("ok")}).catch(function(error){repository.growl(error,"danger")})},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("EntityCounterModalController",["$scope","Repository","params","$modalInstance","$modal","$localStorage","TranslationService",controller])}(),function(){function controller($scope,repository,ngTableParams,translationService,$modalInstance,modalParams){$scope.prefill={Type:"Person"},$scope.isEdit=!!modalParams.guid,$scope.guidSupplier=modalParams.guidSupplier,$scope.model={GuidPurchaseOrder:modalParams.guidPurchaseOrder},$scope.isEdit&&repository.getSingle(repository.apiData.entityEmailList.url,modalParams.guid).then(function(result){$scope.model=result.Data},function(error){repository.showError(error)}),$scope.onContactPersonSelected=function(entity){if(!entity)return void($scope.model.GuidContactPerson=null);$scope.model.GuidContactPerson=entity.Guid,$scope.model.RecipientName=entity.Caption,$scope.model.RecipientEmailAddress=entity.Email,$scope.model.RecipientPhoneNumber=entity.Cellphone},$scope.onPersonSelected=function(entity){if(!entity)return void($scope.model.GuidPerson=null);$scope.model.GuidPerson=entity.Guid,$scope.model.RecipientName=entity.Caption,$scope.model.RecipientEmailAddress=entity.Email,$scope.model.RecipientPhoneNumber=entity.Cellphone},$scope.saveEmailEntityList=function(){$scope.isEdit?repository.updateSingle(repository.apiData.entityEmailList.url,$scope.model).then(function(result){repository.growl(translationService.translate("web-emailEntityListModal-updateSuccess","Epostmottaker oppdatert"),"success"),$modalInstance.close(result)},function(error){repository.showError(error)}):repository.createSingle(repository.apiData.entityEmailList.url,$scope.model).then(function(result){repository.growl(translationService.translate("web-emailEntityListModal-createSuccess","Epostmottaker lagt til"),"success"),$modalInstance.close(result)},function(error){repository.showError(error)})},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"ContactPerson":return filter.PropertyFilter=[{Property:"GuidSupplier",Operator:"=",Value:$scope.guidSupplier}],filter}return filter}}angular.module("Plania").controller("EntityEmailListModalController",["$scope","Repository","ngTableParams","TranslationService","$modalInstance","modalParams",controller])}(),function(){function controller($scope,repository,ngTableParams,translationService,$modal,listService){var initEntityHistoryTable=function(guid){$scope.entityHistoryTable||($scope.entityHistoryColumns=[{Position:1,Title:translationService.translate("web-entityHistory-fieldname","Feltnavn"),Property:"FieldName",PropertyType:"string",SortingDisabled:!0},{Position:2,Title:translationService.translate("web-entityHistory-previousValue","Fra"),Property:"PreviousValue",PropertyType:"string"},{Position:3,Title:translationService.translate("web-entityHistory-value","Til"),Property:"Value",PropertyType:"string"},{Position:4,Title:translationService.translate("web-entityHistory-updatedDate","Tidspunkt"),Property:"UpdatedDate",PropertyType:"datetime"},{Position:5,Title:translationService.translate("web-entityHistory-updatedBy","Bruker"),Property:"UserUpdatedBy.Username",PropertyType:"string"}],$scope.getPropertyValue=function(item,column){var col=column;return"FieldName"===column.Property&&(col={Position:column.Position,Title:column.Title,Property:"TranslatedFieldName",PropertyType:column.PropertyType,SortingDisabled:column.SortingDisabled}),listService.GetPropertyValue(item,col)},$scope.entityHistoryTable=new ngTableParams({page:1,count:10,sorting:{UpdatedDate:"desc",CreationDate:"desc"},filter:{PropertyFilter:[{Property:"GuidEntity",Operator:"=",Value:guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];$scope.entityHistoryColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.entityHistory.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.entityHistoryTable.settings().total=result.TotalCount,$scope.entityHistoryTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))};$scope.showEntityHistory=function(guid){initEntityHistoryTable(guid),$modal.open({templateUrl:"app/entityHistory/views/entityHistoryModal.html",scope:$scope,size:"lg"})}}angular.module("Plania").controller("EntityHistoryController",["$scope","Repository","ngTableParams","TranslationService","$modal","ListService",controller]),angular.module("Plania").controller("EntityHistoryModalController",["$scope","Repository","ngTableParams","TranslationService","modalParams","ListService",function($scope,repository,ngTableParams,translationService,modalParams,listService){$scope.entityHistoryColumns=[{Position:1,Title:translationService.translate("web-entityHistory-fieldname","Feltnavn"),Property:"FieldName",PropertyType:"string",SortingDisabled:!0},{Position:2,Title:translationService.translate("web-entityHistory-previousValue","Fra"),Property:"PreviousValue",PropertyType:"string"},{Position:3,Title:translationService.translate("web-entityHistory-value","Til"),Property:"Value",PropertyType:"string"},{Position:4,Title:translationService.translate("web-entityHistory-updatedDate","Tidspunkt"),Property:"UpdatedDate",PropertyType:"datetime"},{Position:5,Title:translationService.translate("web-entityHistory-updatedBy","Bruker"),Property:"UserUpdatedBy.Username",PropertyType:"string"}],$scope.getPropertyValue=function(item,column){var col=column;return"FieldName"===column.Property&&(col={Position:column.Position,Title:column.Title,Property:"TranslatedFieldName",PropertyType:column.PropertyType,SortingDisabled:column.SortingDisabled}),listService.GetPropertyValue(item,col)},$scope.entityHistoryTable=new ngTableParams({page:1,count:10,sorting:{UpdatedDate:"desc",CreationDate:"desc"},filter:{PropertyFilter:[{Property:"GuidEntity",Operator:"=",Value:modalParams.guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];$scope.entityHistoryColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.entityHistory.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.entityHistoryTable.settings().total=result.TotalCount,$scope.entityHistoryTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})}]),angular.module("Plania").service("EntityHistoryModalService",["$modal",function($modal){var service={};return service.showEntityHistory=function(guid){$modal.open({templateUrl:"app/entityHistory/views/entityHistoryModal.html",controller:"EntityHistoryModalController",size:"lg",resolve:{modalParams:function(){return{guid:guid}}}})},service}])}(),function(){function controller($scope,repository,$stateParams,translationService,columnFormatService,$modal){function toDictionary(arr){for(var rv={},i=0;i0?$scope.model.HttpHeaders=angular.toJson(toDictionary($scope.httpHeaders)):$scope.model.HttpHeaders=void 0,$scope.actionRule&&Object.keys($scope.actionRule).length>0?$scope.model.ActionRule=angular.toJson($scope.actionRule):$scope.model.ActionRule=void 0,$scope.columns&&$scope.columns.length>0?$scope.model.Filter=angular.toJson($scope.columns):$scope.model.Filter=void 0;var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-entityLink-success","Navigasjonslenken har blitt oppdatert."):translationService.translate("create-entityLink-success","Navigasjonslenken har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})};$scope.isUpdate?repository.updateSingle(repository.apiData.entityLink.url,$scope.model).then(success,repository.showError):repository.createSingle(repository.apiData.entityLink.url,$scope.model).then(success,repository.showError)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-entityLink-message","Navigasjonslenken vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-entityLink-button-confirm","Ja, fjern navigasjonslenken"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.entityLink.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-entityLink-success","Navigasjonslenken ble fjernet!"),result,"success"),$scope.goBack("entityLink.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.addNewFormatColumn=function(){columnFormatService.chooseColumn($scope.model,"Url",$scope.model.EntityType)},$scope.addNewColumn=function(){$modal.open({templateUrl:"app/common/views/addNewListColumnModal.html",controller:"AddNewListColumnController",resolve:{params:function(){return{prefix:$scope.model.EntityType,showAdvancedMode:!0}}}}).result.then(function(selectedColumns){selectedColumns.forEach(function(column){column.Filter=[{Operator:"=",Property:column.Property}],$scope.columns.push(column),"date"===column.PropertyType&&($scope.datePickers[column.$$hashKey]=!1)})})},$scope.$watch("model.EntityType",function(newValue,oldValue){newValue&&oldValue&&newValue!==oldValue&&$scope.model.Url&&-1!==$scope.model.Url.indexOf("[")&&($scope.model.Url="")})}angular.module("Plania").controller("EntityLinkController",["$scope","Repository","$stateParams","TranslationService","ColumnFormatService","$modal",controller])}(),function(){function controller(scope,repository){scope.collapse={isEntitiesCollapsed:!1},repository.getWithUrlParameter(repository.apiData.entityLink.url+"linksForEntity","guidEntity="+scope.guid+"&prefix="+scope.entity).then(function(result){scope.totalCount=result.length,scope.entityLinks=result},function(error){repository.showError(error)})}angular.module("Plania").directive("plEntityLinks",function(){return{restrict:"E",scope:{guid:"=guid",entity:"=entity",displayLimit:"=displayLimit"},controller:["$scope","Repository",controller],templateUrl:"app/entityLink/views/plEntityLinksDirective.html"}})}(),function(){function controller($scope,repository,$stateParams,translationService,enumService){$scope.model={Guid:$stateParams.guid},$scope.apiRequestLogColumns=[{Position:1,Title:translationService.translate("web-apiRequestLog-creationDate","Opprettet dato"),Property:"CreationDate",PropertyType:"date"},{Position:2,Title:translationService.translate("web-apiRequestLog-user-realName","Opprettet av"),Property:"UserCreatedBy.RealName",PropertyType:"string"}];var columns=["EntityLink.Id","EntityLink.Description"];repository.getMainModel(repository.apiData.entityTask.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data},function(error){repository.growl(error,"danger")});var setStatus=function(status){repository.runAction(repository.apiData.entityTask.endpoint.setStatus+$scope.model.Guid,{EntityTaskStatus:status}).then(function(response){$scope.model.Status=status},function(error){repository.growl(error,"danger")})};$scope.getContextMenu=function(){var options=[];return[{text:translationService.translate("web-entityTask-dropdownOption-setStatus-created","Sett status til opprettet"),value:"Created"},{text:translationService.translate("web-entityTask-dropdownOption-setStatus-inProgress","Sett status til under arbeid"),value:"InProgress"},{text:translationService.translate("web-entityTask-dropdownOption-setStatus-interactionRequired","Sett status til krever handling"),value:"InteractionRequired"},{text:translationService.translate("web-entityTask-dropdownOption-setStatus-error","Sett status til feil"),value:"Error"},{text:translationService.translate("web-entityTask-dropdownOption-setStatus-cancelled","Sett status til kansellert"),value:"Cancelled"},{text:translationService.translate("web-entityTask-dropdownOption-setStatus-delivered","Sett status til levert"),value:"Delivered"}].forEach(function(status){options.push({html:' '+status.text+"",click:function($itemScope,event){setStatus(status.value)}})}),options}}angular.module("Plania").controller("EntityTaskController",["$scope","Repository","$stateParams","TranslationService","EnumService",controller])}(),function(){function controller($scope,repository,ngTableParams){function initDataAcquisitionTable(resultRows){for(var rows=[],i=0;i0&&items.page(1),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})}angular.module("Plania").controller("EquipmentDataAcquisitionController",["$scope","Repository","ngTableParams",controller])}(),function(){function controller($scope,$modalInstance,parentParams,repository,ngTableParams,$filter){var oldCount=0;if(parentParams.AddComponents){var countsArray=[];$scope.componentsTable=new ngTableParams({page:1,count:10,sorting:{id:"asc"},filter:{}},{total:0,counts:countsArray,getData:function($defer,params){$scope.isLoading=!0,repository.GetPaginated(repository.apiData.component.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(["Id","Description"])).then(function(result){result.totalCount>10&&(countsArray.push(10),countsArray.push(20),countsArray.push(50)),$scope.isLoading=!1,params.total(result.TotalCount);var sortedResult=params.sorting()?$filter("orderBy")(result.List,params.orderBy()):result.List;$defer.resolve(sortedResult)},function(error){repository.growl(error,"danger")})}});var selectedComponents=[];$scope.addComponent=function(guid){if(_.contains(selectedComponents,guid))for(var i=0;i
    Vil du deaktivere anlegget?",type:"error",html:!0,showCancelButton:!0,confirmButtonText:"Deaktiver",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.IsDeactivated=!0,$scope.updateEquipment("equipment.list"))})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.update&&$rootScope.hasModule("Elhub")){var elhubIdField=$localStorage.generalOptions.EquipmentFieldForMeteringIdentifier,matchElhubMeteringPointFormat=function(id){return!(!id||18!==id.length)&&/^\d+$/.test(id)},checkElhubFunctions=function(){var status=$scope.model.ElhubStatus;$scope.showElhubStatus=status&&status!==constants.elhubStatus.undefined&&status!==constants.elhubStatus.noExport,$scope.showElhubOption=$scope.showElhubStatus||$scope.model&&matchElhubMeteringPointFormat($scope.model[elhubIdField])};checkElhubFunctions(),$scope.$watch("model.Id",function(){checkElhubFunctions()}),$scope.showElhubModal=function(){$modal.open({templateUrl:"app/equipment/views/equipmentElhubStatusModal.html",controller:"EquipmentElhubStatusModalController",resolve:{params:function(){return{elhubStatus:$scope.model.ElhubStatus}}}}).result.then(function(newElhubStatus){$scope.model.elhubStatus=newElhubStatus,$scope.updateEquipment("equipment.edit")})}}$scope.openTFMModal=function(){$modal.open({controller:"NonsReferenceModalController",templateUrl:"app/common/modal/views/nonsReferenceModal.html",size:"xxl",resolve:{params:function(){return{entityModel:$scope.model}}}}).result.then(function(nonsReference){$scope.model.NonsReference=nonsReference,$scope.model.GuidNonsReference=nonsReference.Guid})},$scope.changeId=function(){$modal.open({templateUrl:"app/common/modal/views/changeIdModal.html",controller:"ChangeIdModalController",size:"md",resolve:{params:function(){return{id:$scope.model.Id}}}}).result.then(function(id){id&&repository.patch(repository.apiData.equipment.url,$scope.model.Guid,{Id:id}).then(function(result){repository.growl(translationService.translate("web-equipment-changeId-success","Id ble oppdatert"),"success"),$scope.model.Id=id},function(error){repository.showError(error)})})}}angular.module("Plania").controller("EquipmentController",["$scope","Repository","$stateParams","$location","$modal","TranslationService","$localStorage","$rootScope","$timeout","Constants",controller])}(),function(){function controller($scope,$modalInstance,params,constants){var status=params.elhubStatus,canStart=function(status){return status===constants.elhubStatus.undefined||status===constants.elhubStatus.noExport||status===constants.elhubStatus.syncStopped||status===constants.elhubStatus.syncDenied||status===constants.elhubStatus.failed},canStop=function(status){return status===constants.elhubStatus.startedInPlania||status===constants.elhubStatus.syncApproved};canStart(status)?$scope.canStart=!0:canStop(status)?$scope.canStop=!0:$scope.pendingChange=!0,$scope.start=function(){$modalInstance.close(constants.elhubStatus.startedInPlania)},$scope.stop=function(){$modalInstance.close(constants.elhubStatus.stoppedInPlania)},$scope.cancel=function(){$modalInstance.dismiss("Canceled")}}angular.module("Plania").controller("EquipmentElhubStatusModalController",["$scope","$modalInstance","params","Constants",controller])}(),function(){function controller($scope,$timeout,$rootScope){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasEditAccess=$rootScope.hasEditAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.update&&($scope.hasPageLoaded="image"===$scope.currentTab,!$scope.hasPageLoaded))var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"image"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener())},250)})}angular.module("Plania").directive("equipmentImageDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",update:"=update"},controller:["$scope","$timeout","$rootScope",controller],templateUrl:"app/equipment/views/equipmentImage.html"}})}(),function(){function controller($scope,ngTableParams,repository,translationService,$modal,$rootScope,listService,authService,registeredFieldService,$localStorage,$timeout){$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasEditAccess=$rootScope.hasEditAccess,$scope.hasModule=$rootScope.hasModule,$scope.userInfo=$rootScope.userInfo,$scope.customization=$rootScope.customization,$scope.generalOptions=$localStorage.generalOptions,$scope.imageApiUrl=$rootScope.imageApiUrl,$scope.viewMode=!!$scope.update,$scope.isDocumentsCollapsed=!0,$scope.isDynamicPropertiesCollapsed=!1,$scope.showNonsReference=$scope.generalOptions.UseNonsReference&&$scope.update,$scope.entityCommentSearch={searchString:"",focus:!1},$scope.canSeeEntityComment=!1,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode};var updateEntityCommentVisibility=function(){return $scope.canSeeEntityComment=$scope.hasModule("DataAcquisition")&&$scope.hasModule("EntityComment")&&$scope.hasReadAccess("EntityComment")&&$scope.update,$scope.canSeeEntityComment};if(updateEntityCommentVisibility(),$scope.hasPageLoaded="info"===$scope.currentTab,!$scope.hasPageLoaded)var pageListener=$scope.$watch("currentTab",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){"info"!==newVal||$scope.hasPageLoaded||($scope.hasPageLoaded=!0,pageListener(),updateEntityCommentVisibility())},250)});if($scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidEquipmentGroup="",delete $scope.model.EquipmentGroup,$scope.model.GuidArea="",delete $scope.model.Area),$scope.model.GuidBuilding=building.Guid},$scope.onEquipmentCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidEquipmentCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidEquipmentCategory=category.Guid},$scope.onEquipmentSelect=function(equipment){if(!equipment)return void($scope.model.GuidEquipmentGroup="");$scope.model.GuidEquipmentGroup=equipment.Guid,$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=equipment.GuidBuilding,$scope.model.Building=equipment.Building),equipment.GuidArea&&($scope.model.GuidArea=equipment.GuidArea,$scope.model.Area=equipment.Area)},$scope.autoCompleteFilter=function(filterName){switch(filterName){case"equipment":var filter={GuidBuilding:$scope.model.GuidBuilding,RestrictHierarchy:!0,PropertyFilter:[{Property:"IsEquipmentGroup",Operator:"=",Value:"1"}]};return $scope.update&&filter.PropertyFilter.push({Property:"GUID",Operator:"<>",Value:$scope.model.Guid}),filter;case"area":return $localStorage.generalOptions.EqMustBeLocatedInOwnBld?{PropertyFilter:[{Property:"GuidBuilding",operator:"=",Value:$scope.model.GuidBuilding}]}:{};case"person":return{PropertyFilter:[{Property:"IsOperationsManager",Value:!0,Operator:"="}]}}return null},registeredFieldService.getRegisteredField(repository.commonService.prefix.Equipment).then(function(registeredFields){var isExternalUser=$localStorage.userData.isExternalUser,locationRule=_.filter(registeredFields,{DomainFieldName:"Location"})[0],showLocation=!!locationRule&&(!locationRule.Hidden&&(!isExternalUser||!locationRule.ExternallyHidden)),areaRule=_.filter(registeredFields,{DomainFieldName:"GuidArea"})[0],showArea=!!areaRule&&(!areaRule.Hidden&&(!isExternalUser||!areaRule.ExternallyHidden));$scope.hidePlacementSection=!showLocation&&!showArea}),$scope.update){$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)};var getMenuLink=function(url,icon,text){return{html:' '+text+"",isHref:!0}};$scope.componentInfo=new function(){var me=this;this.items=[],this.search={},this.columns=[{Position:1,Title:translationService.translate("web-component-id"),Property:"Component.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-component-description"),Property:"Component.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-componentCategory-description"),Property:"Component.ComponentCategory.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-componentxequipment-quantity","Antall"),Property:"Quantity",PropertyType:"string"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:5,sorting:{"Component.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidEquipment",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[5,10,20],paginationMaxBlocks:6,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("Note"),columns.push("Component.Guid"),columns.push("Component.GuidImage"), repository.GetPaginated(repository.apiData.componentEquipment.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.items=result.List,me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}))},this.add=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Legg til komponent",url:repository.apiData.component.url,columns:[{Title:translationService.translate("web-component-id"),Property:"Id",PropertyType:"string"},{Title:translationService.translate("web-component-description"),Property:"Description",PropertyType:"string"}],filter:{FilterModel:{Condition:"and",Rules:[{Property:"ComponentXEquipments.GuidEquipment",Operator:"<>",Value:$scope.model.Guid,CollectionOperator:"all"}]}},useObjects:!1}}}}).result.then(function(guids){var model=[];guids.forEach(function(guid){model.push({GuidEquipment:$scope.model.Guid,GuidComponent:guid})}),repository.createMultiple(repository.apiData.componentEquipment.url,model).then(function(result){me.table.reload()},function(){me.table.reload()})})},this.update=function(item){me.canEdit(item)&&$modal.open({templateUrl:"app/equipment/views/editComponentEquipment.html",controller:"EquipmentComponentController",resolve:{params:function(){return{component:item,AddComponents:!1}}}}).result.then(function(){me.table.reload()})},$scope.openTFMModal=function(){$modal.open({controller:"NonsReferenceModalController",templateUrl:"app/common/modal/views/nonsReferenceModal.html",size:"xxl",resolve:{params:function(){return{entityModel:$scope.model}}}}).result.then(function(nonsReference){$scope.model.NonsReference=nonsReference,$scope.model.GuidNonsReference=nonsReference.Guid})},this.remove=function(item){me.canDelete(item)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-equipment-component-message","Komponenten vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-equipment-component-button-confirm","Ja, fjern komponenten!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.componentEquipment.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-equipment-component-success","Komponenten ble fjernet!"),result,"success"),me.table.reload()})})},this.contextMenuOptions=function(item){var options=[];return $scope.hasReadAccess("Component")&&options.push(getMenuLink($rootScope.navigation.href("component.edit",{guid:item.GuidComponent}),"fa-arrow-right fa-hc-fw fa-hc-lg",translationService.translate("web-equipment-componentXEquipmentContextMenu-viewComponent","Gå til komponent"))),me.canEdit(item)&&options.push({html:' '+translationService.translate("web-button-edit","Rediger")+"",click:function(){me.update(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-button-delete","Slett")+"",click:function(){me.remove(item)}}),options},this.canEdit=function(item){return item&&$scope.hasEditAccess("ComponentXEquipment")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("ComponentXEquipment")},me.initTable()},$scope.conditionInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-condition-conditionType"),Property:"ConditionType.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-condition-Workorder-Id","Arbeidsordre Id"),Property:"WorkOrder.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-condition-Workorder-Description","Arbeidsordre"),Property:"WorkOrder.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-condition-CreatedBy","Opprettet av"),Property:"UserCreatedBy.RealName",PropertyType:"string"},{Position:5,Title:translationService.translate("web-condition-CreationDate","Opprettet"),Property:"CreationDate",PropertyType:"date"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{CreationDate:"desc"},filter:{PropertyFilter:[{Property:"GuidEquipment",Operator:"=",value:$scope.model.Guid},{Property:"GuidConditionType",Operator:"<>",value:null}]}},{total:0,counts:[10,20,50],filterDelay:10,paginationMaxBlocks:6,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("WorkOrder.Guid"),repository.GetPaginated(repository.apiData.condition.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}))},me.initTable()},$scope.equipmentHourInfo=new function(){var me=this;this.search={},this.columns=[{Position:1,Title:translationService.translate("web-EquipmentOperatingHours-Value","Verdi"),Property:"Value",PropertyType:"string"},{Position:2,Title:translationService.translate("web-EquipmentOperatingHours-EquipmentOperatingHourType-id","Type"),Property:"EquipmentOperatingHourType.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-EquipmentOperatingHours-ReadDate","Registrert dato"),Property:"ReadDate",PropertyType:"date"},{Position:4,Title:translationService.translate("web-EquipmentOperatingHours-CreationDate","Opprettet"),Property:"CreationDate",PropertyType:"date"},{Position:5,Title:translationService.translate("web-EquipmentOperatingHours-CreatedBy","Opprettet av"),Property:"UserCreatedBy.RealName",PropertyType:"string"}],registeredFieldService.getFieldRule(repository.commonService.prefix.equipmentOperatingHours,"GuidEquipmentOperatingHourType").then(function(result){(result.Hidden||authService.getUserData().isExternalUser&&result.ExternallyHidden)&&(me.columns=[{Position:1,Title:translationService.translate("web-EquipmentOperatingHours-Value","Verdi"),Property:"Value",PropertyType:"string"},{Position:2,Title:translationService.translate("web-EquipmentOperatingHours-ReadDate","Registrert dato"),Property:"ReadDate",PropertyType:"date"},{Position:3,Title:translationService.translate("web-EquipmentOperatingHours-CreationDate","Opprettet"),Property:"CreationDate",PropertyType:"date"},{Position:4,Title:translationService.translate("web-EquipmentOperatingHours-CreatedBy","Opprettet av"),Property:"UserCreatedBy.RealName",PropertyType:"string"}])}),this.listSetup={VisibleColumns:me.columns,Columns:me.columns,Id:$scope.model?$scope.model.Caption:""},$scope.$watch("model.Caption",function(newVal){me.listSetup.Id=newVal}),this.dropdownFilters=[{Guid:void 0,Id:"Alle"}],this.selectedDropdownFilter=me.dropdownFilters[0],this.setDropdownFilter=function(type){me.selectedDropdownFilter=type,me.table.reload()};var GetOperatingHourTypeFilters=function(){var filter={PropertyFilter:[{Property:"EquipmentOperatingHours.GuidEquipment",Operator:"=",Value:$scope.model.Guid}]};repository.GetPaginated(repository.apiData.equipmentOperatingHourType.url,0,100,{id:"asc"},filter,"",JSON.stringify(["Id"])).then(function(result){me.dropdownFilters=result.List,me.dropdownFilters.unshift({Guid:null,Id:"Uten type"}),me.dropdownFilters.unshift({Guid:void 0,Id:"Alle"})})};GetOperatingHourTypeFilters(),this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{ReadDate:"desc"},filter:{}},{total:0,counts:[10,20,50],filterDelay:10,paginationMaxBlocks:6,getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)});var filter=params.filter();filter.PropertyFilter=[{Property:"GuidEquipment",Operator:"=",value:$scope.model.Guid}],void 0!==me.selectedDropdownFilter.Guid&&filter.PropertyFilter.push({Property:"GuidEquipmentOperatingHourType",Operator:"=",value:me.selectedDropdownFilter.Guid}),repository.GetPaginated(repository.apiData.equipmentOperatingHours.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}))},this.add=function(){$modal.open({templateUrl:"app/equipment/views/equipmentOperatingHoursModal.html",controller:"EquipmentOperatingHoursController",size:"sm",resolve:{params:function(){return{GuidEquipment:$scope.model.Guid,ReadDate:new Date}}}}).result.then(function(){me.table.reload(),GetOperatingHourTypeFilters()})},this.update=function(item){me.canEdit(item)&&$modal.open({templateUrl:"app/equipment/views/equipmentOperatingHoursModal.html",controller:"EquipmentOperatingHoursController",size:"sm",resolve:{params:function(){return item}}}).result.then(function(){me.table.reload(),GetOperatingHourTypeFilters()})},this.remove=function(item){me.canDelete(item)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-equipment-equipmentOperatingHour-message","Driftstimene vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-equipment-equipmentOperatingHour-button-confirm","Ja, fjern driftstimene!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.equipmentOperatingHours.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-equipment-equipmentOperatingHour-success","Driftstimene ble fjernet!"),result,"success"),me.table.reload(),GetOperatingHourTypeFilters()})})},this.contextMenuOptions=function(item){var options=[];return me.canEdit(item)&&options.push({html:' '+translationService.translate("web-button-edit","Rediger")+"",click:function(){me.update(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-button-delete","Slett")+"",click:function($itemScope,$event,modelValue,text,$li){me.remove(item)}}),options},this.canEdit=function(item){return item&&$scope.hasEditAccess("EquipmentOperatingHours")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("EquipmentOperatingHours")},me.initTable()},$scope.$on($rootScope.events.newSelection,function(){updateEntityCommentVisibility()}),$scope.$watchCollection("model.Images",function(){if($scope.model&&$scope.model.Images&&Array.isArray($scope.model.Images)){var defaultImage=$scope.model.Images.find(function(img){return img.IsDefault});defaultImage?$scope.model.GuidDefaultImage=defaultImage.Guid:delete $scope.model.GuidDefaultImage}})}}angular.module("Plania").directive("equipmentInfoDirective",function(){return{restrict:"E",scope:{model:"=ngModel",restrictEdit:"=restrictEdit",reloads:"=reloads",update:"=update",reloadOperationalMessages:"=reloadOperationalMessages",reloadDocumentTable:"=reloadDocumentTable",activateAutocomplete:"=activateAutocomplete",currentTab:"=currentTab",formReference:"="},controller:["$scope","ngTableParams","Repository","TranslationService","$modal","$rootScope","ListService","authService","RegisteredFieldService","$localStorage","$timeout",controller],templateUrl:"app/equipment/views/equipmentInfo.html"}})}(),function(){function controller($scope,repository,translationService,$rootScope,listService,ngTableParams){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasEditAccess=$rootScope.hasEditAccess,$scope.hasModule=$rootScope.hasModule,$scope.navigation=$rootScope.navigation,$scope.update){$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.workOrderColumns=[{Position:1,Title:translationService.translate("web-workorder-id"),Property:"Id",PropertyType:"string"},{Position:1,Title:translationService.translate("web-workorder-type"),Property:"Type",PropertyType:"string"},{Position:4,Title:translationService.translate("web-workorder-description"),Property:"Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-equipment-resourcegroup-description","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidResourceGroup",AutocompleteService:"resourceGroup"},{Position:6,Title:translationService.translate("web-workorder-startdate"),Property:"StartDate",PropertyType:"date"},{Position:7,Title:translationService.translate("web-workorder-enddate"),Property:"EndDate",PropertyType:"date"}],$scope.periodicTaskColumns=[{Position:1,Title:translationService.translate("web-periodicTask-id"),Property:"Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-building-id"),Property:"Building.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidBuilding",AutocompleteService:"building"},{Position:5,Title:translationService.translate("web-equipment-id"),Property:"Equipment.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidEquipment",AutocompleteService:"equipment"},{Position:5,Title:translationService.translate("web-equipment-description"),Property:"Equipment.Description",PropertyType:"autocomplete",AutocompleteProperty:"GuidEquipment",AutocompleteService:"equipment"},{Position:7,Title:translationService.translate("web-periodicTask-description"),Property:"Description",PropertyType:"string"}];var ptFilter={PropertyFilter:[{Property:"GuidEquipment",Operator:"=",Value:$scope.model.Guid}]};$scope.periodicTaskTable=new ngTableParams({page:1,count:20,sorting:{Id:"desc"},filter:ptFilter},{total:0,filterDelay:10,counts:[10,20,50],paginationMaxBlocks:6,getData:function($defer,params){var columns=[];$scope.periodicTaskColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.periodicTask.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.periodicTaskTable.settings().total=result.TotalCount,$scope.periodicTaskTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.showError(error)})}}),$scope.createWorkOrder=function(){repository.persistedData.setPersistedData("workOrder.create",{guidEstate:$scope.model.Building?$scope.model.Building.Estate.Guid:null,estate:$scope.model.Building?$scope.model.Building.Estate.Caption:"",guidBuilding:$scope.model.GuidBuilding,guidEquipment:$scope.model.Guid,building:$scope.model.Building?$scope.model.Building.Caption:"",guidArea:$scope.model.GuidArea,area:$scope.model.Area?$scope.model.Area.Caption:"",equipment:$scope.model.Id+" - "+$scope.model.Description,fromEquipment:!0}),$scope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})},$scope.createPeriodicTask=function(){repository.persistedData.setPersistedData("periodicTask.create",{guidEstate:$scope.model.Building?$scope.model.Building.Estate.Guid:null,estate:$scope.model.Building?$scope.model.Building.Estate.Caption:"",guidBuilding:$scope.model.GuidBuilding,building:$scope.model.Building?$scope.model.Building.Caption:"",guidEquipment:$scope.model.Guid,equipment:$scope.model.Id+" - "+$scope.model.Description,guidArea:$scope.model.GuidArea,area:$scope.model.Area?$scope.model.Area.Caption:"",fromEquipment:!0}),$scope.navigation.go("periodicTask.create",{showPersistantData:!0},{reload:!0})}}}angular.module("Plania").directive("equipmentMaintenanceDirective",function(){return{restrict:"E",scope:{model:"=ngModel",update:"=update",reloadDeviations:"=reloadDeviations"},controller:["$scope","Repository","TranslationService","$rootScope","ListService","NgTableParams",controller],templateUrl:"app/equipment/views/equipmentMaintenance.html"}})}(),function(){function controller($scope,$modalInstance,params,repository){if(params.Guid){var columns=["EquipmentOperatingHourType.Id"];repository.getMainModel(repository.apiData.equipmentOperatingHours.url,params.Guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data})}else $scope.model=params;$scope.openCalendar=!1;var success=function(result){$scope.model.Guid?repository.growl("Driftstimer har blitt oppdatert","success"):repository.growl("Driftstimer har blitt lagt til anlegget","success"),$modalInstance.close("created")},error=function(result){repository.growl(result,"danger")};$scope.save=function(){$scope.model.Guid?repository.updateSingle(repository.apiData.equipmentOperatingHours.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.equipmentOperatingHours.url,$scope.model).then(success,error)},$scope.cancel=function(){$modalInstance.dismiss("Canceled")}}angular.module("Plania").controller("EquipmentOperatingHoursController",["$scope","$modalInstance","params","Repository",controller])}(),function(){function controller($scope,repository,$stateParams,$localStorage,$modal,translationService){$scope.update="estate.edit"===$scope.navigation.current.name,$scope.activateAutocomplete=!1,$scope.isDocumentsCollapsed=!0,$scope.reloadDeviations=!1,$scope.reloadDocumentTable=!1,$scope.reloadOperationalMessages=!1,$scope.viewMode=!!$scope.update,$scope.model={Guid:$stateParams.guid},$scope.useAddressSearch=$localStorage.generalOptions.UseAddressSearch,$scope.hideId=$localStorage.generalOptions.HideIdOnEstateAndBuildingCreation&&"estate.edit"!==$scope.navigation.current.name,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode},$scope.isDynamicPropertiesCollapsed=!1,$scope.model={Guid:$stateParams.guid};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Estate,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Estate,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Estate),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Estate)};updateAccess();var columns=["EstateCategory.Description","EstateCategory.Icon","EstateCategory.Color","CostCenter.Id","CostCenter.Description","BusinessUnit.Id","BusinessUnit.Description","BusinessUnit.IndexPosition","BusinessUnit.ExplanatoryText1","BusinessUnit.ExplanatoryText2","BusinessUnit.GuidParent","BusinessUnit.ReferenceType.Id","BusinessUnit.ReferenceType.Description","BusinessUnit.ReferenceType.ExplanatoryText","Owner.Id","Owner.Description","ExternalFacilityManager.Id","ExternalFacilityManager.Description","FacilityManager.FirstName","FacilityManager.LastName","OperationsManager.FirstName","OperationsManager.LastName","ManagerPerson1.FirstName","ManagerPerson1.LastName","ManagerPerson2.FirstName","ManagerPerson2.LastName"];if($scope.update)repository.getMainModel(repository.apiData.estate.url,$scope.model.Guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,updateAccess(),$scope.reloadDocumentTable=!0,$scope.reloadDeviations=!0,$scope.reloadOperationalMessages=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")});else{var getCategoryPrefill=function(guid){var guidCategory=guid||$scope.model.GuidEstateCategory;guidCategory&&repository.getSingle(repository.apiData.estateCategory.url,guidCategory).then(function(result){$scope.model.DynamicProperty=result.Data.DynamicProperty},function(error){repository.growl(error,"danger")})};$scope.model.CountryCode||($scope.model.CountryCode=repository.commonService.getFilterData().selectedDataOwner.CountryCode);var webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value)switch(prefill.Property){case"EstateCategory":$scope.model.EstateCategory={Guid:prefill.Value.Guid,Description:prefill.Value.Label,Caption:prefill.Value.Label},$scope.model.GuidEstateCategory=prefill.Value.Guid}else $scope.model[prefill.Property]=prefill.Value}),$stateParams.guidEntityToCopy?repository.getSingle(repository.apiData.estate.url,$stateParams.guidEntityToCopy,JSON.stringify(columns)).then(function(result){delete result.Data.Guid,delete result.Data.GuidGisEntity,$scope.model=result.Data,$scope.model.Id+="-N"}):getCategoryPrefill(),$scope.activateAutocomplete=!0}$scope.updateEstate=function(destination){var success=function(result){repository.growl($scope.update?"Eiendom har blitt oppdatert":"Eiendom har blitt opprettet.","success");var guid=$scope.update?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){repository.growl(error,"danger")};$scope.update?repository.updateSingle(repository.apiData.estate.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.estate.url,$scope.model).then(success).catch(error)},$scope.removeEstate=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-estate-message","Eiendommen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-estate-button-confirm","Ja, slett eiendommen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.estate.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-estate-success","Eiendommen ble fjernet!"),result,"success"),$scope.goBack("estate.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.onPostCodeSelect=function(postalInfo){postalInfo?($scope.model.PostalCode=postalInfo.ZipCode,$scope.model.GuidPost=postalInfo.Guid,$scope.model.PostalArea=postalInfo.PostalArea,$scope.model.County=postalInfo.County,$scope.model.Municipality=postalInfo.MunicipalityName,$scope.postalInfo=postalInfo):($scope.model.GuidPost=null,$scope.model.PostalArea="",$scope.model.County="",$scope.model.Municipality="")},$scope.countryCodeChanged=function(){$scope.model.CountryCode&&"Undefined"!==$scope.model.CountryCode&&($scope.model.PostalCode=null,$scope.onPostCodeSelect(null))},$scope.onEstateCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidEstateCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidEstateCategory=category.Guid},$scope.buildingColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-building-buildingCategory"),Property:"BuildingCategory.Description",PropertyType:"string"}],$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"person":return filter.PropertyFilter=[{Property:"IsOperationsManager",Value:1,Operator:"="}],filter;case"estateCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter;case"businessUnit":return filter.FilterModel={Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null}]},{Property:"ReferenceType.Context",Operator:"=",Value:3}]},filter;case"postal":return-1!==$scope.model.CountryCode&&"Undefined"!==$scope.model.CountryCode&&(filter.FilterModel={Condition:"and",Rules:[{Property:"CountryCode",Operator:"=",Value:$scope.model.CountryCode}]}),filter}},$scope.getBusinessUnitColumns=function(){return[{Title:translationService.translate("web-businessUnit-indexPosition","Indeks"),Property:"IndexPosition"},{Title:translationService.translate("web-businessUnit-id","Id"),Property:"Id"},{Title:translationService.translate("web-businessUnit-description","Beskrivelse"),Property:"Description"}]},$scope.openReferenceData=function(type){var guid="",initialModel=null;switch(type){case"BusinessUnit":guid=$scope.model.GuidBusinessUnit,initialModel=$scope.model.BusinessUnit}guid&&$modal.open({templateUrl:"app/referenceData/views/referenceDataInfoModal.html",controller:"ReferenceDataInfoModalController",resolve:{modalParams:function(){return{guid:guid,initialModel:initialModel}}},size:"lg"})},$scope.getPropertyCadastralNumber=function(){if(!($scope.model.PropertyCadastralNumber||$scope.model.PropertyUnitNumber||$scope.model.PropertyLeaseholdNumber||$scope.model.PropertyUnderNumber))return"-";var str=$scope.model.PropertyUnderNumber||"";return str&&(str+="/"),str+=$scope.model.PropertyLeaseholdNumber||"",str&&(str+="/"),str+=$scope.model.PropertyUnitNumber||"",str+="/",str+=$scope.model.PropertyCadastralNumber||"",str.split("/").reverse().join("/")},$scope.$watchCollection("model.Images",function(){if($scope.model&&$scope.model.Images&&Array.isArray($scope.model.Images)){var defaultImage=$scope.model.Images.find(function(img){return img.IsDefault});defaultImage?$scope.model.GuidDefaultImage=defaultImage.Guid:delete $scope.model.GuidDefaultImage}}),$scope.changeId=function(){$modal.open({templateUrl:"app/common/modal/views/changeIdModal.html",controller:"ChangeIdModalController",size:"md",resolve:{params:function(){return{id:$scope.model.Id}}}}).result.then(function(id){id&&repository.patch(repository.apiData.estate.url,$scope.model.Guid,{Id:id}).then(function(result){repository.growl(translationService.translate("web-estate-changeId-success","Id ble oppdatert"),"success"),$scope.model.Id=id},function(error){repository.showError(error)})})},$scope.showAddressSearchModal=function(){$modal.open({templateUrl:"app/address/views/addressSearchModal.html",controller:"AddressSearchController",resolve:{modalParams:function(){return{}}},size:"lg"}).result.then(function(selectedAddress){$scope.model.PostalCode=selectedAddress.Address.PostalCode,$scope.model.PostalArea=selectedAddress.Address.PostalArea,$scope.model.Address=selectedAddress.Address.StreetAddress,$scope.model.PropertyCadastralNumber=selectedAddress.PropertyCadastralNumber,$scope.model.PropertyUnitNumber=selectedAddress.PropertyUnitNumber,$scope.model.PropertyLeaseholdNumber=selectedAddress.PropertyLeaseholdNumber,$scope.model.PropertyUnderNumber=selectedAddress.PropertyUnderNumber})}}angular.module("Plania").controller("EstateController",["$scope","Repository","$stateParams","$localStorage","$modal","TranslationService",controller])}(),function(){function controller($scope,$window,repository,$localStorage,constants,translationService,columnFormatService,$modal,iconService){$scope.model={UserAuthentication:0},$scope.times={},$scope.activateAutocomplete=!1,$scope.generateQrCodeJobInfo={};var columns=["SystemOwner.UserName","SystemOwner.RealName","SystemOwner.PhoneNumber","SystemOwner.CellPhone","SystemOwner.Email","SystemOwner.IsDeactivated"];repository.getSingle(repository.apiData.generalOptions.url,"",JSON.stringify(columns)).then(function(result){repository.getSingleWithNoParameter(repository.apiData.generalOptions.url+"disabledProperties").then(function(response){$scope.model.DisabledProperties=response.Data}),repository.getSingleWithNoParameter(repository.apiData.generalOptions.url+"generateQrCodeJobInfo").then(function(response){$scope.generateQrCodeJobInfo=response.Data||{}}),$scope.model=result.Data,$scope.model.SystemOwner&&!$scope.model.SystemOwner.Caption&&($scope.model.SystemOwner.Caption=$scope.model.SystemOwner.Username),$scope.selectedInspectedEntityLocation=$scope.enumInspectedEntityLocation[$scope.model.InspectedEntityLocation],$scope.selectedLogSecurityEventLevel=_.find($scope.enumLogSeverity,{value:$scope.model.LogSecurityEventLevel}),$scope.selectedLogSecurityDbLevel=_.find($scope.enumLogSeverity,{value:$scope.model.LogSecurityDbLevel}),$scope.selectedTwoFactorAuthenticationOption=_.find($scope.twoFactorAuthenticationOption,{value:$scope.model.TwoFactorAuthenticationOption}),$scope.model.MapSettings&&($scope.mapSettings=JSON.parse($scope.model.MapSettings)),$scope.mapSettings||($scope.mapSettings={Options:{}},setDefaultEntityInfo()),$scope.mapSettings.entityInfo||setDefaultEntityInfo(),$scope.EquipmentFieldNameForMeteringIdentifierOptions=["Id","AlternateId"];for(var i=1;i<=40;i++){var key=i;i<10&&(key="0"+i),$scope.EquipmentFieldNameForMeteringIdentifierOptions.push("Text"+key)}$scope.mapSettings.entityInfo&&!$scope.mapSettings.entityInfo.request&&($scope.mapSettings.entityInfo.request={entity:"Request",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"fa-envelope"},iconAnchor:[10,24],popupAnchor:[0,-10],weight:8}),$scope.mapSettings.entityInfo&&!$scope.mapSettings.entityInfo.workOrder&&($scope.mapSettings.entityInfo.workOrder={entity:"WorkOrder",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"fa-suitcase"},iconAnchor:[10,24],popupAnchor:[0,-10],weight:8}),setTimeout(function(){$scope.activateAutocomplete=!0},250)}),$scope.poEntityTypes=[{text:translationService.translate("web-enum-prefix-article"),value:repository.commonService.prefix.Article},{text:translationService.translate("web-enum-prefix-component"),value:repository.commonService.prefix.Component},{text:translationService.translate("web-enum-prefix-sparePart"),value:repository.commonService.prefix.SparePart},{text:translationService.translate("web-enum-prefix-equipment"),value:repository.commonService.prefix.Equipment}],$scope.save=function(){delete $scope.BarcodeEquipmentFormatError,delete $scope.BarcodeComponentFormatError,delete $scope.BarcodeBuildingFormatError,delete $scope.BarcodeAreaFormatError,$scope.model.MapSettings=JSON.stringify($scope.mapSettings),$localStorage.generalOptions=$scope.model,repository.updateSingle(repository.apiData.generalOptions.url,$scope.model).then(function(result){repository.growl("Klientprofilen har blitt oppdatert","success")},function(error){if(Array.isArray(error)){var isBarcodeError=!1;error.forEach(function(err){"BarcodeEquipmentFormat"===err&&(isBarcodeError=!0,$scope.BarcodeEquipmentFormatError=translationService.translate("web-generalOptions-error-BarcodeAreaFormat","QR kode format for anlegg er ikke unikt, vennligst gjør den unik eller fjern formattet for å kunne lagre kundeprofilen")),"BarcodeComponentFormat"===err&&(isBarcodeError=!0,$scope.BarcodeComponentFormatError=translationService.translate("web-generalOptions-error-BarcodeComponentFormat","QR kode format for komponent er ikke unikt, vennligst gjør den unik eller fjern formattet for å kunne lagre kundeprofilen")),"BarcodeBuildingFormat"===err&&(isBarcodeError=!0, $scope.BarcodeBuildingFormatError=translationService.translate("web-generalOptions-error-BarcodeBuildingFormat","QR kode format for bygg er ikke unikt, vennligst gjør den unik eller fjern formattet for å kunne lagre kundeprofilen")),"BarcodeAreaFormat"===err&&(isBarcodeError=!0,$scope.BarcodeAreaFormatError=translationService.translate("web-generalOptions-error-BarcodeAreaFormat","QR kode format for areal er ikke unikt, vennligst gjør den unik eller fjern formattet for å kunne lagre kundeprofilen"))}),isBarcodeError?repository.growl("Feil i generering av QR-koder, fiks feilene før du kan lagre endringer på kundeprofilen","danger"):error.length>0&&repository.growl(error[0],"danger")}else"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"error")})},$scope.setMapData=function(item){$scope.mapSettings.TileLayer=item.mapData.TileLayer,$scope.mapSettings.TileLayerOptions=item.mapData.TileLayerOptions,$scope.mapSettings.CrsCode=item.mapData.CrsCode,$scope.mapSettings.Proj4Def=item.mapData.Proj4Def,$scope.mapSettings.Options.Origin=item.mapData.Options.Origin,$scope.mapSettings.Options.Resolution=item.mapData.Options.Resolution,$scope.mapSettings.Options.Resolution=item.mapData.Options.Resolution},$scope.generateGisEntities=function(){repository.runAction(repository.apiData.gisManagement.url).then(function(result){swal(translationService.translate("web-swal-generaloptions-generateGisEntities-success","Genering av kartpunkt er startet. Dette kan ta litt tid."),"","success")},function(error){repository.growl(error,"danger")})},$scope.updateCleaningEstimate=function(){repository.updateSingle(repository.apiData.cleaningStatus.url,{Guid:"UpdateEstimatedTime"}).then(function(result){repository.growl(result,"success")}).catch(function(error){repository.growl(error,"danger")})},$scope.verifyUniqueBarcode=function(typeFormat){var payload={type:typeFormat,Guid:$scope.model.Guid};switch(typeFormat){case repository.commonService.prefix.Building:payload.format=$scope.model.BarcodeBuildingFormat?$scope.model.BarcodeBuildingFormat:null;break;case repository.commonService.prefix.Equipment:payload.format=$scope.model.BarcodeEquipmentFormat?$scope.model.BarcodeEquipmentFormat:null;break;case repository.commonService.prefix.Area:payload.format=$scope.model.BarcodeAreaFormat?$scope.model.BarcodeAreaFormat:null;break;case repository.commonService.prefix.Component:payload.format=$scope.model.BarcodeComponentFormat?$scope.model.BarcodeComponentFormat:null}payload.format&&repository.updateSingle(repository.apiData.generalOptions.url+"VerifyUniqueBarcode/",payload).then(function(result){result.IsSuccess?repository.growl("Formatet er unikt","success"):$modal.open({templateUrl:"app/generalOptions/views/showDuplicateQrCodeModal.html",controller:function($scope,params){$scope.listOfDuplicates=params.failList},resolve:{params:function(){return{failList:result.FailList}}}})},function(error){repository.growl(error,"danger")})},$scope.setPlaniaWebUrl=function(){$scope.model.WebBaseUrl=$window.location.origin+"/"},$scope.testCatendaConnection=function(){repository.getSingleWithNoParameter(repository.apiData.bim.endpoint.ping).then(function(response){response?repository.growl(translationService.translate("web-catendaConnection-success","Koblingen fungerer"),"success"):repository.growl(translationService.translate("web-catendaConnection-error","Koblingen fungerer ikke"),"danger")},function(error){repository.showError(error)})},$scope.sendTestEmail=function(){$modal.open({templateUrl:"app/generalOptions/views/sendTestEmailModal.html",controller:function($scope,modalParams){$scope.emailTo=modalParams.userEmail,$scope.sendTestEmail=function(emailTo){var param="recipient="+emailTo;repository.getWithUrlParameter(repository.apiData.email.endpoint.sendTestEmail,param).then(function(response){response?repository.growl(translationService.translate("web-generaloptions-sendmail-test-success","E-post er sendt. Verifiser at denne kommer frem hos mottaker."),"success"):repository.growl(translationService.translate("web-generaloptions-sendmail-test-error","Feil ved sending. Se i systemlogg for mer informasjon."),"danger")},function(error){repository.showError(error)})}},resolve:{modalParams:function(){return{userEmail:repository.authService.getUserData().email}}}})},$scope.resetTermsOfUseAcceptedDates=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-generalOptions-reset-termsOfUse-confirmationMessage","Alle brukere vil måtte godkjenne brukervilkår på nytt"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-generalOptions-reset-termsOfUse-confirm","Ja, nullstill!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,repository.runAction(repository.apiData.generalOptions.endpoint.resetTermsOfUseAcceptedDates).then(function(response){swal(translationService.translate("web-swal-generaloptions-resetTermsOfUseAcceptedDates-success","Alle brukeres brukervilkår er nullstillet"),"","success")},function(error){repository.growl(error,"danger")})})},$scope.availableColors=["blue","red","green","orange","cyan","pink","black"];var setDefaultEntityInfo=function(){$scope.mapSettings.entityInfo={estate:{entity:"Estate",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"city"},iconAnchor:[10,33],popupAnchor:[0,-19],weight:8},building:{entity:"Building",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"home"},iconAnchor:[10,33],popupAnchor:[0,-19],weight:8},equipment:{entity:"Equipment",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"gear"},iconAnchor:[10,24],popupAnchor:[0,-10],weight:8},request:{entity:"Request",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"envelope"},iconAnchor:[10,24],popupAnchor:[0,-10],weight:8},workOrder:{entity:"WorkOrder",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"briefcase-blank"},iconAnchor:[10,24],popupAnchor:[0,-10],weight:8}}};$scope.iconMap=iconService.getAvailableMapIcons(),$scope.availableMaps=constants.availableMaps,$scope.enumInspectedEntityLocation=[{value:constants.inspectedEntityLocation.anywhere,text:translationService.translate("web-enum-inspectedentity-any","Hvor som helst")},{value:constants.inspectedEntityLocation.estate,text:translationService.translate("web-enum-inspectedentity-property","Eiendom")},{value:constants.inspectedEntityLocation.building,text:translationService.translate("web-enum-inspectedentity-building","Bygg")}],$scope.enumLogSeverity=[{value:-1,text:translationService.translate("web-enum-logseverity-none","Ingen logging")},{value:0,text:translationService.translate("web-enum-logseverity-info","Info (alle requests, avslått og vellyket)")},{value:1,text:translationService.translate("web-enum-logseverity-warning","Advarsel (alle avslåtte forespørsler)")},{value:2,text:translationService.translate("web-enum-logseverity-error","Feil (forsøk på innlogging etc)")}],$scope.twoFactorAuthenticationOption=[{value:0,text:translationService.translate("web-enum-twofactorauthenticationoption-disabled","Avslått")},{value:1,text:translationService.translate("web-enum-twofactorauthenticationoption-activeperuser","Aktiv per bruker")},{value:2,text:translationService.translate("web-enum-twofactorauthenticationoption-activeforall","Aktiv for alle")}],$scope.canChangeTwoFactorAuthenticationOption=function(){return $scope.model.SmsConfiguration},$scope.addNewBarcodeFormatColumn=function(modelProperty,entityName){columnFormatService.chooseColumn($scope.model,modelProperty,entityName)},$scope.navigateTo=function(url,guid){$scope.navigation.go(url,{guid:guid})},$scope.onUseDynamicCategoryCommonLabelsClick=function(){$scope.model.UseDynamicCategoryCommonLabels||$modal.open({templateUrl:"app/generalOptions/views/useDynamicCategoryCommonLabelsModal.html",controller:"UseDynamicCategoryCommonLabelsModalController"}).result.then(function(){$scope.model.UseDynamicCategoryCommonLabels=!0},function(){$scope.model.UseDynamicCategoryCommonLabels=!1})},$scope.onSelectSystemOwner=function(user){if(!user)return $scope.model.GuidSystemOwner=null,void($scope.model.SystemOwner=null);$scope.model.GuidSystemOwner!==user.Guid&&($scope.model.GuidSystemOwner=user.Guid,$scope.model.SystemOwner=user,$scope.model.SystemOwner.Caption||($scope.model.SystemOwner.Caption=user.Username))}}angular.module("Plania").controller("GeneralOptionsController",["$scope","$window","Repository","$localStorage","Constants","TranslationService","ColumnFormatService","$modal","IconService",controller])}(),function(){function controller($scope,repository,modalInstance,translationService,ngTableParams,listService){$scope.isLoading=!0,$scope.validations=[],$scope.hasConflictsTexts={header:translationService.translate("web-generalOptions-dynamicCategoryCommonLabelsValidation-alertHeader-hasConflicts","Ikke anbefalt å aktivere"),text:translationService.translate("web-generalOptions-dynamicCategoryCommonLabelsValidation-alertText-hasConflicts","Installasjonen inneholder kategorier som har konflikt mellom sine ledetekster. Undersøk helsesjekk for å se hvilke kategorier som har konflikt.")},$scope.noConflictsTexts={header:translationService.translate("web-generalOptions-dynamicCategoryCommonLabelsValidation-alertHeader-noConflicts","Anbefalt å aktivere"),text:translationService.translate("web-generalOptions-dynamicCategoryCommonLabelsValidation-alertText-noConflicts","Fant ingen kolliderende ledetekster blant alle kategorier på installasjonen.")},$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)},$scope.columns=[{Position:1,Title:translationService.translate("web-generalOptions-dynamicCategoryCommonLabelsValidation-dataOwnerId","Klient"),Property:"DataOwnerId",PropertyType:"string"},{Position:2,Title:translationService.translate("web-generalOptions-dynamicCategoryCommonLabelsValidation-hasConflictingLabel","Har kollisjon"),Property:"HasConflictingLabel",PropertyType:"bool"}],repository.getSingleWithNoParameter(repository.apiData.generalOptions.url+"validate/UseDynamicCategoryCommonLabels").then(function(response){$scope.isLoading=!1,$scope.validations=response.Data.Validations},function(error){repository.showError(error),$scope.isLoading=!1}),$scope.table=new ngTableParams({page:1,count:10,sorting:{DataOwnerId:"asc"}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var sortingKey=Object.keys(params.sorting())[0],direction=params.sorting()[sortingKey],data=$scope.validations.sort(function(a,b){var aVal=a[sortingKey],bVal=b[sortingKey];return aValbVal?1:0});"desc"===direction.toLowerCase()&&(data=data.reverse()),data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$scope.table.settings().total=$scope.validations.length,$scope.table.settings().filterDelay=50,$defer.resolve(data)}}),$scope.confirm=function(){modalInstance.close()},$scope.cancel=function(){modalInstance.dismiss("Avbryt")}}angular.module("Plania").controller("UseDynamicCategoryCommonLabelsModalController",["$scope","Repository","$modalInstance","TranslationService","ngTableParams","ListService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService){$scope.isUpdate="hourType.edit"===$scope.navigation.current.name||$stateParams.isModal&&$stateParams.isUpdate,$scope.activateAutocomplete=!1,$scope.isModal=$stateParams.isModal,$scope.model={},$scope.isModal&&!$scope.isUpdate&&($scope.model.GuidProject=$stateParams.guidProject);var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.HourType,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.HourType,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.HourType),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.HourType)};$scope.isUpdate?repository.getSingle(repository.apiData.hourType.url,$stateParams.guid,null).then(function(response){$scope.model=response.Data,updateAccess(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}):$scope.activateAutocomplete=!0,$scope.cancel=function(){$stateParams.cancel()},$scope.ok=function(){$stateParams.ok()},$scope.update=function(destination){var success=function(result){if(repository.growl($scope.isUpdate?translationService.translate("update-hourType-success","Time type har blitt oppdatert."):translationService.translate("create-hour-type-success","Time type har blitt opprettet."),"success"),$scope.isModal)$scope.ok();else{var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})}},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.hourType.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.hourType.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-hourType-delete-message","Time typen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-hourType-delete-button-confirm","Ja, fjern time typen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.hourType.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-hourType-delete-success","Time typen ble fjernet!"),result,"success"),repository.growl(translationService.translate("web-workorder-hourType-removed","Time typen er fjernet"),"success"),$scope.isModal?$modalStack.dismissAll():$scope.goBack("hourType.list",{menuGuid:$scope.navigation.params.menuGuid})})})}}angular.module("Plania").controller("HourTypeController",["$scope","Repository","$stateParams","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,$modal,modalParams,ngTableParams,listService,$modalStack){$scope.project=modalParams.Project;var modalInstance=null;$scope.hourTypeColumns=[],$scope.hourTypeColumns.AddColumn=function(translationId,defaultText,property,propertyType){return this.push({Position:this.length,Title:translationService.translate(translationId,defaultText),Property:property,PropertyType:propertyType}),this},$scope.hourTypeColumns.AddColumn("web-hour-type-id","Id","Id","string").AddColumn("web-hour-type-description","Beskrivelse","Description","string").AddColumn("web-hour-type-price","Pris","Price","number").AddColumn("web-hour-type-type","Type","PriceType","enum.PriceType"),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.can=function(operation){if($scope.project.ClosedDate)return!1;var permissionHandler=$scope["has"+operation+"Access"];return!!permissionHandler&&permissionHandler("HourType")},function(){$scope.hourTypeTable=new ngTableParams({page:1,count:10,sorting:{},filter:{GuidProject:$scope.project.Guid}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];$scope.hourTypeColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.hourType.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.loadingHourType=!1,$scope.hourTypeTable.settings().total=result.TotalCount,$scope.hourTypeTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){$scope.loadingHourType=!1,repository.growl(error,"danger")})}})}(),$scope.updateHourType=function(hourType){modalInstance=$modal.open({templateUrl:"app/hourType/views/editHourTypeModal.html",size:"md",animation:!1,controller:"HourTypeController",resolve:{$stateParams:function(){return{isModal:!0,isUpdate:!0,guid:hourType.Guid,cancel:$scope.modalCancel,ok:$scope.modalOk}}}}),modalInstance.result.then(function(result){$scope.hourTypeTable.reload()},function(error){})},$scope.createHourType=function(){modalInstance=$modal.open({templateUrl:"app/hourType/views/editHourTypeModal.html",size:"md",animation:!1,controller:"HourTypeController",resolve:{$stateParams:function(){return{isModal:!0,isUpdate:!1,guidProject:$scope.project.Guid,cancel:$scope.modalCancel,ok:$scope.modalOk}}}}),modalInstance.result.then(function(result){$scope.hourTypeTable.reload()},function(error){})},$scope.modalCancel=function(){modalInstance.dismiss("canceled")},$scope.modalOk=function(){modalInstance.close()},$scope.deleteHourType=function(hourType){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-hourType-delete-message","Time typen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-hourType-delete-button-confirm","Ja, fjern time typen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.hourType.url,hourType.Guid).then(function(result){swal(translationService.translate("web-swal-hourType-delete-success","Time typen ble fjernet!"),result,"success"),repository.growl(translationService.translate("web-workorder-hourType-removed","Time typen er fjernet"),"success"),$scope.hourTypeTable.reload()})})}}angular.module("Plania").controller("HourTypeModalController",["$scope","Repository","$stateParams","TranslationService","$modal","modalParams","ngTableParams","ListService","$modalStack",controller])}(),function(){function controller($scope,$modalInstance,params,repository){$scope.isUpdate=!!params.guidAreaXEntity,$scope.areaXEntity={GuidArea:params.guidArea};var setProperties=function(){var areaXEntity=$scope.areaXEntity;areaXEntity.Room&&($scope.area=areaXEntity.Room.Id+" - "+areaXEntity.Room.Description),areaXEntity.Service&&($scope.service=areaXEntity.Service.Id+" - "+areaXEntity.Service.Description),areaXEntity.Article&&($scope.article=areaXEntity.Article.Id+" - "+areaXEntity.Article.Description)};if($scope.isUpdate){var columns=["Room.Id","Room.Description","Article.Id","Article.Description","Service.Id","Service.Description"];repository.getSingle(repository.apiData.areaXEntity.url,params.guidAreaXEntity,JSON.stringify(columns)).then(function(result){$scope.areaXEntity=result.Data,setProperties(),$scope.reload=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)})}else $scope.areaXEntity.Quantity=1,$scope.activateAutocomplete=!0;$scope.$watch("areaXEntity.EntityType",function(newValue,oldValue){if(newValue!==oldValue){var entityType="string"==typeof $scope.areaXEntity.EntityType?parseInt($scope.areaXEntity.EntityType):$scope.areaXEntity.EntityType;13===entityType?(delete $scope.areaXEntity.GuidService,delete $scope.areaXEntity.GuidArticle,delete $scope.service,delete $scope.article):14===entityType&&(delete $scope.areaXEntity.GuidRoom,delete $scope.area)}}),$scope.onAreaSelect=function(area){$scope.areaXEntity.GuidRoom=area.Guid,$scope.areaXEntity.Id=area.Id,$scope.areaXEntity.Description=area.Description,$scope.areaXEntity.RentalPricePerMonth=area.RentalPricePerMonth,$scope.area=area.Id+" - "+area.Description},$scope.onArticleSelect=function(article){$scope.areaXEntity.GuidArticle=article.Guid,$scope.areaXEntity.Id=article.Id,$scope.areaXEntity.Description=article.Description,$scope.areaXEntity.RentalPricePerMonth=0,article.Service&&($scope.areaXEntity.GuidService=article.Service.Guid,$scope.service=article.Service.Id+" - "+article.Service.Description)},$scope.save=function(){var success=function(result){$modalInstance.close()},error=function(error){repository.growl(error,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.areaXEntity.url,$scope.areaXEntity).then(success,error):repository.createSingle(repository.apiData.areaXEntity.url,$scope.areaXEntity).then(success,error)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("AreaXEntityModalController",["$scope","$modalInstance","params","Repository",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,ngTableParams,$modal,listService,$state,areaService){$scope.isUpdate="housing.edit"===$scope.navigation.current.name,$scope.model=$stateParams.model||{Guid:$stateParams.guid},$scope.allWorkOrdersSelected=!1,$scope.selectedWorkOrders=[],$scope.activateAutocomplete=!1,$scope.viewMode=!!$scope.isUpdate,$scope.reloadControlList=!1,$scope.reloadDeviation=!1,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Area,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Area,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Area),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Area)};$scope.areaXEntityColumns=[{Position:1,Title:translationService.translate("web-areaXEntity-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-areaXEntity-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-areaXEntity-quantity","Antall"),Property:"Quantity",PropertyType:"string"},{Position:4,Title:translationService.translate("web-areaXEntity-rentalPricePerMonth","Månedsleie"),Property:"RentalPricePerMonth",PropertyType:"double"},{Position:5,Title:translationService.translate("web-areaXEntity-updatedDate","Oppdatert"),Property:"UpdatedDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-areaXEntity-creationDate","Opprettet"),Property:"CreationDate",PropertyType:"date"}],$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)};var workOrderFilters=[{value:"active",name:translationService.translate("web-workOrder-filterType-active","Aktive")},{value:"history",name:translationService.translate("web-workOrder-filterType-history","Historikk")}];$scope.selectedWorkOrderFilter=_.find(workOrderFilters,{value:"active"}).name,$scope.setWorkOrderFilter=function(filterType){$scope.selectedWorkOrderFilter=_.find(workOrderFilters,{value:filterType}).name;var existingStageFilterIndex=_.findIndex($scope.workOrderTable.filter().PropertyFilter,function(o){return"Stage"===o.Property});existingStageFilterIndex>-1&&$scope.workOrderTable.filter().PropertyFilter.splice(existingStageFilterIndex,1);var propertyFilter=$scope.workOrderTable.filter().PropertyFilter,filter={};switch(filterType){case"active":filter={Property:"Stage",Operator:"=",Value:"1"},propertyFilter?propertyFilter.push(filter):$scope.workOrderTable.filter().PropertyFilter=[filter];break;case"history":filter={Property:"Stage",Operator:"=",Value:"2"},propertyFilter?propertyFilter.push(filter):$scope.workOrderTable.filter().PropertyFilter=[filter]}},$scope.createWorkOrder=function(){var prefill={guidEstate:$scope.model.Estate?$scope.model.Estate.Guid:null,estate:$scope.model.Estate?$scope.model.Estate.Caption:null,guidBuilding:$scope.model.GuidBuilding,building:$scope.model.Building?$scope.model.Building.Caption:null,guidArea:$scope.model.Guid,area:$scope.model.Id+" - "+$scope.model.Description,fromArea:!0},navigate=function(){repository.persistedData.setPersistedData("workOrder.create",prefill),$scope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})};areaService.getActiveCustomer($scope.model.Guid).then(function(customer){customer&&(prefill.guidCustomer=customer.Guid,prefill.customer=customer.Caption),navigate()},function(){navigate()})};var getCardTables=function(){$scope.areaXEntityTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{PropertyFilter:[{Property:"GuidArea",Operator:"=",value:$stateParams.guid}]}},{total:0,counts:[10,20,50],filterDelay:10,paginationMaxBlocks:6,getData:function($defer,params){var columns=[];$scope.areaXEntityColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.areaXEntity.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.areaXEntityTable.settings().total=result.TotalCount,$scope.areaXEntityTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),listService.getWebListViews(null,repository.apiData.workOrder.prefix,!1,null,{}).then(function(result){$scope.workOrderListOptions=result.listOptions,$scope.workOrderListSetup=result.selectedListSetup,$scope.workOrderTable||($scope.workOrderTable=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{ActivityStatus:"Undefined",PropertyFilter:[{Property:"GuidArea",Operator:"=",Value:$stateParams.guid},{Property:"Stage",Operator:"=",Value:"1"}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];$scope.workOrderListSetup.Columns.forEach(function(col){columns.push(col.Property)}),columns.push("CompletionRate"),repository.GetPaginated(repository.apiData.workOrder.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.workOrderTable.settings().total=result.TotalCount,$scope.workOrderTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))})},setProperties=function(){$scope.showDynamicProperties=$scope.model.DynamicProperty&&$scope.model.DynamicProperty.Groups.length>0,$scope.model.Building&&($scope.building=$scope.getEntityCaption($scope.model.Building)),$scope.model.AreaType&&($scope.areaType=$scope.getEntityCaption($scope.model.AreaType))};repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix.ContractItem).then(function(result){$scope.contractItemFieldRules=result,$scope.reloadContractItem=!0});var columns=["Building.Guid","Building.PostalCode","Building.Id","Building.Description","Building.PostalArea","Building.Address","Building.County","Building.Estate.Id","Building.Estate.Description","Building.Estate.Guid","CostCenter.Id","CostCenter.Description","ContractItem.EffectiveStartDate","ContractItem.UnitPrice","ContractItem.EffectiveEndDate","ContractItem.Contract.EndDate","ContractItem.Contract.ScheduledEndDate","ContractItem.Contract.Customer.Guid","ContractItem.Contract.Customer.Description","ContractItem.Contract.Customer.Telephone","AreaCategory.Description","AreaType.Id","AreaType.Description"];if($scope.isUpdate)repository.getMainModel(repository.apiData.area.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){if($scope.model=response.Data,!$scope.model.IsHousing)return void $state.go("area.edit",{guid:$stateParams.guid,model:$scope.model},{location:"replace"});$scope.fieldRules=response.FieldRules,updateAccess(),setProperties(),setTimeout(function(){$scope.activateAutocomplete=!0},250),$scope.reload=!0,$scope.reloadControlList=!0,$scope.reloadDeviation=!0},function(error){repository.growl(error,"danger")}),getCardTables();else{var getCategoryPrefill=function(guid){var guidCategory=guid||$scope.model.GuidAreaCategory;guidCategory&&repository.getSingle(repository.apiData.areaCategory.url,guidCategory).then(function(result){$scope.model.DynamicProperty=result.Data.DynamicProperty,$scope.showDynamicProperties=$scope.model.DynamicProperty&&$scope.model.DynamicProperty.Groups.length>0},function(error){repository.growl(error,"danger")})},building=repository.commonService.getFilterData().selectedBuilding;building.Guid&&($scope.building=building.Name,$scope.model.GuidBuilding=building.Guid);var webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value)switch(prefill.Property){case"AreaCategory":$scope.model.GuidAreaCategory=prefill.Value.Guid,$scope.model.AreaCategory={Guid:prefill.Value.Guid,Description:prefill.Value.Label,Caption:prefill.Value.Label}}else"@CurrentBuilding"===prefill.Value?building.Guid&&($scope.building=building.Name,$scope.model.GuidBuilding=building.Guid):$scope.model[prefill.Property]=prefill.Value}),$scope.model.RentalStatus="Vacant",$scope.model.IsHousing=!0,$stateParams.guidEntityToCopy?repository.getSingle(repository.apiData.area.url,$stateParams.guidEntityToCopy,JSON.stringify(columns)).then(function(result){delete result.Data.Guid,delete result.Data.Id,$scope.model=result.Data,$scope.fieldRules=result.FieldRules,$scope.reload=!0,setProperties()}):(getCategoryPrefill(),repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix.Area).then(function(result){$scope.fieldRules=result,$scope.reload=!0,$scope.activateAutocomplete=!0}))}$scope.onBuildingSelect=function(building){if(!building)return $scope.model.GuidBuilding="",void($scope.model.Address="");$scope.model.GuidBuilding=building.Guid,building.Address&&($scope.model.Address=building.Address)},$scope.onAreaCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidAreaCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidAreaCategory=category.Guid},$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-housing-success","Bolig har blitt oppdatert."):translationService.translate("create-housing-success","Bolig har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.area.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.area.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-housing-message","Boligen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-housing-button-confirm","Ja, fjern Bolig"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){ window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.area.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-housing-success","Boligen ble fjernet!"),result,"success"),$scope.goBack("housing.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.addAreaXEntity=function(){$modal.open({templateUrl:"app/housing/views/areaXEntityModal.html",controller:"AreaXEntityModalController",resolve:{params:function(){return{guidArea:$scope.model.Guid}}}}).result.then(function(){$scope.areaXEntityTable.reload()},function(){})},$scope.editAreaXEntity=function(areaXEntity){$modal.open({templateUrl:"app/housing/views/areaXEntityModal.html",controller:"AreaXEntityModalController",resolve:{params:function(){return{guidArea:$scope.model.Guid,guidAreaXEntity:areaXEntity.Guid}}}}).result.then(function(){$scope.areaXEntityTable.reload()},function(){})},$scope.removeAreaXEntity=function(areaXEntity){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-areaXEntity-message","Objektet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-areaXEntity-button-confirm","Ja, fjern objektet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.areaXEntity.url,areaXEntity.Guid).then(function(result){swal(translationService.translate("web-swal-areaXEntity-success","Objektet ble fjernet!"),result,"success"),$scope.areaXEntityTable.reload()})})},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.selectAllRows=function(table,selectedItems,allRowsSelected){$scope[allRowsSelected]?(table.data.forEach(function(row){var index=_.findIndex(selectedItems,function(o){return o===row.Guid});selectedItems.splice(index,1)}),$scope[allRowsSelected]=!1):(table.data.forEach(function(row){_.contains(selectedItems,row.Guid)||selectedItems.push(row.Guid)}),$scope[allRowsSelected]=!0)},$scope.selectItem=function(guid,selectedItems){if($scope.itemIsSelected(guid,selectedItems)){for(var i=0;i0},$scope.focusedLoginMethod=null,$scope.showTwoFactor=!0}if($scope.status=null,$scope.model={username:"",password:""},$scope.externalLoginMethods=null,$scope.loginMethods=[],$scope.focusedLoginMethod=null,repository.getSingleWithNoParameter("/PlaniaStatus").then(function(result){$scope.status=result,$scope.showMobileApp=result.ShowMobileApp,result.ShowUsernamePasswordLogin&&$scope.loginMethods.push({Type:"UsernamePassword",Id:"UsernamePassword",Name:translationService.translate("web-login-method-usernamePassword","Brukernavn og passord"),Icon:"far fa-lock",OnFocusClick:function(){$scope.focusLoginMethod("UsernamePassword")},OnClickFunc:function(){$localStorage.loginHint="UsernamePassword",$scope.focusLoginMethod("UsernamePassword")}}),result.ShowSamlLogin&&$scope.loginMethods.push({Type:"Saml",Id:"Saml",Icon:"far fa-id-card",Name:translationService.translate("web-login-method-saml","Logg inn med SAML"),OnFocusClick:function(){$scope.focusLoginMethod("Saml")},OnClickFunc:function(){$localStorage.loginHint="Saml",$scope.samlLogin()}}),result.ShowExternalLogin&&_.forEach(result.ExternalLoginMethods,function(item){$scope.loginMethods.push({Type:"ExternalLogin",Id:item.Name,Icon:getIconFromLoginType(item.Type),Name:item.Name,OnFocusClick:function(){$scope.focusLoginMethod(item.Name)},OnClickFunc:function(){$localStorage.loginHint=item.Name,$scope.loginWithProvider(item.Name)}})});var loginHint=$location.search().loginHint;if(loginHint||(loginHint=$localStorage.loginHint),loginHint){var loginMethod=_.find($scope.loginMethods,function(item){return item.Id===loginHint});loginMethod&&loginMethod.OnFocusClick&&loginMethod.OnFocusClick()}if($scope.showChooseLogin=!$scope.focusedLoginMethod&&$scope.loginMethods.length>1,$scope.focusedLoginMethod||1!==$scope.loginMethods.length||$scope.loginMethods[0].OnFocusClick(),$localStorage.planiaStatus=result,$location.search().initExternalLoginRegistration){var startExternalLoginRegistration=$location.search().initExternalLoginRegistration,externalLoginProvider=$location.search().externalLoginProvider,provider=_.find(result.ExternalLoginMethods,function(item){return item.Name===externalLoginProvider}),token=$location.search().token,email=$location.search().email,cellPhone=$location.search().cellPhone;startExternalLoginRegistration&&$modal.open({controller:"RegisterExternalLoginModalController",templateUrl:"app/login/views/registerExternalLoginModal.html",resolve:{params:function(){return{externalLoginProvider:provider,token:token,email:email,cellPhone:cellPhone}}}}).result.then(function(provider){provider===externalLoginProvider&&$scope.loginWithProvider(provider)})}}),$location.search().error&&($scope.alertMessage=$location.search().error),$stateParams.message&&($scope.alertMessage=$stateParams.message),$stateParams.refreshtoken||$location.search().refreshToken){var refreshToken=$stateParams.refreshtoken||$location.search().refreshToken;$scope.hideLoginBox=!0,repository.authService.authenticateSamlRefresh(refreshToken).then(function(){afterLogonNavigate()}).catch(function(error){$scope.hideLoginBox=!1,$scope.alertMessage="Kunne ikke logge inn, prøv igjen."})}$scope.openQRCodeModal=function(){$modal.open({controller:"QrCodeModalController",templateUrl:"app/common/views/qrCodeModal.html"})};var sessionStorage=window.sessionStorage,logoutError=sessionStorage.getItem("logoutError");logoutError&&($scope.alertMessage=logoutError,sessionStorage.removeItem("logoutError"));var getNavigationStateAfterLogin=function(){var defer=$q.defer(),stateObject={state:"",params:{},options:{}};if($stateParams.returnToState){var returnTo=JSON.parse($stateParams.returnToState);return stateObject.state=returnTo.name,stateObject.params=returnTo.params,$.Deferred().resolve(stateObject).promise()}var userData=repository.authService.getUserData();return menuService.getShortcuts().then(function(){if(userData.GuidWebMenu&&userData.MenuContext){var filter=userData.MenuParameters.replace(/(\r\n|\n|\r)/gm,"");repository.setMenuParameters(userData.GuidWebMenu,filter,0),stateObject.state=userData.MenuContext,stateObject.params={menuGuid:userData.GuidWebMenu},stateObject.options={reload:!0}}else stateObject.state="building.list";defer.resolve(stateObject)},function(error){$scope.isLoginActive=!1,error===translationService.translate("api-accessDomain-hasEntityAccess-hasNoAccess","Bruker har ikke tilgang")?repository.growl(translationService.translate("web-login-userXWebProfile-access-error","Bruker mangler rettighet til brukerprofil (UserXWebProfile), vennligst kontakt en Plania adminstrator for å fikse problemet"),"danger"):repository.growl(translationService.translate("web-login-userXWebProfile-generic-error","Noe gikk galt ved henting av brukerprofil, vennligst kontakt en Plania adminstrator, for å fikse problemet"),"danger"),defer.reject(error)}),defer.promise},afterLogonNavigate=function(userData){repository.setLocale(repository.authService.getUserData().language),translationService.getTranslations(),generalOptionsService.refreshGeneralOptions(),signalR.setQs({fingerprint:config.fingerprint,guidUser:repository.authService.getUserData().guidUser}),signalR.start(),repository.GetPaginated(repository.apiData.userAccess.url,0,0,{},{}).then(function(response){response.forEach(function(row){repository.authService.updateUserAccess(row)}),getNavigationStateAfterLogin().then(function(navigationState){!$stateParams.returnToState&&$scope.$parent&&($scope.$parent.home={state:navigationState.state,params:navigationState.params||{menuGuid:null}}),!userData||"1"!==userData.MustChangePassword?$scope.navigation.go(navigationState.state,navigationState.params,navigationState.options):$scope.navigation.go("mustChangePassword",{returnToState:navigationState})})},function(error){$scope.isLoginActive=!1,swal("Feil ved henting av brukerens tilganger",error,"error")})};repository.authService.getUserData().isAuthenticated&&repository.authService.refreshAuthentication().then(function(result){"invalid"!==result&&afterLogonNavigate()}),$scope.samlLogin=function(){repository.authService.authenticateSaml()},$scope.model.username="",$scope.model.password="",$scope.isLoginActive=!1;var afterLogonRememberTwoFactor=function(twoFactor){if(twoFactor&&twoFactor.rememberMe){var daysToRemember=$scope.status.TwoFactorExpirationPeriodInDays;if(daysToRemember>0){var rememberMeInfo={username:$scope.model.username,identifier:twoFactor.identifier,secret:twoFactor.newSecret,expires:moment().add(daysToRemember,"days").format()};$localStorage.twoFactorRememberMe=rememberMeInfo}}},getRememberedTwoFactorForUser=function(username){var rememberMeInfo=$localStorage.twoFactorRememberMe;if(rememberMeInfo&&rememberMeInfo.expires){moment(rememberMeInfo.expires).isBefore(moment())&&($localStorage.twoFactorRememberMe=null,rememberMeInfo=null)}return rememberMeInfo&&rememberMeInfo.username===username?rememberMeInfo:null};$scope.performLogin=function(){if($scope.isLoginActive=!0,!$scope.model.username)return repository.growl("Du må fylle ut brukernavn","danger"),void($scope.isLoginActive=!1);if(!$scope.model.password)return repository.growl("Du må fylle ut passord","danger"),void($scope.isLoginActive=!1);var logoutOtherLocation=!0===$scope.model.confirmLogout,twoFactorRemembered=getRememberedTwoFactorForUser($scope.model.username);twoFactorRemembered||$scope.twoFactor&&$scope.twoFactor.rememberMe&&($scope.twoFactor.newSecret=planiaUtils.randomString(100)),repository.authService.authenticate($scope.model.username,$scope.model.password,logoutOtherLocation,$scope.twoFactor,twoFactorRemembered,function(result){afterLogonRememberTwoFactor($scope.twoFactor),afterLogonNavigate(result)},function(result){"error"===result.status?repository.growl(result.message,"danger"):"confirm_logout"===result.status?$scope.displayConfirmation=!0:"two_factor_required"===result.status?handleTwoFactor(result):"two_factor_failed"===result.status?repository.growl(result.message,"danger"):"two_factor_cancelled"===result.status&&(repository.growl(result.message,"danger"),$scope.cancelTwoFactor()),$scope.isLoginActive=!1})},$scope.submitTwoFactor=function(){$scope.twoFactor.error=null,$scope.performLogin()},$scope.cancelTwoFactor=function(){$scope.twoFactor=null,$scope.focusLoginMethod("UsernamePassword"),$scope.showTwoFactor=!1},$scope.ignoreStatusNotOk=function(){$scope.status&&($scope.status.IsStatusOk=!0)},$scope.loginWithProvider=function(loginProvider){repository.authService.authenticateExternalLogin(loginProvider)},$scope.goToChooseLogin=function(){$scope.showChooseLogin=!0,$scope.focusedLoginMethod=null},$scope.focusLoginMethod=function(loginMethodId){var loginMethod=_.find($scope.loginMethods,function(item){return item.Id===loginMethodId});$scope.focusedLoginMethod=loginMethod,$scope.showChooseLogin=!1}}angular.module("Plania").controller("LoginController",["$scope","Repository","MenuService","GeneralOptionsService","$stateParams","$modal","$location","TranslationService","$state","$localStorage","SignalR","config","$q",loginController])}(),function(){function controller($scope,repository,$state,signalR){signalR.stop(),signalR.setQs({}),repository.authService.removeAuthentication().then(function(result){repository.growl("Du har blitt logget ut","success"),$state.go("login",{useSSO:!1})},function(error){$state.go("login",{useSSO:!1})})}angular.module("Plania").controller("LogoutController",["$scope","Repository","$state","SignalR",controller])}(),function(){function controller($scope,$state,repository,authService,translationService,$modal){var returnToState,params=$state.params;params&&(returnToState=params.returnToState),$modal.open({templateUrl:"app/common/modal/views/changePasswordModal.html",controller:"ChangePasswordModalController",size:"sm",keyboard:!1,resolve:{params:function(){return{user:{},mustChangePasswordProcess:!0,saveOverride:function(viewModel,modalInstance){repository.createSingle(repository.apiData.user.urlChangePassword,viewModel).then(function(){repository.growl("Passord har blitt oppdatert","success"),returnToState?$state.go(returnToState.state,returnToState.params,returnToState.options):$state.go("login")},function(error){repository.growl(error,"danger")})}}}}})}angular.module("Plania").controller("MustChangePasswordController",["$scope","$state","Repository","authService","TranslationService","$modal",controller])}(),function(){function controller($scope,$modalInstance,$http,repository,config,params,$location){$scope.model={email:params.email,cellPhone:params.cellPhone,token:params.token,verificationCode:null},$scope.externalLoginProvider=params.externalLoginProvider,$scope.showTokenInput=!!$scope.model.token,$scope.isLoading=!1,$scope.externalLoginProvider.SendVerificationCodeUsingEmail||$scope.externalLoginProvider.SendVerificationCodeUsingSms?!$scope.externalLoginProvider.SendVerificationCodeUsingEmail&&$scope.externalLoginProvider.SendVerificationCodeUsingSms?$scope.VerificationMode="Sms":$scope.VerificationMode="Email":($scope.externalLoginProvider.SendVerificationCodeUsingEmail=!0,$scope.VerificationMode="Email"),$scope.send=function(){if($scope.model.email||$scope.model.cellPhone){$scope.isLoading=!0;var postConfig={method:"POST",url:encodeURI(config.baseUrl+"login/external/register"),headers:{"Content-Type":"application/json; charset=UTF-8"},data:{CellPhone:$scope.model.cellPhone,EmailAddress:$scope.model.email,ExternalLoginProvider:$scope.externalLoginProvider.Name}};$http(postConfig).success(function(response){$scope.model.token=response.Token,$location.search("token",$scope.model.token),$location.search("email",$scope.model.email),$location.search("cellPhone",$scope.model.cellPhone),$scope.showTokenInput=!0,$scope.isLoading=!1}).error(function(message){repository.showError(message),$scope.isLoading=!1})}},$scope.verify=function(){if($scope.model.verificationCode){$scope.isLoading=!0;var postConfig={method:"POST",url:encodeURI(config.baseUrl+"login/external/verify"),headers:{"Content-Type":"application/json; charset=UTF-8"},data:{VerificationCode:$scope.model.verificationCode,Token:$scope.model.token}};$http(postConfig).success(function(response){repository.growl(response.Message,"success"),$location.search({}),$modalInstance.close($scope.externalLoginProvider.Name),$scope.isLoading=!1}).error(function(message){repository.showError(message),$scope.isLoading=!1})}},$scope.cancel=function(){$location.search({}),$modalInstance.dismiss("cancelled")}}angular.module("Plania").controller("RegisterExternalLoginModalController",["$scope","$modalInstance","$http","Repository","config","params","$location",controller])}(),angular.module("Plania").directive("gantt",function(){function controller(scope,$modal){var monthArray=["Januar","Februar","Mars","April","Mai","Juni","Juli","August","September","Oktober","November","Desember"],updatedModel=null,windowScrollY=window.scrollY,panelScrollX=0,renderGantt=function(){$(".gantt").gantt({source:scope.tasks?scope.tasks:[],columnData:scope.columnData?scope.columnData:[],scale:scope.viewMode?scope.viewMode:"days",scrollToToday:!0,maxScale:"months",minScale:"days",itemsPerPage:scope.count,months:monthArray,dow:["S","M","T","O","T","F","L"],waitText:"",useCookie:!0,onItemClick:function(data){windowScrollY=window.scrollY,panelScrollX=$(".gantt .rightPanel").scrollLeft();var shouldReload=!1;data.GuidWorkOrder?$modal.open({templateUrl:"app/workOrder/views/editWorkOrderModal.html",size:"lg",controller:"WorkOrderController",resolve:{$stateParams:function(){return{guid:data.GuidWorkOrder,isModal:!0,viewMode:!1,onSaved:function(model){shouldReload=!0,updatedModel=model}}}}}).result.then(function(){shouldReload&&scope.reload()},function(){shouldReload&&scope.reload()}):scope.$root.navigation.go("periodicTask.edit",{guid:data.GuidPeriodicTask,menuGuid:scope.$root.navigation.params.menuGuid})},onAddClick:function(dt,rowId){},onScrollTo:function(){if(updatedModel)return $(".gantt .rightPanel").scrollLeft(panelScrollX),window.scrollTo({top:windowScrollY}),updatedModel=null,{useStandardNavigation:!1}},onRender:function(settings){switch($(".gantt-task-controls, .gantt-task-footer").css("display","block"),$(".gantt-task-controls").height($(".spacer").height()),settings.scale){case"days":$(".row .date").height($(".dataPanel").height()-24),$(".dataPanel").css("background-position","24px 25px");break;case"weeks":$(".row .day").height($(".dataPanel").height()-48),$(".dataPanel").css("background-position","24px 25px");break;case"months":$(".row.year:not(.data-row)").height($(".dataPanel").height()),$(".dataPanel").css("background-position","24px 1px")}}})};scope.tasks&&scope.tasks.length&&renderGantt(),scope.$watchGroup(["tasks"],function(newValues,oldValues,scope){newValues!==oldValues&&newValues&&renderGantt()})}return{restrict:"E",scope:{tasks:"=tasks",viewMode:"=viewMode",filters:"=filters",count:"=count",columnData:"=columnData",reload:"=reload"},controller:["$scope","$modal",controller],templateUrl:"/app/maintenancePlan/gantt.html"}}),function(){function controller($scope,repository,translationService,$filter,$timeout){$scope.hasInitialized=!1,$scope.showFilters=!0,$scope.activateAutocomplete=!1,$scope.tasks=[],$scope.columnData=[],$scope.totalCount=0,$scope.sortingProperty="StartDate",$scope.sortingDirection="desc",$scope.sorting={},$scope.sorting[$scope.sortingProperty]=$scope.sortingDirection,$scope.viewMode="days",$scope.filterValues={dueDateInterval:"nextThreeMonths",showWorkordersWithoutStartDate:!1,searchString:"",autocomplete:{},types:[]},$scope.autocompleteModel={},$scope.loading=!1,$scope.count=100,$scope.totalCount=0;var search=repository.location.search();if(search){if(search.viewMode&&($scope.viewMode=rison.decode_uri(search.viewMode)),search.count&&($scope.count=rison.decode_uri(search.count)),search.filterValues){var storedValues=rison.decode_uri(search.filterValues);"object"==typeof storedValues&&($scope.filterValues.dueDateInterval=storedValues.dueDateInterval||$scope.filterValues.dueDateInterval,$scope.filterValues.autocomplete="object"==typeof storedValues.autocomplete?storedValues.autocomplete:$scope.filterValues.autocomplete,$scope.filterValues.showWorkordersWithoutStartDate=!!storedValues.showWorkordersWithoutStartDate,$scope.filterValues.searchString=storedValues.searchString||$scope.filterValues.searchString,$scope.filterValues.types=Array.isArray(storedValues.types)?storedValues.types:$scope.filterValues.types),$scope.hasInitialized=!0,$scope.showFilters=!1,$timeout(function(){$scope.activateAutocomplete=!!Object.keys($scope.filterValues.autocomplete).length},250)}search.sorting&&($scope.sorting=rison.decode_uri(search.sorting),$scope.sortingProperty=Object.keys($scope.sorting)[0],$scope.sortingDirection=$scope.sorting[$scope.sortingProperty])}$scope.sortingProperties=[{value:"Description",label:translationService.translate("web-maintenancePlan-sorting-description","Beskrivelse"),type:"string"},{value:"StartDate",label:translationService.translate("web-maintenancePlan-sorting-startDate","Startdato"),type:"date"},{value:"EstimatedCost",label:translationService.translate("web-maintenancePlan-sorting-estimatedCost","Estimert kostnad"),type:"string"},{value:"EstimatedTime",label:translationService.translate("web-maintenancePlan-sorting-estimatedTime","Estimert tid"),type:"string"},{value:"Building.Id",label:translationService.translate("web-maintenancePlan-sorting-buildingId","Bygning ID"),typee:"string"},{value:"Building.Description",label:translationService.translate("web-maintenancePlan-sorting-buildingDescription","Bygningsbeskrivelse"),type:"string"},{value:"Equipment.Id",label:translationService.translate("web-maintenancePlan-sorting-equipmentId","Anlegg ID"),type:"string"},{value:"Equipment.Description",label:translationService.translate("web-maintenancePlan-sorting-equipmentDescription","Anleggsbeskrivelse"),type:"string"},{value:"Area.Id",label:translationService.translate("web-maintenancePlan-sorting-areaId","Areal ID"),type:"string"},{value:"ResourceGroup.Id",label:translationService.translate("web-maintenancePlan-sorting-resourceGroupId","Ressurs")},{value:"Type",label:translationService.translate("web-maintenancePlan-sorting-type","Arbeidsordretype")},{value:"ActivityCategory.Description",label:translationService.translate("web-maintenancePlan-sorting-activityCategoryDescription","Kategori")},{value:"Supplier.Description",label:translationService.translate("web-maintenancePlan-sorting-supplierDescription","Leverandør")},{value:"ResponsiblePerson.LastName",label:translationService.translate("web-maintenancePlan-sorting-responsiblePersonLastName","Ansvarlig person - Etternavn")}], $scope.workOrderTypes=[{title:translationService.getEnumTranslation("WorkOrderType","KO"),value:0},{title:translationService.getEnumTranslation("WorkOrderType","PR"),value:1},{title:translationService.getEnumTranslation("WorkOrderType","FV"),value:2},{title:translationService.getEnumTranslation("WorkOrderType","ME"),value:3},{title:translationService.getEnumTranslation("WorkOrderType","TE"),value:4},{title:translationService.getEnumTranslation("WorkOrderType","TK"),value:5},{title:translationService.getEnumTranslation("WorkOrderType","AV"),value:6},{title:translationService.getEnumTranslation("WorkOrderType","Alarm"),value:7},{title:translationService.getEnumTranslation("WorkOrderType","VL"),value:8},{title:translationService.getEnumTranslation("WorkOrderType","TT"),value:9}],$scope.dueDateIntervals=[{title:translationService.translate("web-maintenancePlan-dueDateIntervals-nextMonth","Neste måned"),value:"nextMonth"},{title:translationService.translate("web-maintenancePlan-dueDateIntervals-nextThreeMonths","Neste 3 måneder"),value:"nextThreeMonths"},{title:translationService.translate("web-maintenancePlan-dueDateIntervals-nextHalfYear","Neste halvår"),value:"nextHalfYear"},{title:translationService.translate("web-maintenancePlan-dueDateIntervals-nextYear","Neste år"),value:"nextYear"}];var getDueDateFilters=function(dueDateInterval){switch(dueDateInterval){case"nextMonth":return{Property:"DueDate",Operator:"<=",Value:moment().utc().startOf("day").add(1,"month").toISOString()};case"nextThreeMonths":return{Property:"DueDate",Operator:"<=",Value:moment().utc().startOf("day").add(3,"month").toISOString()};case"nextHalfYear":return{Property:"DueDate",Operator:"<=",Value:moment().utc().startOf("day").add(6,"month").toISOString()};case"nextYear":return{Property:"DueDate",Operator:"<=",Value:moment().utc().startOf("day").add(1,"year").toISOString()};default:return null}},updateUrl=function(count,sorting,filterValues,viewMode){repository.location.search("viewMode",rison.encode_uri(viewMode)).replace(),repository.location.search("count",rison.encode_uri(count)).replace(),repository.location.search("sorting",rison.encode_uri(sorting)).replace(),repository.location.search("filterValues",rison.encode_uri(filterValues)).replace()};$scope.getData=function(){if($scope.hasInitialized){updateUrl($scope.count,$scope.sorting,$scope.filterValues,$scope.viewMode);var filters={ActivityStatus:"Active",Interval:"months"===$scope.viewMode?3:"weeks"===$scope.viewMode?2:1,NumberOfYearsToCalculate:"months"===$scope.viewMode?3:void 0,FilterModel:{Condition:"and",Rules:[]},SearchString:$scope.filterValues.searchString};Array.isArray($scope.filterValues.types)&&$scope.filterValues.types.length&&filters.FilterModel.Rules.push({Property:"Type",Operator:"in",Value:$scope.filterValues.types.join(",")});var dueDateRule=getDueDateFilters($scope.filterValues.dueDateInterval);dueDateRule&&filters.FilterModel.Rules.push(dueDateRule);for(var key in $scope.filterValues.autocomplete){var currentFilterValue=$scope.filterValues.autocomplete[key];currentFilterValue&&filters.FilterModel.Rules.push({Property:key,Operator:"=",Value:currentFilterValue})}$scope.loading=!0,repository.GetPaginated(repository.apiData.maintenance.url,0,$scope.count,$scope.sorting,filters,null).then(function(result){var data=[];result.List.forEach(function(item){var selectedSorting=_.find($scope.sortingProperties,function(o){return o.value===$scope.sortingProperty});$scope.loading=!1;var object={id:item.GuidWorkOrder?item.GuidWorkOrder:item.GuidPeriodicTask,name:item.Title,filterValue:item.Subtitle,filterLabel:selectedSorting.label,detailProperties:[],dataObj:item,values:[]},subtitle="";item.Equipment&&(subtitle+=item.Equipment),item.Area&&(subtitle+=subtitle?" / "+item.Area:item.Area),item.Building&&!repository.commonService.getFilterData().selectedBuilding.Guid&&(subtitle+=subtitle?" / "+item.Building:item.Building),object.subtitle=subtitle,item.Building&&!repository.commonService.getFilterData().selectedBuilding.Guid&&object.detailProperties.push({name:"Bygg",value:item.Building}),item.Equipment&&object.detailProperties.push({name:"Anlegg",value:item.Equipment}),item.Area&&object.detailProperties.push({name:"Areal",value:item.Area}),item.ResourceGroup&&object.detailProperties.push({name:"Ressurs",value:item.ResourceGroup}),item.WorkOrderType&&object.detailProperties.push({name:"Type",value:item.WorkOrderType.Description}),item.ActivityCategory&&object.detailProperties.push({name:"Kategori",value:item.ActivityCategory}),item.Supplier&&object.detailProperties.push({name:"Leverandør",value:item.Supplier}),item.StartDate&&object.detailProperties.push({name:"Start dato",value:$filter("date")(item.StartDate,"dd.MM.yyyy")}),item.EstimatedCost&&object.detailProperties.push({name:"Est. kost",value:item.EstimatedCost}),item.EstimatedTime&&object.detailProperties.push({name:"Est. tid",value:item.EstimatedTime}),item.MaintenanceValues.forEach(function(value){var className=value.IsCompleted?"ganttGreen":value.IsPastDueDate?"ganttRed":"";value.GuidPeriodicTask&&(className="ganttGray transparent-bar"),object.values.push({from:"/Date("+new Date(value.StartDate).getTime()+")/",to:"/Date("+new Date(value.EndDate).getTime()+")/",customClass:className,dataObj:value})}),data.push(object)}),$scope.tasks=data,$scope.columnData=result.ColumnData,$scope.totalCount=result.TotalCount},function(error){$scope.loading=!1,repository.growl(error,"danger")})}},$scope.getData(),$scope.initialize=function(){$scope.hasInitialized||($scope.hasInitialized=!0,$scope.getData())},$scope.addMoreData=function(){$scope.loading||($scope.count+=1e3,$scope.getData())},$scope.lessData=function(){$scope.loading||($scope.count-=1e3,$scope.count<100&&($scope.count=100),$scope.getData())},$scope.setSorting=function(item){$scope.sortingProperty===item.value?($scope.sortingDirection="desc"===$scope.sortingDirection?"asc":"desc",$scope.sorting[$scope.sortingProperty]=$scope.sortingDirection):($scope.sorting={},$scope.sortingProperty=item.value,$scope.sortingDirection="desc",$scope.sorting[$scope.sortingProperty]=$scope.sortingDirection),$scope.getData()},$scope.setViewMode=function(viewMode){$scope.viewMode=viewMode,$scope.getData()},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"ActivityCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}return filter};var watchKeys=["dueDateInterval","showWorkordersWithoutStartDate","searchString","types","autocomplete.GuidBuilding","autocomplete.GuidEquipment","autocomplete.GuidArea","autocomplete.GuidResourceGroup","autocomplete.GuidPriority","autocomplete.GuidActivityCategory","autocomplete.GuidResponsiblePerson","autocomplete.GuidSupplier"].map(function(key){return"filterValues."+key});$scope.$watchGroup(watchKeys,function(newValues,oldValues){for(var hasChanged=!1,i=0;i
    ')($scope)}else $scope.clustermarkers=a.markers.map(function(mark){return{entity:mark.feature.properties.entity,entityGuid:mark.feature.properties.entityGuid,caption:mark.feature.properties.caption}}),message=$compile("")($scope);a.cluster.closePopup(),a.cluster.bindPopup(message[0]),setTimeout(function(){a.cluster.openPopup()},100)}function createMarkerClusterGroup(clusterRadius){null!==clusterRadius&&void 0!==clusterRadius&&"number"==typeof clusterRadius||(clusterRadius=20);var markerGroup=L.markerClusterGroup({spiderfyDistanceMultiplier:1,showCoverageOnHover:!1,removeOutsideVisibleBounds:!0,maxClusterRadius:clusterRadius<=0?1:clusterRadius,chunkedLoading:!0});return markerGroup.on("spiderfied",onClickSpiderified),markerGroup}function getMarker(feature){var key=feature.properties.icon+feature.properties.markerColor+feature.properties.shape;if(markerCache[key])return markerCache[key];var mark=L.ExtraMarkers.icon({icon:iconService.getMapIcon(feature.properties.icon),markerColor:feature.properties.markerColor,shape:feature.properties.shape,prefix:"fa",type:"extraMarker",svg:feature.properties.markerColor&&feature.properties.markerColor.startsWith("#")});return markerCache[key]=mark,mark}function pointToLayer(feature,latlng){var mark=getMarker(feature),message="";message="workOrder"===$scope.selectedTheme?"
    ':'

    '+feature.properties.caption+"

    ";var marker=L.marker(latlng,{icon:mark}).bindPopup(message);return marker.on("popupopen",function(){safeApply(function(){marker.openPopup();var popup=marker.getPopup();$compile(popup._contentNode)($scope);var unregister=$scope.$on("$includeContentLoaded",function(){popup._updateLayout(),popup._updatePosition(),unregister()})})}),marker}function style(feature){return"LineString"===feature.geometry.type?{color:feature.properties.color,weight:feature.properties.weight,opacity:feature.properties.opacity}:{}}function centerOnMarkers(features){var latLngs=[];if(features.forEach(function(feature){"Point"===feature.geometry.type?Array.isArray(feature.geometry.coordinates)&&2===feature.geometry.coordinates.length&&latLngs.push(new L.LatLng(feature.geometry.coordinates[1],feature.geometry.coordinates[0])):"LineString"===feature.geometry.type&&Array.isArray(feature.geometry.coordinates)&&feature.geometry.coordinates.forEach(function(coordinate){Array.isArray(coordinate)&&latLngs.push(new L.LatLng(coordinate[1],coordinate[0]))})}),latLngs.length){var bounds=new L.LatLngBounds(latLngs),existingZoom=map.getZoom();map.fitBounds(bounds,{padding:[50,50]});0===map.getZoom()&&map.setZoom(existingZoom)}shouldCenterOnMarkers=!1}function onReloadData(){map.removeLayer(markerGroup),markerGroup.clearLayers();var filters={};for(var property in $scope.panelFilter)filters[property]=$scope.panelFilter[property];repository.GetPaginated(repository.apiData.gisManagement.url,0,-1,{},filters).then(function(result){shouldCenterOnMarkers&&!coordinatesInUrlParams?centerOnMarkers(result.features):urlParams.lat&&(coordinatesInUrlParams=!1,map.setView({lat:urlParams.lat,lng:urlParams.lng},urlParams.zoom));var clusterRadius=1;result.features.length>=1e5?clusterRadius=80:result.features.length>=5e4?clusterRadius=60:result.features.length>=1e4?clusterRadius=40:result.features.length>=500&&(clusterRadius=10),markerGroup=createMarkerClusterGroup(clusterRadius),map.addLayer(markerGroup),geoJsonLayer=L.geoJson(result,{pointToLayer:pointToLayer,style:style}),markerGroup.addLayer(geoJsonLayer)})}function addFilterWatcher(watch){filterWatcher=$scope.$watch(watch,function(newValue,oldValue){newValue!==oldValue&&(onReloadData(),updateUrlParams({theme:$scope.selectedTheme,panelFilter:JSON.stringify($scope.panelFilter)}))},!0)}var urlParams=$location.search(),coordinatesInUrlParams=!!urlParams.lat,shouldCenterOnMarkers=!coordinatesInUrlParams;$scope.iconMap=iconService.getIconsForMapUsage(),$scope.showFilter=!0,$scope.panelFilter={showBasicData:!0},$scope.selectedTheme=urlParams.theme?urlParams.theme:"basicData",$scope.dropdownFilters={estateCategory:{list:[]},buildingCategory:{list:[]},equipmentCategory:{list:[]},unoXCoLocation:{list:[]}},$scope.themeSelections=[{label:translationService.translate("web-map-toolbar-selectTheme-Basicdata","Grunndata"),value:"basicData"},{label:translationService.translate("web-map-toolbar-selectTheme-request","Meldinger"),value:"request"},{label:translationService.translate("web-map-toolbar-selectTheme-workOrder","Arbeidsordre"),value:"workOrder"}];var delayParams=!0,settings=getSettings();$scope.entityInfos=settings.entityInfo||{};var map=L.map("map").setView([63.43,10.4],5);L.tileLayer(settings.TileLayer,settings.TileLayerOptions).addTo(map);var markerGroup=createMarkerClusterGroup();map.addLayer(markerGroup);var markerCache={};$scope.requestFilterStatusChange=function(newValue){$scope.panelFilter.request.status=newValue,shouldCenterOnMarkers||(shouldCenterOnMarkers=!0,onReloadData())};var filterWatcher=function(){};$scope.themeChanged=function(panelFilter){filterWatcher(),"basicData"===$scope.selectedTheme&&($scope.panelFilter=panelFilter||{showBasicData:!0,basicData:{showEstate:!0,showBuilding:!0,showEquipment:!1,guidEstateCategories:[],guidBuildingCategories:[],guidEquipmentCategories:[],unoXCoLocations:[]}},addFilterWatcher("panelFilter.basicData")),"workOrder"===$scope.selectedTheme&&($scope.panelFilter=panelFilter||{showWorkOrder:!0},addFilterWatcher("panelFilter.workOrder")),"request"===$scope.selectedTheme&&($scope.panelFilter=panelFilter||{showRequest:!0,request:{status:[0,1,6]}},addFilterWatcher("panelFilter.request")),updateUrlParams({theme:$scope.selectedTheme,panelFilter:JSON.stringify($scope.panelFilter)}),shouldCenterOnMarkers=!0,onReloadData()},$scope.themeChanged(urlParams.panelFilter?JSON.parse(urlParams.panelFilter):null),function(){var commonFilter={FilterModel:{Condition:"and",Rules:[{Property:"IsAbstract",Operator:"=",Value:!1}]}};$scope.hasReadAccess("EstateCategory")&&repository.GetPaginated(repository.apiData.estateCategory.url,0,-1,{Description:"asc"},commonFilter).then(function(response){$scope.dropdownFilters.estateCategory.hasError=!1,$scope.dropdownFilters.estateCategory.list=response.List},function(){$scope.dropdownFilters.estateCategory.hasError=!0}),$scope.hasReadAccess("BuildingCategory")&&repository.GetPaginated(repository.apiData.buildingCategory.url,0,-1,{Description:"asc"},commonFilter).then(function(response){if($scope.dropdownFilters.buildingCategory.hasError=!1,$scope.dropdownFilters.buildingCategory.list=response.List,$scope.customization.isCustomer("UnoX")){var getAllItems=function(category){var items=[];return category&&category.Groups?(category.Groups.forEach(function(group){group.Items&&group.Items.forEach(function(item){"Category"===item.Type?item.Template&&getAllItems(item.Template).forEach(function(i){items.push(i)}):items.push(item)})}),items):items},coLocationOptions=[];response.List.forEach(function(buildingCategory){var items=getAllItems(buildingCategory.DynamicProperty),coLocation=items.find(function(item){return"Combo"===item.Type&&0===item.Field});coLocation&&coLocation.NamedSelectionOptions&&coLocation.NamedSelectionOptions.forEach(function(option){coLocationOptions.includes(option)||coLocationOptions.push(option)})}),$scope.dropdownFilters.unoXCoLocation.list=coLocationOptions.sort()}},function(){$scope.dropdownFilters.buildingCategory.hasError=!0}),$scope.hasReadAccess("EquipmentCategory")&&repository.GetPaginated(repository.apiData.equipmentCategory.url,0,-1,{Description:"asc"},commonFilter).then(function(response){$scope.dropdownFilters.equipmentCategory.hasError=!1,$scope.dropdownFilters.equipmentCategory.list=response.List},function(){$scope.dropdownFilters.equipmentCategory.hasError=!0})}(),map.on("moveend",function(){safeApply(function(){updateUrlParams({zoom:map.getZoom(),lat:map.getCenter().lat,lng:map.getCenter().lng})})}),$scope.$on($scope.events.newSelection,function(){shouldCenterOnMarkers=!0,onReloadData()})}angular.module("Plania").controller("MapController",["$scope","Repository","TranslationService","$timeout","$localStorage","Constants","$compile","$location","IconService",controller])}(),function(){angular.module("Plania").factory("MapService",["$localStorage",function($localStorage){var service={};return service.getPropertyFilter=function(entity,params){return[]},service}])}(),function(){function workOrderMapMessageController($scope,$modal,repository,ngTableParams,$stateParams){$scope.workOrders=[],$scope.modalInstance={},$scope.isLoading=!0;var propertyFilter=repository.mapService.getPropertyFilter("workOrder",$stateParams);$scope.workOrderPopover={content:"test",templateUrl:"workOrderPopover.html"},$scope.init=function(entityType,guid,caption,activityStatus,isCluster,buildingGuids,estateGuids,equipmentGuids){$scope.entityGuid=guid,$scope.caption=caption,$scope.navigationState=entityType,isCluster?("History"!==activityStatus&&(activityStatus="Active"),buildingGuids&&propertyFilter.push({Property:"GuidBuilding",Operator:"in",value:buildingGuids}),estateGuids&&propertyFilter.push({Property:"GuidEstate",Operator:"in",value:estateGuids,Operand:"or"}),equipmentGuids&&propertyFilter.push({Property:"GuidEquipment",Operator:"in",value:equipmentGuids,Operand:"or"})):propertyFilter.push({Property:entityType+".Guid",Operator:"=",Value:guid});var columns=["Id","Description","Building.Id","Building.Description","DueDate","Estate.Id","Estate.Description","Equipment.Id","Equipment.Description"];$scope.workOrderTableSmall=new ngTableParams({page:1,count:10,filter:{ActivityStatus:activityStatus,PropertyFilter:propertyFilter},sorting:{Id:"asc"}},{total:0,counts:[],paginationMaxBlocks:6,getData:function($defer,params){repository.GetPaginated(repository.apiData.workOrder.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){0===result.TotalCount?$scope.listIsEmpty=!0:$scope.listIsEmpty=!1,$scope.isLoading=!1,params.total(result.TotalCount),$defer.resolve(result.List)},function(error){$scope.isLoading=!1,repository.growl(error,"danger")})}})},$scope.openWOEdit=function(workOrderGuid){$modal.open({templateUrl:"app/workOrder/views/editWorkOrderModal.html",size:"lg",animation:!1,controller:"WorkOrderController",resolve:{$stateParams:function(){return{guid:workOrderGuid,isModal:!0}}}})},$scope.dateExpired=function(dueDate){return!!dueDate&&new Date(dueDate).getTime()<(new Date).getTime()}}angular.module("Plania").controller("WorkOrderMapMessageController",["$scope","$modal","Repository","ngTableParams","$stateParams",workOrderMapMessageController])}(),function(){function controller($scope,$modal,ngTableParams,repository,$rootScope,translationService,operationalMessageService){$scope.messagesIsLoading=!1,$scope.search={};var updateAccess=function(){$scope.hasReadAccess=$rootScope.hasReadAccess("OperationalMessage"),$scope.hasEditAccess=$rootScope.hasEditAccess("OperationalMessage"),$scope.hasCreateAccess=$rootScope.hasCreateAccess("OperationalMessage"),$scope.hasDeleteAccess=$rootScope.hasDeleteAccess("OperationalMessage")};updateAccess();var filterTypes=operationalMessageService.getCommonFilterTypes();$scope.selectedFilter=_.find(filterTypes,{value:"active"}),$scope.setFilter=function(filterType){var filter=_.find(filterTypes,{value:filterType});filter&&($scope.selectedFilter=filter,$scope.operationalMessageTable.reload(),$scope.showFilterDropdown=!1)};var getFilterModel=function(){var filterModel={Condition:"and",Rules:[{Property:"Guid"+$scope.parentEntity,Operator:"=",Value:$scope.guid}]},commonFilter=operationalMessageService.getCommonFilterModel($scope.selectedFilter.value);return commonFilter&&commonFilter.Rules&&Array.isArray(commonFilter.Rules)&&commonFilter.Rules.length&&commonFilter.Rules.forEach(function(f){filterModel.Rules.push(f)}),filterModel};$scope.$watch("reload",function(newValue,oldValue){newValue!==oldValue&&$scope.reload&&!0===$scope.reload&&($scope.operationalMessageTable.reload(),$scope.reload=!1)});var columns=["Message","DueDate","Type","StartDate","Status","ContactPerson.FirstName","ContactPerson.LastName","Equipment.Id","Equipment.Description","Equipment.Building.Id","Equipment.Building.Description","Equipment.Building.Estate.Id","Equipment.Building.Estate.Description","Building.Id","Building.Description","Building.Estate.Id","Building.Estate.Description","Estate.Id","Estate.Description","WorkOrder.Id","WorkOrder.Description"];$scope.operationalMessageTable=new ngTableParams({page:1,count:5,sorting:{DueDate:"desc"}},{total:0,counts:[5,10,20],filterDelay:50,paginationMaxBlocks:6,getData:function($defer,params){var filter=angular.copy(params.filter());filter.FilterModel=getFilterModel(),$scope.messagesIsLoading=!0,repository.GetPaginated(repository.apiData.operationalMessage.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){if($scope.operationalMessageTable.settings().total=result.TotalCount,$scope.operationalMessageTable.settings().filterDelay=500,$scope.operationalMessages||($scope.operationalMessages=[]),$scope.operationalMessages)for(;$scope.operationalMessages.length>0;)$scope.operationalMessages.pop();result.List.forEach(function(message){message.startDateText=operationalMessageService.getStartDateText(message),message.dueDateText=operationalMessageService.getDueDateText(message),$scope.operationalMessages.push(message)}),$defer.resolve(result.List),$scope.messagesIsLoading=!1},function(error){repository.growl(error,"danger")})}}),$scope.create=function(type){$modal.open({templateUrl:"app/operationalMessage/views/operationalMessageModal.html",controller:"OperationalMessageModalController",resolve:{params:function(){return{parentGuid:$scope.guid,parentEntityType:$scope.parentEntity,parentModel:$scope.parentModel}}}}).result.then(function(){$scope.operationalMessageTable.reload()},function(){$scope.operationalMessageTable.reload()})},$scope.open=function(message){$modal.open({templateUrl:"app/operationalMessage/views/operationalMessageModal.html",controller:"OperationalMessageModalController",resolve:{params:function(){return{guid:message.Guid}}}}).result.then(function(){$scope.operationalMessageTable.reload()},function(){})},$scope.remove=function(message){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-operationalMessage-message","Driftsmeldingen vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-operationalMessage-button-confirm","Ja, fjern driftsmeldingen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.deleteSingle(repository.apiData.operationalMessage.url,message.Guid).then(function(result){swal(translationService.translate("web-swal-operationalMessage-success","Driftsmeldingen ble fjernet!"),result,"success"),$scope.operationalMessageTable.reload()},function(error){swal("Error",error,"error")})})},$scope.connectOperationalMessage=function(){var operationalMessageColumns=[{Position:1,Title:translationService.translate("web-operationalMessage-type"),Property:"Type",PropertyType:"enum.OperationalMessageType"},{Position:2,Title:translationService.translate("web-operationalMessage-equipment-id","Anleggsnr"),Property:"Equipment.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-operationalMessage-equipment-description","Anleggsnavn"),Property:"Equipment.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-operationalMessage-message"),Property:"Message",PropertyType:"string"},{Position:5,Title:translationService.translate("web-operationalMessage-startDate"),Property:"StartDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-operationalMessage-dueDate"),Property:"DueDate",PropertyType:"date"}],propertyFilter=[{Property:"GuidWorkOrder",Operator:"=",Value:null}];$scope.parentModel.GuidBuilding&&$scope.parentModel.Building&&propertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:$scope.parentModel.GuidBuilding,allowToggle:!0,isDisabled:!1,filterValue:$scope.parentModel.Building.Caption}),$scope.parentModel.GuidEquipment&&$scope.parentModel.Equipment&&propertyFilter.push({Property:"GuidEquipment",Operator:"=",Value:$scope.parentModel.GuidEquipment,allowToggle:!0,isDisabled:!1,filterValue:$scope.parentModel.Equipment.Caption}),$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:translationService.translate("web-operational-message-choose","Velg driftsmelding"),columns:operationalMessageColumns,useObjects:!0,url:repository.apiData.operationalMessage.url,sorting:{DueDate:"desc"},filter:{PropertyFilter:propertyFilter}}}}}).result.then(function(operationalMessages){if(operationalMessages.length>0){var changeList=[];operationalMessages.forEach(function(operationalMessage){changeList.push({Guid:operationalMessage.Guid,GuidWorkOrder:$scope.guid})}),repository.patch(repository.apiData.operationalMessage.url,null,changeList).then(function(result){repository.growl(translationService.translate("operationalMessageList-addMultiple-success","Driftsmeldingene har blitt lagt til"),"success"),$scope.operationalMessageTable.reload()},function(error){repository.growl(error,"danger"),$scope.operationalMessageTable.reload()})}})},$scope.getLowestEntityCaption=operationalMessageService.getLowestEntityCaption,$scope.getEntityIcon=operationalMessageService.getEntityIcon;var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.menuOptions=function(message){var options=[];return $scope.hasReadAccess&&options.push({html:' '+translationService.translate("web-operationalMessage-menuOption-view","Åpne")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.open(message)}}),message.GuidWorkOrder&&$scope.hasEditAccess&&options.push({html:' '+translationService.translate("web-operationalMessage-menuOption-removeWorkOrder","Fjern fra arbeidsordren")+"",click:function(){repository.patch(repository.apiData.operationalMessage.url,message.Guid,{GuidWorkOrder:null}).then(function(response){repository.growl(translationService.translate("web-operationalMessage-removeWorkOrder-success","Driftsmeldingen ble fjernet fra arbeidsordren"),"success"),$scope.operationalMessageTable.reload()},function(error){repository.showError(error)})}}),message.GuidEstate&&message.GuidEstate!==$scope.guid&&options.push(getMenuLink($rootScope.navigation.href("estate.edit",{guid:message.GuidEstate}),translationService.translate("web-operationalMessage-menuOption-viewEstate","Gå til eiendom"))),message.GuidBuilding&&message.GuidBuilding!==$scope.guid&&options.push(getMenuLink($rootScope.navigation.href("building.edit",{guid:message.GuidBuilding}),translationService.translate("web-operationalMessage-menuOption-viewBuilding","Gå til bygg"))),message.GuidEquipment&&message.GuidEquipment!==$scope.guid&&options.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:message.GuidEquipment }),translationService.translate("web-operationalMessage-menuOption-viewEquipment","Gå til anlegg"))),message.GuidWorkOrder&&message.GuidWorkOrder!==$scope.guid?options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:message.GuidWorkOrder}),translationService.translate("web-operationalMessage-menuOption-viewWorkOrder","Gå til arbeidsodre"))):!message.GuidWorkOrder&&$rootScope.hasCreateAccess("WorkOrder")&&options.push({html:' '+translationService.translate("web-operationalMessage-menuOption-createWorkOrder","Opprett arbeidsordre")+"",click:function(){operationalMessageService.createWorkOrder(message)}}),$scope.hasDeleteAccess&&options.push({html:' '+translationService.translate("web-operationalMessage-menuOption-delete","Slett")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.remove(message)}}),options},$scope.$on($rootScope.events.newSelection,function(){updateAccess(),$scope.operationalMessageTable.reload()})}angular.module("Plania").directive("operationalMessage",function(){return{restrict:"E",scope:{isCollapsed:"=isCollapsed",reload:"=reload",operationalMessages:"=operationalMessages",disableActions:"=disableActions",parentEntity:"=parentEntity",parentModel:"=parentModel",guid:"=guid",restrictEdit:"=restrictEdit"},controller:["$scope","$modal","ngTableParams","Repository","$rootScope","TranslationService","OperationalMessageService",controller],link:function(scope,element,attrs){},templateUrl:"app/operationalMessage/views/operationalMessageDirective.html"}})}(),function(){function controller($scope,repository,params,$modalInstance,$modal,$localStorage,translationService,operationalMessageService){$scope.isUpdate=!!params.guid,$scope.activateAutocomplete=!1,$scope.model={canCreateDowntime:!1},$scope.guid=params.guid,$scope.parentGuid=params.parentGuid,$scope.parentEntityType=params.parentEntityType,$scope.parentModel=params.parentModel,$scope.timepickerOptions={hstep:1,mstep:5};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner&&$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.OperationalMessage,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.OperationalMessage,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.OperationalMessage),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.OperationalMessage)};updateAccess(),$scope.onWorkOrderSelect=function(workOrder){if(!workOrder)return void($scope.model.GuidWorkOrder="");$scope.model.GuidWorkOrder=workOrder.Guid},$scope.onEquipmentSelect=function(equipment){if(!equipment)return $scope.model.GuidEquipment="",$scope.model.Type="Information",void($scope.model.canCreateDowntime=!1);$scope.model.GuidEquipment=equipment.Guid,$scope.model.canCreateDowntime=equipment.CanHaveDowntime,$scope.model.canCreateDowntime?$scope.model.Type="Downtime":$scope.model.Type="Information",$scope.model.GuidEstate&&""!==$scope.model.GuidEstate||($scope.model.GuidEstate=equipment.GuidEstate||equipment.Building.Estate.Guid),$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=equipment.GuidBuilding)},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidEquipment="",$scope.model.Type="Information",$scope.model.canCreateDowntime=!1),$scope.model.GuidBuilding=building.Guid,$scope.model.GuidEstate&&""!==$scope.model.GuidEstate&&$scope.model.GuidEstate===building.GuidEstate||($scope.model.GuidEstate=building.GuidEstate)},$scope.onEstateSelect=function(estate){if(!estate)return void($scope.model.GuidEstate="");$scope.model.GuidEstate!==estate.Guid&&($scope.model.GuidBuilding="",$scope.model.GuidEquipment="",$scope.model.Type="Information",$scope.model.canCreateDowntime=!1),$scope.model.GuidEstate=estate.Guid};var updateDateTexts=function(){$scope.model.startDateDisplayText=operationalMessageService.getStartDateText($scope.model),$scope.model.dueDateDisplayText=operationalMessageService.getDueDateText($scope.model)},columns=["Estate.Id","Estate.Description","Building.Id","Building.Description","Equipment.Id","Equipment.Description","Equipment.CanHaveDowntime","WorkOrder.Id","WorkOrder.Description","ContactPerson.FirstName","ContactPerson.LastName","UserUpdatedBy.RealName","UserUpdatedBy.RealName"];$scope.setupAutoSelect=function(){angular.element(document.querySelectorAll(".time-picker-container input")).on("focus",function(){this.select()})},$scope.$watch("model.StartDate",function(newValue){newValue&&setTimeout(function(){$scope.setupAutoSelect()},250)}),$scope.$watch("model.DueDate",function(newValue){newValue&&setTimeout(function(){$scope.setupAutoSelect()},250)});var getMessage=function(){repository.getSingle(repository.apiData.operationalMessage.url,params.guid,JSON.stringify(columns)).then(function(result){$scope.model=result.Data,$scope.model.Equipment&&($scope.model.canCreateDowntime=$scope.model.Equipment.CanHaveDowntime),$scope.model.StartDate&&($scope.model.StartTime=new Date($scope.model.StartDate)),$scope.model.DueDate&&($scope.model.DueTime=new Date($scope.model.DueDate)),updateDateTexts(),updateAccess(),setTimeout(function(){$scope.activateAutocomplete=!0,$scope.setupAutoSelect()},250)},function(error){repository.growl(error,"danger")})};params.guid?getMessage():($scope.model={},$scope.parentGuid&&$scope.parentEntityType&&($scope.model["Guid"+$scope.parentEntityType]=$scope.parentGuid,$scope.parentModel&&$scope.parentModel.Caption&&($scope.model[$scope.parentEntityType]=$scope.parentModel)),"WorkOrder"===$scope.parentEntityType?($scope.parentModel&&$scope.parentModel.GuidEquipment&&($scope.model.GuidEquipment=$scope.parentModel.GuidEquipment,$scope.parentModel.Equipment&&$scope.parentModel.Equipment.Caption&&($scope.model.canCreateDowntime=$scope.parentModel.Equipment.CanHaveDowntime,$scope.model.Equipment=$scope.parentModel.Equipment)),$scope.parentModel&&$scope.parentModel.GuidBuilding&&($scope.model.GuidBuilding=$scope.parentModel.GuidBuilding,$scope.parentModel.Building&&$scope.parentModel.Building.Caption&&($scope.model.Building=$scope.parentModel.Building)),$scope.parentModel&&$scope.parentModel.GuidEstate&&($scope.model.GuidEstate=$scope.parentModel.GuidEstate,$scope.parentModel.Estate&&$scope.parentModel.Estate.Caption&&($scope.model.Estate=$scope.parentModel.Estate))):"Equipment"===$scope.parentEntityType?($scope.model.canCreateDowntime=$scope.parentModel&&$scope.parentModel.CanHaveDowntime,$scope.parentModel&&$scope.parentModel.GuidBuilding&&($scope.model.GuidBuilding=$scope.parentModel.GuidBuilding,$scope.parentModel.Building&&$scope.parentModel.Building.Caption&&($scope.model.Building=$scope.parentModel.Building)),$scope.parentModel&&$scope.parentModel.Building&&($scope.parentModel.Building.GuidEstate||$scope.parentModel.Building.Estate)&&($scope.model.GuidEstate=$scope.parentModel.Building.GuidEstate?$scope.parentModel.Building.GuidEstate:$scope.parentModel.Building.Estate.Guid,$scope.parentModel.Building.Estate&&$scope.parentModel.Building.Estate.Caption&&($scope.model.Estate=$scope.parentModel.Building.Estate))):"Building"===$scope.parentEntityType&&$scope.parentModel&&$scope.parentModel.GuidEstate&&($scope.model.GuidEstate=$scope.parentModel.GuidEstate,$scope.parentModel.Estate&&$scope.parentModel.Estate.Caption&&($scope.model.Estate=$scope.parentModel.Estate)),$scope.model.Type=$scope.model.canCreateDowntime?"Downtime":"Information",$scope.model.StartDate=(new Date).setMinutes(0),$scope.model.StartTime=(new Date).setMinutes(0),updateAccess(),$scope.activateAutocomplete=!0),$scope.save=function(action){var saveDto=angular.copy($scope.model);if(saveDto.DueDate){var dueDate=new Date(saveDto.DueDate);if(saveDto.DueTime){var dueTime=new Date(saveDto.DueTime);dueDate.setHours(dueTime.getHours(),dueTime.getMinutes(),dueTime.getSeconds())}saveDto.DueDate=dueDate.toISOString()}if(saveDto.StartDate){var startDate=new Date(saveDto.StartDate);if(saveDto.StartTime){var startTime=new Date(saveDto.StartTime);startDate.setHours(startTime.getHours(),startTime.getMinutes(),startTime.getSeconds())}saveDto.StartDate=startDate.toISOString()}params.guidEquipment&&(saveDto.GuidEquipment=params.guidEquipment),delete saveDto.Estate,delete saveDto.Building,delete saveDto.Area,delete saveDto.Equipment,delete saveDto.ContactPerson,delete saveDto.WorkOrder,params.guid?repository.updateSingle(repository.apiData.operationalMessage.url,saveDto).then(function(result){repository.growl(translationService.translate("web-operationalMessage-updated","Driftsmelding oppdatert"),"success"),$modalInstance.close("ok")}).catch(function(error){repository.growl(error,"danger")}):repository.createSingle(repository.apiData.operationalMessage.url,saveDto).then(function(result){repository.growl(translationService.translate("web-operationalMessage-created","Driftsmeldingen ble lagt til"),"success"),$modalInstance.close("ok")}).catch(function(error){repository.growl(error,"danger")})},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"building":return $scope.model.GuidEstate?{PropertyFilter:[{Property:"GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]}:filter;case"equipment":return filter.PropertyFilter=[{Property:"IsTemplate",Operator:"=",Value:!1}],$scope.model.GuidBuilding?filter.PropertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:$scope.model.GuidBuilding}):$scope.model.GuidEstate&&filter.PropertyFilter.push({Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}),filter;case"workorder":return filter.PropertyFilter=[],$scope.model.GuidBuilding?filter.PropertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:$scope.model.GuidBuilding}):$scope.model.GuidEstate&&filter.PropertyFilter.push({Property:"GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}),filter.PropertyFilter.push({Property:"EndDate",Operator:"=",Value:null}),filter;default:return filter}},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("OperationalMessageModalController",["$scope","Repository","params","$modalInstance","$modal","$localStorage","TranslationService","OperationalMessageService",controller])}(),function(){function operationalMessageService(repository,translationService,$filter,$rootScope){var service={};return service.getCommonFilterTypes=function(){return[{value:"active",name:translationService.translate("web-operationalMessage-filterType-active","Aktive")},{value:"planned",name:translationService.translate("web-operationalMessage-filterType-planned","Planlagt")},{value:"history",name:translationService.translate("web-operationalMessage-filterType-history","Historiske")},{value:"all",name:translationService.translate("web-operationalMessage-filterType-all","Alle")}]},service.getCommonFilterModel=function(filterType){var filterModel={Condition:"and",Rules:[]};switch(filterType){case"active":filterModel.Rules.push({Property:"StartDate",Operator:"<=",Value:moment().startOf("day").toISOString()}),filterModel.Rules.push({Condition:"or",Rules:[{Property:"DueDate",Operator:">=",Value:moment().toISOString()},{Property:"DueDate",Operator:"=",Value:null}]});break;case"planned":filterModel.Rules.push({Property:"StartDate",Operator:">",Value:moment().startOf("day").toISOString()});break;case"history":filterModel.Rules.push({Property:"DueDate",Operator:"<",Value:moment().toISOString()})}return filterModel},service.getEntityIcon=function(operationalMessage){return operationalMessage.Equipment?"fa-gear c-bluegray":operationalMessage.Building?"fa-building-columns c-brown":operationalMessage.Estate?"fa-city c-teal":void 0},service.getLowestEntityCaption=function(message){if(!message)return"";if(message.Equipment){var caption="";return caption=message.Equipment.Caption,message.Building&&(caption+=" ("+message.Building.Id+")"),caption}return message.Building?message.Building.Caption:message.Estate?message.Estate.Caption:void 0},service.getStartDateText=function(message){if(!message||!message.StartDate)return"";try{var startDate=moment(message.StartDate).startOf("day"),today=moment().startOf("day"),dayDifference=startDate.diff(today,"days");return dayDifference<0?message.DueDate?"":-1===dayDifference?translationService.translate("web-operationalMessage-startDateText-yesterday","Startet i går"):dayDifference<-15?translationService.translate("web-operationalMessage-startDateText-pastDate","Startet")+" "+$filter("date")(message.StartDate,"dd.MM.yyyy"):translationService.translate("web-operationalMessage-startDateText-pastDays-prefix","Startet for")+" "+-1*dayDifference+" "+translationService.translate("web-operationalMessage-startDateText-pastDays-suffix","dager siden"):0===dayDifference?translationService.translate("web-operationalMessage-startDateText-today","Starter i dag"):1===dayDifference?translationService.translate("web-operationalMessage-startDateText-tomorrow","Starter i morgen"):dayDifference>15?translationService.translate("web-operationalMessage-startDateText-atDate","Starter")+" "+$filter("date")(message.StartDate,"dd.MM.yyyy"):translationService.translate("web-operationalMessage-startDateText-atDays-prefix","Starter om")+" "+dayDifference+" "+translationService.translate("web-operationalMessage-startDateText-atDays-suffix","dager")}catch(error){return""}},service.getDueDateText=function(message){if(!message||!message.DueDate)return"";try{var dueDate=moment(message.DueDate).startOf("day"),today=moment().startOf("day"),dayDifference=dueDate.diff(today,"days");return dayDifference<0?"":0===dayDifference?translationService.translate("web-operationalMessage-dueDateText-today","Slutter i dag"):1===dayDifference?translationService.translate("web-operationalMessage-dueDateText-tomorrow","Slutter i morgen"):dayDifference>30?translationService.translate("web-operationalMessage-dueDateText-atDate","Slutter")+" "+$filter("date")(message.DueDate,"dd.MM.yyyy"):translationService.translate("web-operationalMessage-dueDateText-atDays-prefix","Slutter om")+" "+dayDifference+" "+translationService.translate("web-operationalMessage-dueDateText-atDays-suffix","dager")}catch(error){return""}},service.createWorkOrder=function(operationalMessage){if(operationalMessage.GuidWorkOrder)return void swal(translationService.translate("web-operationalMessage-createWorkOrder-alreadyConnectedToWorkOrder-title","Kan ikke opprette arbeidsordre."),translationService.translate("web-operationalMessage-createWorkOrder-alreadyConnectedToWorkOrder-message","Kan ikke opprette arbeidsordre for en driftsmelding som allerede er knyttet til en arbeidsordre."));var workOrder={fromOperationalMessage:!0,guidSelections:[operationalMessage.Guid],StartDate:(new Date).toISOString(),defaultDescription:operationalMessage.Message};operationalMessage.GuidEstate&&(workOrder.guidEstate=operationalMessage.GuidEstate,operationalMessage.Estate&&(workOrder.estate=[operationalMessage.Estate.Id,operationalMessage.Estate.Description].filter(function(x){return!!x}).join(" - "))),operationalMessage.GuidBuilding&&(workOrder.guidBuilding=operationalMessage.GuidBuilding,operationalMessage.Building&&(workOrder.building=[operationalMessage.Building.Id,operationalMessage.Building.Description].filter(function(x){return!!x}).join(" - "))),operationalMessage.GuidEquipment&&(workOrder.guidEquipment=operationalMessage.GuidEquipment,operationalMessage.Equipment&&(workOrder.equipment=[operationalMessage.Equipment.Id,operationalMessage.Equipment.Description].filter(function(x){return!!x}).join(" - "))),repository.persistedData.setPersistedData("workOrder.create",workOrder),$rootScope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})},service}angular.module("Plania").factory("OperationalMessageService",["Repository","TranslationService","$filter","$rootScope",operationalMessageService])}(),function(){function controller($scope,repository,$stateParams,$modal,$modalStack,ngTableParams,$window,translationService,$localStorage,listService){$scope.isUpdate="paymentOrderForm.edit"===$scope.navigation.current.name,$scope.model={Guid:$stateParams.guid};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.PaymentOrderForm,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.PaymentOrderForm,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.PaymentOrderForm),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.PaymentOrderForm)},columns=["Report.Name"];$scope.isUpdate&&repository.getSingle(repository.apiData.paymentOrderForm.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.reload=!0,updateAccess()},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("web-paymentOrderForm-update-success","Fakturablankett har blitt oppdatert."):translationService.translate("web-paymentOrderForm-create-success","Fakturablankett har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.paymentOrderForm.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.paymentOrderForm.url,$scope.model).then(success,error)},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"report":return filter.FilterModel={Condition:"or",Rules:[{Property:"ReportType",Operator:"=",Value:"1"},{Property:"ReportType",Operator:"=",Value:"2"}]},filter}return filter},$scope.delete=function(){}}angular.module("Plania").controller("PaymentOrderFormController",["$scope","Repository","$stateParams","$modal","$modalStack","ngTableParams","$window","TranslationService","$localStorage","ListService",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,ngTableParams,translationService,listService){$scope.isUpdate="paymentTerm.edit"===$scope.navigation.current.name,$scope.model={};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.PaymentTerm,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.PaymentTerm,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.PaymentTerm),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.PaymentTerm)};$scope.isUpdate?repository.getSingle(repository.apiData.paymentTerm.url,$stateParams.guid).then(function(response){$scope.model=response.Data,$scope.reload=!0,updateAccess()},function(error){repository.growl(error,"danger")}):$scope.model.Type=0,$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-payment-term-success","Betalingsbetingelse har blitt oppdatert."):translationService.translate("create-payment-term-success","Betalingsbetingelse har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.paymentTerm.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.paymentTerm.url,$scope.model).then(success,error)}}angular.module("Plania").controller("PaymentTermController",["$scope","Repository","$stateParams","$modal","ngTableParams","TranslationService","ListService",controller])}(),function(){function controller($scope,repository,params,ngTableParams,$filter,$modalInstance,authService,translationService,listService,$localStorage,$q,registeredFieldService){$scope.allRowsSelected=!1,$scope.selectedItems=[],$scope.GetPoItemAccountingFromWo=$localStorage.generalOptions.GetPoItemAccountingFromWo,$scope.mandatoryFields={},params.fieldRules.forEach(function(field){"GUID_ESTATE"===field.FieldName&&($scope.mandatoryFields.estate=field.Mandatory),"GUID_BUILDING"===field.FieldName&&($scope.mandatoryFields.building=field.Mandatory),"GUID_EQUIPMENT"===field.FieldName&&($scope.mandatoryFields.equipment=field.Mandatory),"GUID_AREA"===field.FieldName&&($scope.mandatoryFields.area=field.Mandatory)}),$scope.displayMaintenaceObject={estate:!$scope.mandatoryFields.equipment&&(!$scope.mandatoryFields.area&&!$scope.mandatoryFields.building),building:!$scope.mandatoryFields.equipment&&!$scope.mandatoryFields.area},$scope.listSelection=$scope.displayMaintenaceObject.building?"building":"equipment",$scope.estateColumns=[{Position:1,Title:translationService.translate("web-estate-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-estate-description"),Property:"Description",PropertyType:"string"}],$scope.buildingColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-buildingcategory-description"),Property:"BuildingCategory.Description",PropertyType:"string"}],"KA"===$localStorage.generalOptions.CustomerId&&$scope.buildingColumns.push({Position:4,Title:"Bygningsgruppe",Property:"Combo06",PropertyType:"string"}),$scope.equipmentColumns=[{Position:1,Title:translationService.translate("web-equipment-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-equipment-description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-building-id"),Property:"Building.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-building-description"),Property:"Building.Description",PropertyType:"string"}],$scope.areaColumns=[{Position:1,Title:translationService.translate("web-area-id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-area-description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-building-id"),Property:"Building.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-building-description"),Property:"Building.Description",PropertyType:"string"}];var setListColumns=function(){switch($scope.listColumns=[],$scope.listSelection){case"estate":$scope.listColumns=$scope.estateColumns;break;case"building":$scope.listColumns=$scope.buildingColumns;break;case"equipment":$scope.listColumns=$scope.equipmentColumns;break;case"area":$scope.listColumns=$scope.areaColumns}},setFilter=function(filter){switch(filter.ProprtyFilter||(filter.PropertyFilter=[]),$scope.listSelection){case"estate":break;case"building":filter.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:"0"})}return filter},getDataColumns=function(){var columns=[];switch($scope.listColumns.forEach(function(col){columns.push(col.Property)}),$scope.listSelection){case"building":columns.push("Estate.Id"),columns.push("Estate.Description");break;case"equipment":case"area":columns.push("Building.Description"),columns.push("Building.Estate.Id"),columns.push("Building.Estate.Description")}return columns};$scope.itemTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){setListColumns();var url=repository.apiData[$scope.listSelection].url,filter=angular.copy(params.filter());setFilter(filter);var columns=getDataColumns();repository.GetPaginated(url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.getPropertyValue=function(entity,field){return listService.GetPropertyValue(entity,field)},$scope.addSelectedItem=function(object){if($scope.isItemSelected(object)){for(var i=0;i<$scope.selectedItems.length;i++)if($scope.selectedItems[i].Guid===object.Guid)return void $scope.selectedItems.splice(i,1)}else $scope.selectedItems.push(object)},$scope.isItemSelected=function(object){return _.find($scope.selectedItems,function(o){return o.Guid===object.Guid})},$scope.reloadList=function(){$scope.itemTable.reload()},$scope.tabs=[{heading:translationService.translate("web-periodicTask-maintenanceObject","Velg vedlikehold objekt"),step:0},{heading:translationService.translate("web-periodicTask-maintenanceObject-preview","Bekreft valgte"),step:1}],$scope.step=0,$scope.isCurrentStep=function(step){return $scope.step===step},$scope.setCurrentStep=function(step){$scope.isValid(step)&&($(".tab-content").css("overflow","hidden"),setTimeout(function(){$(".tab-content").css("overflow","visible")},500),$scope.step=step)},$scope.isLastStep=function(){return $scope.step===$scope.tabs.length-1},$scope.getNextLabel=function(){return $scope.isLastStep()?translationService.translate("web-button-saveAndClose","Lagre og lukk"):translationService.translate("web-button-next","Neste")},$scope.handlePrevious=function(){$scope.setCurrentStep($scope.step-(0===$scope.step?0:1))},$scope.handleNext=function(){$scope.isLastStep()?$scope.copyPeriodicTask():($scope.reloadTables(),$scope.setCurrentStep($scope.step+=1))},$scope.isValid=function(step){var valid=!0;switch(step){case 0:break;case 1:0===$scope.selectedItems.length&&(valid=!1)}return valid},$scope.amountOfSelectedItems=function(entity){return entity?$scope.selectedItems.filter(function(item){return item.Prefix===entity}).length:$scope.selectedItems.length},$scope.estimateInMinutes=function(){var items=$scope.selectedItems.length;return items?Math.ceil(.2*items/60):null},$scope.removeSelectedItem=function(item){for(var i=0;i<$scope.selectedItems.length;i++)if($scope.selectedItems[i].Guid===item.Guid)return $scope.selectedItems.splice(i,1),void $scope.reloadTables()},$scope.reloadTables=function(){$scope.estateTable.reload(),$scope.buildingTable.reload(),$scope.equipmentTable.reload(),$scope.areaTable.reload()},$scope.estateTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){var rawData=$scope.selectedItems.filter(function(item){return"Estate"===item.Prefix});params.total($scope.amountOfSelectedItems("Estate"));var data=params.sorting()?$filter("orderBy")(rawData,params.orderBy()):rawData;data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$defer.resolve(data)}}),$scope.buildingTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){var rawData=$scope.selectedItems.filter(function(item){return"Building"===item.Prefix});params.total($scope.amountOfSelectedItems("Building"));var data=params.sorting()?$filter("orderBy")(rawData,params.orderBy()):rawData;data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$defer.resolve(data)}}),$scope.equipmentTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){var rawData=$scope.selectedItems.filter(function(item){return"Equipment"===item.Prefix});params.total($scope.amountOfSelectedItems("Equipment"));var data=params.sorting()?$filter("orderBy")(rawData,params.orderBy()):rawData;data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$defer.resolve(data)}}),$scope.areaTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){var rawData=$scope.selectedItems.filter(function(item){return"Area"===item.Prefix});params.total($scope.amountOfSelectedItems("Area"));var data=params.sorting()?$filter("orderBy")(rawData,params.orderBy()):rawData;data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$defer.resolve(data)}}),$scope.copyPeriodicTask=function(){if(0!==$scope.selectedItems){var arrayOfMaintenanceObjects=[];$scope.selectedItems.forEach(function(object){var transferObject={Prefix:object.Prefix};"Equipment"===object.Prefix?(transferObject.GuidEquipment=object.Guid,transferObject.GuidBuilding=object.GuidBuilding,transferObject.GuidEstate=object.Building.Estate.Guid):"Area"===object.Prefix?(transferObject.GuidArea=object.Guid,transferObject.GuidBuilding=object.GuidBuilding,transferObject.GuidEstate=object.Building.Estate.Guid):"Building"===object.Prefix?(transferObject.GuidBuilding=object.Guid,transferObject.GuidEstate=object.GuidEstate):"Estate"===object.Prefix&&(transferObject.GuidEstate=object.Guid),arrayOfMaintenanceObjects.push(transferObject)}),repository.createMultipleWithGuid(repository.apiData.periodicTask.url+"copyPeriodicTask/",params.GuidPeriodicTask,arrayOfMaintenanceObjects).then(function(result){repository.growl("Periodisk rutine har blitt kopiert","success"),$modalInstance.close()}).catch(function(error){repository.growl(error,"danger")})}}}angular.module("Plania").controller("CopyPeriodicTaskModalController",["$scope","Repository","params","ngTableParams","$filter","$modalInstance","authService","TranslationService","ListService","$localStorage","$q","RegisteredFieldService",controller])}(),function(){function controller($scope,$modalInstance,params,repository,ngTableParams,translationService,$localStorage,listService,constants){$scope.equipmentColumns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Building.Id",sortable:!0},{Position:2,Title:translationService.translate("web-building-description"),Property:"Building.Description"},{Position:3,Title:translationService.translate("web-equipment-id"),Property:"Id"},{Position:4,Title:translationService.translate("web-equipment-description"),Property:"Description"}];var createFilterModel=function(){var filter={Condition:"and",Rules:[{Property:"HasConditionControl",Operator:"=",Value:!0},{Property:"PeriodicTaskXEquipments.GuidPeriodicTask",Operator:"<>",Value:params.guidPeriodicTask,CollectionOperator:"all"}]};switch($localStorage.generalOptions.InspectedEntityLocation){case constants.inspectedEntityLocation.estate:params.guidEstate&&filter.Rules.push({Property:"Building.GuidEstate",Operator:"=",Value:params.guidEstate});break;case constants.inspectedEntityLocation.building: params.guidBuilding&&filter.Rules.push({Property:"GuidBuilding",Operator:"=",Value:params.guidBuilding})}return filter};$scope.equipmentTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{FilterModel:createFilterModel()}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){var columns=[];$scope.equipmentColumns.forEach(function(column){columns.push(column.Property)}),repository.GetPaginated(repository.apiData.equipment.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.showError(error)})}}),$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)},$scope.selectedEquipments=[],$scope.save=function(){var xRef=[];$scope.selectedEquipments.forEach(function(eq){xRef.push({GuidPeriodicTask:params.guidPeriodicTask,GuidEquipment:eq})}),repository.createMultiple(repository.apiData.periodicTaskXEquipment.url,xRef,"Prefix=PeriodicTaskXEquipment").then(function(result){repository.growl(translationService.translate("periodicTask-equipment-add-success","Anlegg har blitt lagt til"),"success"),$modalInstance.close("OK")})},$scope.addEquipment=function(guid){if(_.contains($scope.selectedEquipments,guid)){for(var i=0;i<$scope.selectedEquipments.length;i++)if($scope.selectedEquipments[i]===guid)return void $scope.selectedEquipments.splice(i,1)}else $scope.selectedEquipments.push(guid)},$scope.alreadySaved=function(guid){return _.includes(params.selectedGuids,guid)},$scope.isEquipmentSelected=function(guid){return _.contains($scope.selectedEquipments,guid)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CreatePeriodicTaskXEquipmentController",["$scope","$modalInstance","params","Repository","ngTableParams","TranslationService","$localStorage","ListService","Constants",controller])}(),function(){function controller($scope,$modalInstance,translationService,params,repository){$scope.disableResourceGroupSelection=!1,$scope.isLoaded=!1;var costPrHour=0,setCost=function(newEstimatedTime){if(newEstimatedTime||(newEstimatedTime=$scope.model.EstimatedTime),$scope.model.HourType&&"Fixed"===$scope.model.HourType.PriceType)costPrHour=$scope.model.HourType.Price;else if($scope.model.HourType&&"Addition"===$scope.model.HourType.PriceType)costPrHour=$scope.model.ResourceGroup.CostPrHour+$scope.model.HourType.Price;else if($scope.model.HourType&&"Adjustment"===$scope.model.HourType.PriceType){var cost=$scope.model.ResourceGroup.CostPrHour;costPrHour=cost+cost*$scope.model.HourType.Price/100}$scope.model.EstimatedCost=newEstimatedTime?costPrHour*newEstimatedTime:0};$scope.onResourceGroupSelect=function(resourceGroup){if(!resourceGroup)return costPrHour=0,$scope.model.EstimatedCost=0,$scope.model.RealCost=0,$scope.model.GuidResourceGroup="",$scope.resourceGroup=null,void $scope.onPersonSelect(null);$scope.model.GuidResourceGroup=resourceGroup.Guid,$scope.model.ResourceGroup=resourceGroup,resourceGroup.CostPrHour&&(costPrHour=resourceGroup.CostPrHour,$scope.model.EstimatedTime&&($scope.model.EstimatedCost=costPrHour*$scope.model.EstimatedTime),$scope.model.RealCost=costPrHour*$scope.model.RealTime)},$scope.onPersonSelect=function(person){if(!person)return $scope.model.GuidPerson="",$scope.model.GuidPersonResourceGroup=null,void($scope.person=null);$scope.model.GuidPerson=person.Guid,$scope.model.GuidPersonResourceGroup=person.GuidResourceGroup,person.GuidResourceGroup&&($scope.disableResourceGroupSelection=!0,$scope.onResourceGroupSelect(person.ResourceGroup))},$scope.onHourTypeSelect=function(hourType){hourType?($scope.model.GuidHourType=hourType.Guid,$scope.model.HourType=hourType):($scope.model.GuidHourType="",$scope.model.HourType.Caption=null),setCost()},$scope.model={HourType:{}},$scope.model.GuidPeriodicTask=params.GuidPeriodicTask,params.ResourceGroup&¶ms.ResourceGroup.Id&&$scope.onResourceGroupSelect(params.ResourceGroup),$scope.model.RegisteredDate=new Date,$scope.saveResource=function(){$scope.model.RegisteredDate=$scope.model.RegisteredDate.toISOString(),$scope.model.EstimatedCost||($scope.model.EstimatedCost=0),repository.createSingle(repository.apiData.periodicTaskXResourceGroup.url,$scope.model).then(function(result){repository.growl(translationService.translate("create-periodic-task-resource-success","Ressursen har blitt knyttet til den periodiske rutinen"),"success"),$modalInstance.close("Resource have been addded to periodictask")},function(error){repository.growl(error,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.autoCompleteFilter=function(filterName){switch(filterName){case"person":return{GuidResourceGroup:$scope.model.GuidResourceGroup,DoesMaintenanceTasks:!0};case"resourceGroup":return{PropertyFilter:[{Property:"DoesMaintenanceTasks",Operator:"=",Value:"1"}]};case"hourType":return{PropertyFilter:[{Property:"GuidProject",Operator:"=",Value:""}]}}},$scope.$watch("model.EstimatedTime",function(newValue,oldValue){newValue!==oldValue&&setCost()},!0),$scope.$watch("model.RealTime",function(newValue,oldValue){newValue!==oldValue&&($scope.model.RealCost=costPrHour*newValue||0)},!0),$scope.$watch("model.GuidPersonResourceGroup",function(newValue,oldValue){$scope.disableResourceGroupSelection=!!newValue},!0)}angular.module("Plania").controller("CreatePeriodicTaskXResourceGroupController",["$scope","$modalInstance","TranslationService","params","Repository",controller])}(),function(){function controller($scope,ngTableParams,$modalInstance,params,repository,listService,translationService){$scope.model={Quantity:0},$scope.update=params.update,$scope.tabs=[{heading:translationService.translate("web-sparepart-chooseSparePart","Velg reservedel"),step:1},{heading:translationService.translate("web-sparepart-setNumber","Sett antall"),step:2}],params.withdraw&&($scope.modelProperties={quantityToWithdraw:0}),$scope.title=$scope.update?translationService.translate("web-sparepart-edit-title","Rediger reservedel"):translationService.translate("web-sparepart-new-title","Legg til ny reservedel"),$scope.step=$scope.update?2:1,$scope.setCurrentStep=function(step){$(".tab-content").css("overflow","hidden"),setTimeout(function(){$(".tab-content").css("overflow","visible")},500),$scope.step=step};var sparePartColumns=[{Title:translationService.translate("web-component-id","Id"),Property:"Component.Id"},{Title:translationService.translate("web-component-description","Beskrivelse"),Property:"Component.Description"},{Title:translationService.translate("web-componentXSupplier-partnumber","Delenummer"),Property:"ComponentXSupplier.PartNumber"},{Title:translationService.translate("web-componentXSupplier-Manufacturer","Fabrikat"),Property:"ComponentXSupplier.Manufacturer"},{Title:translationService.translate("web-componentXSupplier-Supplier","Leverandør"),Property:"ComponentXSupplier.Supplier.Description"},{Property:"ComponentXSupplier.Price",hidden:!0},{Property:"Inventory",hidden:!0},{Property:"Component.Unit",hidden:!0},{Property:"Component.GuidImage",hidden:!0}];if($scope.columns=_.filter(sparePartColumns,function(c){return!c.hidden}),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.update){var columns=["SparePart.ComponentXSupplier.PartNumber","SparePart.Inventory","SparePart.Component.Unit","SparePart.Component.GuidImage","SparePart.Component.Id","SparePart.Component.Description"];repository.getSingle(repository.apiData.periodicTaskXSparePart.url,params.guid,JSON.stringify(columns)).then(function(result){$scope.model=result.Data,$scope.model.Inventory=result.Data.SparePart.Inventory,$scope.model.Unit=result.Data.SparePart.Component.Unit,$scope.model.GuidImage=result.Data.SparePart.Component.GuidImage,$scope.modelProperties&&($scope.modelProperties.quantityToWithdraw=$scope.model.Quantity-$scope.model.QuantityWithdrawn)})}else $scope.sparePartTable=new ngTableParams({page:1,count:10,sorting:{},filter:{}},{total:0,counts:[10,50,100],paginationMaxBlocks:8,getData:function($defer,params){var columns=_.map(sparePartColumns,"Property");repository.GetPaginated(repository.apiData.sparePart.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}});$scope.chooseSparePart=function(item){$scope.itemExcluded(item.Guid)||($scope.model={GuidSparePart:item.Guid,Id:item.Component.Id,Description:item.Component.Description,Inventory:item.Inventory,Unit:item.Component.Unit,GuidImage:item.Component.GuidImage,Quantity:0},item.ComponentXSupplier&&($scope.model.PartNumber=item.ComponentXSupplier.PartNumber,$scope.model.Price=item.ComponentXSupplier.Price),$scope.setCurrentStep(2))},$scope.itemExcluded=function(guid){return _.contains(params.excludeGuids,guid)},$scope.save=function(){delete $scope.model.Inventory,delete $scope.model.Unit,delete $scope.model.GuidUmage,params.withdraw&&($scope.model.QuantityWithdrawn=$scope.model.QuantityWithdrawn+$scope.modelProperties.quantityToWithdraw),$modalInstance.close($scope.model)},$scope.cancel=function(){$modalInstance.close()}}angular.module("Plania").controller("CreatePeriodicTaskXSparePartController",["$scope","ngTableParams","$modalInstance","params","Repository","ListService","TranslationService",controller])}(),function(){function controller($scope,$modalInstance,params,repository,authService,translationService,$localStorage,listService,constants){$scope.model={Guid:params.guid};var updateAccess=function(){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!authService.hasEditAccess(repository.commonService.prefix.PeriodicTask,checkOtherDo),$scope.restrictDelete=!authService.hasDeleteAccess(repository.commonService.prefix.PeriodicTask,checkOtherDo)};updateAccess();var columns=["Equipment.Id","Equipment.Description","Equipment.ConditionContextDescription"];repository.getSingle(repository.apiData.periodicTaskXEquipment.url,$scope.model.Guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,updateAccess()},function(error){repository.showError(error)}),$scope.save=function(close){repository.updateSingle(repository.apiData.periodicTaskXEquipment.url,$scope.model).then(function(response){repository.growl(translationService.translate("web-periodicTaskXEquipment-modal-save-success","Inspeksjonsobjekt er oppdatert"),"success"),close&&$modalInstance.close()},function(error){repository.showError(error)})},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("EditPeriodicTaskXEquipmentController",["$scope","$modalInstance","params","Repository","authService","TranslationService","$localStorage","ListService","Constants",controller])}(),function(){function controller($scope,$modalInstance,translationService,params,repository){$scope.isUpdate=params.isUpdate,$scope.isLoaded=!1,$scope.model={};var costPrHour=0;$scope.activateAutocomplete=!1,$scope.isFromProjectTemplate=params.isFromProjectTemplate;var setCost=function(newEstimatedTime){if(newEstimatedTime||(newEstimatedTime=$scope.model.EstimatedTime),$scope.model.HourType&&"Fixed"===$scope.model.HourType.PriceType)costPrHour=$scope.model.HourType.Price;else if($scope.model.HourType&&"Addition"===$scope.model.HourType.PriceType)costPrHour=$scope.model.ResourceGroup.CostPrHour+$scope.model.HourType.Price;else if($scope.model.HourType&&"Adjustment"===$scope.model.HourType.PriceType){var cost=$scope.model.ResourceGroup.CostPrHour;costPrHour=cost+cost*$scope.model.HourType.Price/100}$scope.model.EstimatedCost=newEstimatedTime?costPrHour*newEstimatedTime:0};if($scope.saveResource=function(){$scope.isUpdate?repository.updateSingle(repository.apiData.periodicTaskXResourceGroup.url,$scope.model).then(function(result){repository.growl(translationService.translate("edit-periodic-task-resource-success","Ressursen ble oppdatert"),"success"),$modalInstance.close("ok")},function(error){repository.growl(error,"danger")}):($scope.model.RegisteredDate=$scope.model.RegisteredDate.toISOString(),$scope.model.EstimatedCost||($scope.model.EstimatedCost=0),repository.createSingle(repository.apiData.periodicTaskXResourceGroup.url,$scope.model).then(function(result){repository.growl(translationService.translate("create-periodic-task-resource-success","Ressursen har blitt knyttet til den periodiske rutinen"),"success"),$modalInstance.close("Resource have been addded to periodictask")},function(error){repository.growl(error,"danger")}))},$scope.onPersonSelect=function(person){if(!person)return $scope.model.GuidPerson="",$scope.model.GuidPersonResourceGroup=null,void($scope.person=null);$scope.model.GuidPerson=person.Guid,$scope.model.GuidPersonResourceGroup=person.GuidResourceGroup,person.GuidResourceGroup&&($scope.disableResourceGroupSelection=!0,$scope.onResourceGroupSelect(person.ResourceGroup))},$scope.onHourTypeSelect=function(hourType){hourType?($scope.model.GuidHourType=hourType.Guid,$scope.model.HourType=hourType):($scope.model.GuidHourType="",$scope.model.HourType.Caption=null),setCost()},$scope.onResourceGroupSelect=function(resourceGroup){if(!resourceGroup)return costPrHour=0,$scope.model.EstimatedCost=0,$scope.model.RealCost=0,$scope.model.GuidResourceGroup="",$scope.resourceGroup=null,void $scope.onPersonSelect(null);$scope.model.GuidResourceGroup=resourceGroup.Guid,$scope.model.ResourceGroup=resourceGroup,resourceGroup.CostPrHour&&(costPrHour=resourceGroup.CostPrHour,$scope.model.EstimatedTime&&($scope.model.EstimatedCost=costPrHour*$scope.model.EstimatedTime),$scope.model.RealCost=costPrHour*$scope.model.RealTime)},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.autoCompleteFilter=function(filterName){switch(filterName){case"person":return{GuidResourceGroup:$scope.model.GuidResourceGroup,DoesMaintenanceTasks:!0};case"resourceGroup":return{PropertyFilter:[{Property:"DoesMaintenanceTasks",Operator:"=",Value:"1"}]};case"hourType":return{PropertyFilter:[{Property:"GuidProject",Operator:"=",Value:""}]}}},$scope.$watch("model.EstimatedTime",function(newValue,oldValue){newValue!==oldValue&&setCost()},!0),$scope.$watch("model.RealTime",function(newValue,oldValue){newValue!==oldValue&&($scope.model.RealCost=costPrHour*newValue||0)},!0),$scope.$watch("model.GuidPersonResourceGroup",function(newValue,oldValue){$scope.disableResourceGroupSelection=!!newValue},!0),$scope.isUpdate){var columns=["Person.GuidResourceGroup","Person.FirstName","Person.LastName","ResourceGroup.Id","ResourceGroup.Description","ResourceGroup.CostPrHour"];repository.getSingle(repository.apiData.periodicTaskXResourceGroup.url,params.GuidWorkOrderXResourceGroupGroup,JSON.stringify(columns)).then(function(result){$scope.model=result.Data,$scope.model.RegisteredDate=new Date($scope.model.RegisteredDate),setTimeout(function(){$scope.activateAutocomplete=!0},250),costPrHour=$scope.model.ResourceGroup.CostPrHour},function(error){repository.growl(error,"danger")})}else $scope.model.HourType={},$scope.model.RegisteredDate=new Date,$scope.model.GuidPeriodicTask=params.GuidPeriodicTask,$scope.disableResourceGroupSelection=!1,params.ResourceGroup&¶ms.ResourceGroup.Id&&$scope.onResourceGroupSelect(params.ResourceGroup)}angular.module("Plania").controller("EditPeriodicTaskXResourceGroupController",["$scope","$modalInstance","TranslationService","params","Repository",controller])}(),function(){function controller($scope,repository,$stateParams,ngTableParams,$modal,$modalStack,authService,translationService,listService,$localStorage,$q,registeredFieldService,$rootScope){$scope.isUpdate="periodicTask.edit"===$scope.navigation.current.name||"workOrderTemplate.edit"===$scope.navigation.current.name,$scope.isDocumentsCollapsed=!0,$scope.isTextCollapsed=!0,$scope.isResourcesCollapsed=!0,$scope.isAreaCollapsed=!0,$scope.model={Guid:$stateParams.guid},$scope.modelDto={},$scope.activateAutocomplete=!1,$scope.validCharacters="^(?!.*<[a-zA-ZæøåÆØÅ]+).*",$scope.isBuildingDisabled=!1,$scope.isEquipmentDisabled=!1,$scope.isAreaDisabled=!1,$scope.restrictEdit=!0,$scope.viewMode=!!$scope.isUpdate,$scope.reload=!1,$scope.generalOptions=$localStorage.generalOptions,$scope.count={workOrder:0},$scope.reloadWorkOrderTable=!1,$scope.routeEntity=$scope.navigation.current.name.split(".")[0],$scope.isCopying=!!$stateParams.guidEntityToCopy,$scope.GetPoItemAccountingFromWo=$localStorage.generalOptions.GetPoItemAccountingFromWo,$scope.suggestedNewDueDate=null,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.selectedSeasonValue=null,$scope.setSeasonValue=function(newValue){$scope.model.Season=_.reduce(newValue,function(a,b){return a+b},0),$scope.checkDueDate()};var updateAccess=function(){if($scope.isUpdate){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!authService.hasEditAccess(repository.commonService.prefix.PeriodicTask,checkOtherDo),$scope.restrictDelete=!authService.hasDeleteAccess(repository.commonService.prefix.PeriodicTask,checkOtherDo),$scope.isBuildingDisabled=$scope.restrictEdit,$scope.isEquipmentDisabled=$scope.restrictEdit,$scope.isAreaDisabled=$scope.restrictEdit}else $scope.restrictEdit=!authService.hasCreateAccess(repository.commonService.prefix.PeriodicTask),$scope.isBuildingDisabled=$scope.restrictEdit,$scope.isEquipmentDisabled=$scope.restrictEdit,$scope.isAreaDisabled=$scope.restrictEdit};updateAccess(),$scope.workOrderColumns=[{Position:1,Title:translationService.translate("web-workorder-id"),Property:"Id",PropertyType:"string"},{Position:1,Title:translationService.translate("web-workorder-type"),Property:"Type",PropertyType:"string"},{Position:4,Title:translationService.translate("web-workorder-description"),Property:"Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-equipment-resourcegroup-description","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidResourceGroup",AutocompleteService:"resourceGroup"},{Position:6,Title:translationService.translate("web-workorder-startdate"),Property:"StartDate",PropertyType:"date"},{Position:7,Title:translationService.translate("web-workorder-enddate"),Property:"EndDate",PropertyType:"date"}];var getCardTables=function(){$scope.equipmentInfo.initTable(),$scope.resourceInfo.initTable(),$scope.purchaseOrderItemInfo.initTable(),$scope.sparePartInfo.initTable(),$scope.standardTextInfo.initTable()};$scope.getPropertyValue=function(building,column){return listService.GetPropertyValue(building,column)};var columns=["Estate.Id","Estate.Description","Estate.Guid","Estate.GuidCostCenter","Estate.CostCenter.Id","Estate.CostCenter.Description","Building.Id","Building.Description","Building.GuidCostCenter","Building.Guid","Building.CostCenter.Id","Building.CostCenter.Description","Equipment.Id","Equipment.Description","Area.Id","Area.Description","Area.Guid","Area.IsHousing","Area.GuidCostCenter","Area.CostCenter.Id","Area.CostCenter.Description","Project.Id","Project.Description","ResourceGroup.Id","ResourceGroup.Description","ResourceGroup.CostPrHour","Cause.Id","ResponsiblePerson.FirstName","ResponsiblePerson.LastName","ResourceResponsible.FirstName","ResourceResponsible.LastName","UserUpdatedBy.RealName","UserCreatedBy.RealName","Supplier.Id","Supplier.Description","Priority.Description","ActivityGroup.Id","Department.Id","Department.Description","ActivityCategory.Description","Department.Id","InvoiceCustomer.Id","InvoiceCustomer.Description"];$scope.isTemplateDisabled=function(field){return!!$scope.model.TemplateFieldConstraints&&$scope.model.TemplateFieldConstraints.some(function(f){return f===field})};var getPresets=function(){if($scope.isUpdate)return null;var presets=null,setParameter=function(name,value){return!!value&&(presets||(presets={}),presets[name]=value,!0)};if($stateParams.showPersistantData){var persistentData=repository.persistedData.getPersistedData("periodicTask.create");persistentData&&(setParameter("GuidEstate",persistentData.guidEstate),setParameter("GuidBuilding",persistentData.guidBuilding),setParameter("GuidArea",persistentData.guidArea),setParameter("GuidEquipment",persistentData.guidEquipment),setParameter("GuidProject",persistentData.guidProject),persistentData.model&&(setParameter("GuidResourceGroup",persistentData.model.GuidResourceGroup),setParameter("GuidResponsiblePerson",persistentData.model.GuidResponsiblePerson),setParameter("GuidDepartment",persistentData.model.GuidDepartment),setParameter("GuidCause",persistentData.model.GuidCause),setParameter("GuidActivityCategory",persistentData.model.GuidActivityCategory),setParameter("GuidPriority",persistentData.model.GuidPriority)))}return setParameter("TemplateType","workOrderTemplate.create"===$scope.navigation.current.name?"WorkOrderTemplate":"Periodic"),setParameter("IsTemplate","workOrderTemplate.create"===$scope.navigation.current.name),$scope.model.TemplateType=presets.TemplateType,$scope.model.IsTemplate=presets.IsTemplate,presets},getEntity=function(){var queryString=JSON.stringify(columns);$stateParams.guidEntityToCopy&&(queryString+="&GuidCopyFrom="+$stateParams.guidEntityToCopy);var presets=getPresets();return repository.getMainModel(repository.apiData.periodicTask.url,$scope.isUpdate?$stateParams.guid:"00000000-0000-0000-0000-000000000000",queryString,presets?JSON.stringify(presets):null)},getSingle=function(skipCardTables){getEntity().then(function(response){$scope.fieldRules=response.FieldRules;var periodicTask=response.Data;if($scope.model=periodicTask,$scope.reload=!0,$scope.isUpdate&&($scope.reloadDocumentTable=!0,$scope.reloadControlLists=!0,skipCardTables||getCardTables()),updateAccess(),$scope.restrictEdit||($scope.model.GuidBuilding&&($scope.isBuildingDisabled=!0),$scope.model.GuidEquipment&&($scope.isEquipmentDisabled=!0),$scope.model.GuidArea&&($scope.isAreaDisabled=!0)),setProperties(),!$scope.isUpdate){var user=repository.authService.getUserData();user.guidDepartment&&($scope.model.GuidDepartment=user.guidDepartment,$scope.modelDto.department=user.userDepartment),user.guidResourceGroup&&($scope.model.GuidResourceGroup=user.guidResourceGroup,$scope.modelDto.resourceGroup=user.userResourceGroup);var selectedBuilding=repository.commonService.getFilterData().selectedBuilding;if(selectedBuilding.Guid&&($scope.model.GuidBuilding=selectedBuilding.Guid,$scope.modelDto.building=selectedBuilding.Name,selectedBuilding.Estate&&($scope.model.GuidEstate=selectedBuilding.Estate.Guid,$scope.modelDto.estate=selectedBuilding.Estate.Caption)),repository.commonService.getFilterData().selectedEstate){var estate=repository.commonService.getFilterData().selectedEstate;$scope.model.GuidEstate=estate.Guid,$scope.modelDto.estate=estate.Name}if($stateParams.DueDateControlCode||0===$stateParams.DueDateControlCode){var selectedDueDateControlCode=_.filter($scope.dueDateControlCodes,{value:$stateParams.DueDateControlCode});selectedDueDateControlCode.length>0&&($scope.selectedDueDateControlCode=selectedDueDateControlCode[0])}var webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value)$scope.modelDto[prefill.Property.toLowerCase()]=prefill.Value.Label,$scope.model["Guid"+prefill.Property]=prefill.Value.Guid;else if("@CurrentBuilding"===prefill.Value){var building=repository.commonService.getFilterData().selectedBuilding;building.Guid&&($scope.modelDto.building=building.Name,$scope.model.GuidBuilding=building.Guid)}else"@LoggedInPerson"===prefill.Value?($scope.modelDto.personResponsible=user.personFirstName+" "+user.personLastName,$scope.model.GuidResponsiblePerson=repository.authService.getUserData().guidPerson):$scope.model[prefill.Property]=prefill.Value})}setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})};$scope.onEstateSelect=function(estate){if(!estate)return void($scope.model.GuidEstate="");$scope.model.GuidEstate!==estate.Guid&&($scope.model.GuidBuilding="",$scope.modelDto.building="",$scope.model.GuidEquipment="",$scope.modelDto.equipment="",$scope.model.GuidArea="",$scope.modelDto.area=""),$scope.model.GuidEstate=estate.Guid},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidEquipment="",$scope.modelDto.equipment="",$scope.model.GuidArea="",$scope.modelDto.area=""),$scope.model.GuidBuilding=building.Guid,$scope.model.GuidEstate&&""!==$scope.model.GuidEstate&&$scope.model.GuidEstate===building.GuidEstate||($scope.model.GuidEstate=building.GuidEstate,$scope.modelDto.estate=building.Estate.Id+" - "+building.Estate.Description)},$scope.onEquipmentSelect=function(equipment){if(!equipment)return void($scope.model.GuidEquipment="");$scope.model.GuidEquipment=equipment.Guid,$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=equipment.GuidBuilding,equipment.Building&&($scope.modelDto.building=equipment.Building.Caption)),$scope.model.GuidEstate&&""!==$scope.model.GuidEstate||equipment.Building.Estate&&($scope.model.GuidEstate=equipment.Building.Estate.Guid,$scope.modelDto.estate=equipment.Building.Estate.Caption),equipment.GuidArea&&($scope.model.GuidArea=equipment.GuidArea,$scope.modelDto.area=equipment.Area.Caption)},$scope.onPrioritySelect=function(priority){priority?($scope.model.GuidPriority=priority.Guid,priority.HasDeadline&&($scope.model.DeadlinePeriodNumber=priority.DeadlinePeriodNumber,$scope.model.DeadlinePeriodUnit=priority.DeadlinePeriodUnit)):$scope.model.GuidPriority=null};var setProperties=function(){var periodicTask=$scope.model;periodicTask.Estate&&($scope.modelDto.estate=periodicTask.Estate.Caption),periodicTask.Building&&($scope.modelDto.building=periodicTask.Building.Caption),periodicTask.Equipment&&($scope.modelDto.equipment=periodicTask.Equipment.Caption),periodicTask.Area&&($scope.modelDto.area=periodicTask.Area.Caption),periodicTask.ResourceGroup&&($scope.modelDto.resourceGroup=periodicTask.ResourceGroup.Caption),periodicTask.Supplier&&($scope.modelDto.supplier=periodicTask.Supplier.Caption),periodicTask.Department&&($scope.modelDto.department=periodicTask.Department.Caption),periodicTask.ActivityGroup&&($scope.modelDto.activityGroup=periodicTask.ActivityGroup.Id),periodicTask.Priority&&($scope.modelDto.priority=periodicTask.Priority.Description),periodicTask.Cause&&($scope.modelDto.cause=periodicTask.Cause.Id),periodicTask.ActivityCategory&&($scope.modelDto.activityCategory=periodicTask.ActivityCategory.Description),periodicTask.Project&&($scope.modelDto.project=periodicTask.Project.Caption),periodicTask.InvoiceCustomer&&($scope.modelDto.invoiceCustomer=periodicTask.InvoiceCustomer.Description),periodicTask.ResponsiblePerson&&($scope.modelDto.personResponsible=periodicTask.ResponsiblePerson.FirstName+" "+periodicTask.ResponsiblePerson.LastName),periodicTask.ResourceResponsible&&($scope.modelDto.resourceResponsible=periodicTask.ResourceResponsible.FirstName+" "+periodicTask.ResourceResponsible.LastName),$scope.selectedSeasonValue=periodicTask.Season};getSingle(!1),$scope.getTextValue=function(intValue,collection){var collectionItem=_.find(collection,function(o){return o.value===intValue});return collectionItem?collectionItem.text:collection[0].text};var runUpdate=function(success,error){var parentProperties=[];for(var propertyName in $scope.model)if(propertyName.startsWith("Guid")){var parentPropertyName=_.capitalize(propertyName.substring(4)),parent=$scope.model[parentPropertyName];parent&&parentProperties.push(parentPropertyName)}var payloadEntity=angular.copy($scope.model);parentProperties.forEach(function(field){delete payloadEntity[field]}),$scope.isUpdate?repository.updateSingle(repository.apiData.periodicTask.url,payloadEntity).then(success).catch(error):repository.createSingle(repository.apiData.periodicTask.url,payloadEntity).then(success).catch(error)};$scope.updatePeriodicTask=function(destination){$scope.model.DueDate&&($scope.model.DueDate=new Date($scope.model.DueDate).toISOString()),$scope.model.LastExecutedDate&&($scope.model.LastExecutedDate=new Date($scope.model.LastExecutedDate).toISOString()),$scope.model.DeadlinePeriodNumber&&($scope.model.DeadlinePeriodNumber=Math.floor($scope.model.DeadlinePeriodNumber));var success=function(result){var successMessage="";successMessage="PeriodicTemplate"===$scope.model.TemplateType?$scope.isUpdate?translationService.translate("web-periodictask-periodicTemplate-updated","Malrutine oppdatert"):translationService.translate("web-periodictask-periodicTemplate-created","Malrutine opprettet"):"WorkOrderTemplate"===$scope.model.TemplateType?$scope.isUpdate?translationService.translate("web-periodictask-workOrderTemplate-updated","Malaktivitet oppdatert"):translationService.translate("web-periodictask-workOrderTemplate-created","Malaktivitet opprettet"):$scope.isUpdate?translationService.translate("web-periodictask-periodic-updated","Periodisk rutine oppdatert"):translationService.translate("web-periodictask-periodic-created","Periodisk rutine opprettet"),repository.growl(successMessage,"success");var ptGuid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,ptGuid),$scope.goBack(destination,{guid:ptGuid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};($scope.model.GuidProject||"WorkOrderTemplate"===$scope.model.TemplateType)&&($scope.model.Interval=1),$scope.model.Interval?($scope.model.Interval=Math.floor($scope.model.Interval),runUpdate(success,error)):registeredFieldService.getFieldRule(repository.commonService.prefix.periodicTask,"Interval").then(function(result){result.Mandatory&&swal({title:"Intervall er ikke satt.",text:"Intervall vil automatisk bli satt til 1. Vil du fortsatt lagre?",type:"info",showCancelButton:!0,confirmButtonText:"Lagre",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){isConfirm&&($scope.model.Interval=1,runUpdate(success,error))})})},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"estate":return filter;case"building":return $scope.model.GuidEstate?registeredFieldService.getFieldRule(repository.commonService.prefix.periodicTask,"Interval").then(function(result){return result.Hidden||(filter.PropertyFilter=[{Property:"GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]),filter}):filter;case"equipment":return filter={GuidBuilding:$scope.model.GuidBuilding,IsMaintainable:1,PropertyFilter:[]},$scope.model.GuidEstate&&!$scope.model.GuidBuilding&&filter.PropertyFilter.push({Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}),$scope.model.IsTemplate&&(filter.TemplateContext="All"),filter;case"area":return filter={GuidBuilding:$scope.model.GuidBuilding},$scope.model.GuidEstate&&(filter.PropertyFilter=[{Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]),filter;case"person":return $localStorage.generalOptions.UseOnlyActivPersonOnActiv&&(filter.DoesMaintenanceTasks=1),$localStorage.generalOptions.UseOnlyPersInBldOnActiv&&(filter.GuidBuildingResponsible=$scope.model.GuidBuilding),filter;case"resourceResponsible":return{DoesMaintenanceTasks:1};case"resourceGroup":return{PropertyFilter:[{Property:"DoesMaintenanceTasks",Operator:"=",Value:"1"}]};case"priority":return{PropertyFilter:[{Property:"EntityType",Operator:"=",Value:6}]} ;case"cause":return $scope.model.GuidResourceGroup&&(filter.FilterOnResourceGroup=$scope.model.GuidResourceGroup),filter;case"activityCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}},$scope.removePeriodicTask=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-periodictask-message","Den periodiske rutinen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-periodictask-button-confirm","Ja, fjern rutinen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null;var destination="periodicTask.list";repository.deleteSingle(repository.apiData.periodicTask.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-periodictask-success","Den periodiske rutinen ble fjernet!"),result,"success"),$scope.goBack(destination,{menuGuid:$scope.navigation.params.menuGuid})},function(error){swal({title:translationService.translate("web-swal-periodictask-deactivate-title","Kunne ikke slette periodiske rutinen"),text:error.Message+"

    "+translationService.translate("web-swal-periodictask-deactivate-text","Vil du deaktivere periodiske rutinen?"),type:"error",html:!0,showCancelButton:!0,confirmButtonText:translationService.translate("web-button-deactivate","Deaktiver"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.IsDeactivated=!0,runUpdate(function(result){var successMessage=$scope.model.IsTemplate?translationService.translate("web-periodictask-template-disabled","Malrutinen er deaktivert"):translationService.translate("web-periodictask-disabled","Periodisk rutine er deaktivert");repository.growl(successMessage,"success");var ptGuid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,ptGuid),$scope.goBack(destination,{guid:ptGuid,menuGuid:$scope.navigation.params.menuGuid})}))})})})},$scope.createWorkOrderFromPeriodicTask=function(){($scope.userInfo.canRunSystemFunction||$scope.userInfo.canRunNewPeriod)&&$scope.hasEditAccess("WorkOrder")&&(runUpdate(),$modal.open({templateUrl:"app/periodicTask/views/periodicTaskGenerateOrdersConfirmationModal.html",controller:"PeriodicTaskGenerateOrdersConfirmationModalController",size:"lg",resolve:{params:function(){return{guids:[$scope.model.Guid]}}}}).result.then(function(result){getSingle(!1),$scope.reloadWorkOrderTable=!$scope.reloadWorkOrderTable},function(){}))},$scope.toggleMustLinkInstances=function(){if("PeriodicTemplate"===$scope.model.TemplateType&&$scope.hasEditAccess("PeriodicTask")){var title=$scope.model.MustLinkInstances?translationService.translate("web-periodicTask-turnOffMustLinkInstances-popup-title","Ønsker du å skru av synkronisering?"):translationService.translate("web-periodicTask-turnOnMustLinkInstances-popup-title","Ønsker du å skru på synkronisering?"),text=$scope.model.MustLinkInstances?translationService.translate("web-periodicTask-turnOffMustLinkInstances-popup-text","Endringer utført på denne malrutinen vil ikke oppdatere rutiner som er knyttet til denne. Ulagrede endringer vil også bli sendt ved bekreftelse."):translationService.translate("web-periodicTask-turnOnMustLinkInstances-popup-text","Endringer som blir utført på gjeldende malrutine, og knytinger vil bli også lagt til på rutiner som er knyttet til denne. Ulagrede endringer vil også bli sendt ved bekreftelse.");swal({title:title,text:text,type:"info",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-button-confirm","Ja"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.model.MustLinkInstances=!$scope.model.MustLinkInstances,runUpdate(function(){var text=$scope.model.MustLinkInstances?translationService.translate("web-periodicTask-turnOnMustLinkInstances-popup-success","Malrutine oppdatert og har synkronisert endringer."):translationService.translate("web-periodicTask-turnOffMustLinkInstances-popup-success","Malrutine oppdatert og vil ikke synkronisere.");repository.growl(text,"success")},function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")})})}};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.sparePartInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-sparepart-componentXSupplier-partnumber","Delenummer"),Property:"SparePart.ComponentXSupplier.PartNumber",PropertyType:"string"},{Position:2,Title:translationService.translate("web-sparepart-component-description","Komponentnavn"),Property:"SparePart.Component.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-sparePart-location","Plassering"),Property:"SparePart.Location",PropertyType:"string"},{Position:4,Title:translationService.translate("web-periodicTaskxsparepart-Quantity","Antall"),Property:"Quantity",PropertyType:"number"},{Position:5,Title:translationService.translate("web-periodicTaskxsparepart-Price","Price"),Property:"Price",PropertyType:"double"},{Position:7,Title:translationService.translate("web-sparePart-Inventory","Beholdning"),Property:"SparePart.Inventory",PropertyType:"number"},{Position:8,Title:translationService.translate("web-componentXSupplier-supplier-description","Leverandør"),Property:"SparePart.ComponentXSupplier.Supplier.Description",PropertyType:"string"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{UpdatedDate:"desc"},filter:{PropertyFilter:[{Property:"GuidPeriodicTask",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.periodicTaskXSparePart.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))},this.add=function(){var selectedGuids=[];me.table.data.forEach(function(sparePart){selectedGuids.push(sparePart.GuidSparePart)}),$modal.open({templateUrl:"app/periodicTask/views/createPeriodicTaskXSparePart.html",controller:"CreatePeriodicTaskXSparePartController",size:"lg",resolve:{params:function(){return{update:!1,excludeGuids:selectedGuids}}}}).result.then(function(item){item&&item.GuidSparePart&&(item.GuidPeriodicTask=$scope.model.Guid,repository.createSingle(repository.apiData.periodicTaskXSparePart.url,item).then(function(result){item.QuantityWithdrawn||(item.QuantityWithdrawn=0),repository.growl(translationService.translate("web-periodictask-sparepart-added","Reservedel er lagt til periodiske rutinen"),"success"),me.table.reload()}))},function(){})},this.update=function(sparePart){me.canEdit(sparePart)&&$modal.open({templateUrl:"app/periodicTask/views/createPeriodicTaskXSparePart.html",controller:"CreatePeriodicTaskXSparePartController",resolve:{params:function(){return{update:!0,guid:sparePart.Guid}}}}).result.then(function(item){item&&item.GuidSparePart&&(item.GuidPeriodicTask=$scope.model.Guid,item.Guid=sparePart.Guid,repository.updateSingle(repository.apiData.periodicTaskXSparePart.url,item).then(function(result){repository.growl(translationService.translate("web-spare-part-updated","Reservedel er oppdatert"),"success"),me.table.reload()}))})},this.remove=function(sparePart){me.canDelete(sparePart)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-periodictask-sparepart-swal-confirmRemove","Reservedelen vil bli fjernet fra periodisk rutine"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-sparePart-button-confirm","Ja, fjern reservedelen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.periodicTaskXSparePart.url,sparePart.Guid).then(function(result){swal(translationService.translate("web-periodictask-swal-sparePartRemoval-success","Reservedelen ble fjernet!"),result,"success"),repository.growl(translationService.translate("web-periodictask-sparepart-removed","Reservedelen er fjernet fra periodiske rutinen"),"success"),me.table.reload()})})},this.canEdit=function(sparePart){return sparePart&&$scope.hasEditAccess("PeriodicTaskXSparePart")},this.canDelete=function(sparePart){return sparePart&&$scope.hasDeleteAccess("PeriodicTaskXSparePart")},this.contextMenuOptions=function(item){var options=[];return me.canEdit(item)&&options.push({html:' '+translationService.translate("web-periodicTask-periodicTaskXSparePart-edit","Rediger reservedel")+"",click:function($itemScope,$event,modelValue,text,$li){me.update(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-periodicTask-periodicTaskXSparePart-delete","Slett reservedel")+"",click:function($itemScope,$event,modelValue,text,$li){me.remove(item)}}),options}},$scope.equipmentInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-building-id"),Property:"Equipment.Building.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-building-description"),Property:"Equipment.Building.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-equipment-id"),Property:"Equipment.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-equipment-description"),Property:"Equipment.Description",PropertyType:"string"},{Position:5,Title:translationService.translate("web-equipment-conditionContextDescription"),Property:"Equipment.ConditionContextDescription",PropertyType:"string"},{Position:6,Title:translationService.translate("web-periodicTaskXEquipment-objectContextDescription"),Property:"ObjectContextDescription",PropertyType:"string"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{},filter:{PropertyFilter:[{Property:"GuidPeriodicTask",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.periodicTaskXEquipment.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))},this.add=function(){if(me.canAdd()){var selectedGuids=[];me.table.data.forEach(function(equipment){selectedGuids.push(equipment.GuidEquipment)}),$modal.open({templateUrl:"app/periodicTask/views/createPeriodicTaskXEquipment.html",controller:"CreatePeriodicTaskXEquipmentController",resolve:{params:function(){return{guidPeriodicTask:$scope.model.Guid,guidBuilding:$scope.model.GuidBuilding,guidEstate:$scope.model.GuidEstate,selectedGuids:selectedGuids}}}}).result.then(function(){me.table.reload()},function(){})}},this.edit=function(equipment){me.canEdit(equipment)&&$modal.open({templateUrl:"app/periodicTask/views/editPeriodicTaskXEquipment.html",controller:"EditPeriodicTaskXEquipmentController",resolve:{params:function(){return{guid:equipment.Guid}}}}).result.then(function(){me.table.reload()},function(){})},this.remove=function(equipment){me.canDelete(equipment)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-periodictask-equipment-message","Anlegget vil bli koblet fra rutinen"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-periodictask-equipment-button-confirm","Ja, fjern anlegget"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.periodicTaskXEquipment.url,equipment.Guid).then(function(result){swal(translationService.translate("web-swal-periodictask-equipment-success","Anlegget ble frakoblet"),result,"success"),me.table.reload()})})},this.canAdd=function(){return $scope.hasReadAccess("Equipment")&&$scope.hasCreateAccess("PeriodicTaskXEquipment")},this.canEdit=function(equipment){return equipment&&$scope.hasEditAccess("PeriodicTaskXEquipment")},this.canDelete=function(equipment){return equipment&&$scope.hasDeleteAccess("PeriodicTaskXEquipment")},this.contextMenuOptions=function(item){var options=[];return options.push({html:' '+translationService.translate("web-periodicTask-periodicTaskXEquipment-edit","Rediger")+"",click:function(){me.edit(item)}}),item.GuidEquipment&&$scope.hasReadAccess("Equipment")&&options.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:item.GuidEquipment}),translationService.translate("web-periodicTask-periodicTaskXEquipment-goToEquipment","Gå til anlegg"))),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-periodicTask-periodicTaskXEquipment-delete","Fjern kobling")+"",click:function(){me.remove(item)}}),options}},$scope.resourceInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("workOrder-resourceTable-resource","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("workOrder-resourceTable-person","Person"),Property:"Person.FirstName",PropertyType:"string"},{Position:3,Title:translationService.translate("workOrder-resourceTable-estimatedTime","Est. Tid"),Property:"EstimatedTime",PropertyType:"string"},{Position:4,Title:translationService.translate("workOrder-resourceTable-estimatedCost","Est. Kost"),Property:"EstimatedCost",PropertyType:"double"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{"ResourceGroup.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidPeriodicTask",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("ResourceGroup.Description"),columns.push("ResourceGroup.Guid"),columns.push("Person.LastName"),repository.GetPaginated(repository.apiData.periodicTaskXResourceGroup.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))},this.getResourceGroup=function(){return $scope.model.ResourceGroup?($scope.model.ResourceGroup.Guid=$scope.model.GuidResourceGroup,$scope.model.ResourceGroup):null},this.add=function(){$modal.open({templateUrl:"app/periodicTask/views/editPeriodicTaskXResourceGroup.html",controller:"EditPeriodicTaskXResourceGroupController",resolve:{params:function(){return{GuidPeriodicTask:$scope.model.Guid,ResourceGroup:me.getResourceGroup(),isUpdate:!1,isFromProjectTemplate:!!$scope.model.GuidProject}}}}).result.then(function(){getSingle(!0),me.table.reload()},function(){})},this.update=function(resource){me.canEdit(resource)&&$modal.open({templateUrl:"app/periodicTask/views/editPeriodicTaskXResourceGroup.html",controller:"EditPeriodicTaskXResourceGroupController",resolve:{params:function(){return{GuidWorkOrderXResourceGroupGroup:resource.Guid,isUpdate:!0,isFromProjectTemplate:!!$scope.model.GuidProject}}}}).result.then(function(){getSingle(!0),me.table.reload()},function(){})},this.remove=function(resource){me.canDelete(resource)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-periodictask-resource-message","Ressursen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-periodictask-resource-button-confirm","Ja, fjern ressursen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.periodicTaskXResourceGroup.url,resource.Guid).then(function(result){swal(translationService.translate("web-swal-periodictask-resource-success","Ressursen ble fjernet!"),result,"success"),getSingle(!0),me.table.reload()})})},this.canEdit=function(resource){return resource&&$scope.hasEditAccess("PeriodicTaskXResourceGroup")},this.canDelete=function(resource){return resource&&$scope.hasDeleteAccess("PeriodicTaskXResourceGroup")},this.contextMenuOptions=function(item){var options=[];return me.canEdit(item)&&options.push({html:' '+translationService.translate("web-periodicTask-periodicTaskXResourceGroup-edit","Rediger ressurs")+"",click:function($itemScope,$event,modelValue,text,$li){me.update(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-periodicTask-periodicTaskXResourceGroup-delete","Slett ressurs")+"",click:function($itemScope,$event,modelValue,text,$li){me.remove(item)}}),options}},$scope.purchaseOrderItemInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-purchaseOrder-Id"),Property:"PurchaseOrder.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-purchaseOrderItem-Id"),Property:"Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-purchaseOrderItem-Description"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-supplier-Id","Leverandør navn"),Property:"Supplier.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-purchaseOrderItem-OrderedQuantity","Bestilt antall"),Property:"OrderedQuantity",PropertyType:"number"},{Position:6,Title:translationService.translate("web-purchaseOrderItem-UnitPrice","Enhetspris"),Property:"UnitPrice",PropertyType:"number"},{Position:7,Title:translationService.translate("web-purchaseOrderItem-OrderedAmount","Bestilt beløp"),Property:"OrderedAmount",PropertyType:"number"},{Position:8,Title:translationService.translate("web-purchaseOrderItem-Status","Status"),Property:"Status",PropertyType:"enum.PurchaseOrderItemStatus"}],this.initTable=function(){if(!me.table){var purchaseOrderItemTableFilter={PropertyFilter:[{Property:"GuidPeriodicTask",Operator:"=",Value:$scope.model.Guid}]};me.table=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:purchaseOrderItemTableFilter},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.purchaseOrderItem.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})}},this.add=function(){$modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"md",resolve:{params:function(){var guidCostCenter,costCenterCaption;return $scope.model.Area&&$scope.model.Area.GuidCostCenter?(guidCostCenter=$scope.model.Area.GuidCostCenter,costCenterCaption=$scope.model.Area.CostCenter.Caption):$scope.model.Building&&$scope.model.Building.GuidCostCenter?(guidCostCenter=$scope.model.Building.GuidCostCenter,costCenterCaption=$scope.model.Building.CostCenter.Caption):$scope.model.Estate&&$scope.model.Estate.GuidCostCenter&&(guidCostCenter=$scope.model.Estate.GuidCostCenter,costCenterCaption=$scope.model.Estate.CostCenter.Caption),{purchaseOrderItem:{GuidPeriodicTask:$scope.model.Guid,GuidDataOwner:repository.commonService.getFilterData().selectedDataOwner.Guid,GuidBuilding:$scope.model.GuidBuilding,GuidSupplier:$scope.model.GuidSupplier,Supplier:$scope.model.Supplier,GuidDepartment:$scope.model.GuidDepartment,GuidCostCenter:guidCostCenter},costCenterCaption:costCenterCaption,isFromProjectTemplate:!!$scope.model.GuidProject}}}}).result.then(function(){me.table.reload()},function(){})},this.update=function(purchaseOrderItem){me.canEdit(purchaseOrderItem)&&$modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"xl",resolve:{params:function(){return{Guid:purchaseOrderItem.Guid,isFromProjectTemplate:!!$scope.model.GuidProject}}}}).result.then(function(){me.table.reload()},function(){})},this.remove=function(purchaseOrderItem){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-purchaseOrderItem-message","Bestilling objektet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-purchaseOrderItem-button-confirm","Ja, fjern bestilling objektet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.purchaseOrderItem.url,purchaseOrderItem.Guid).then(function(result){swal(translationService.translate("web-swal-purchaseOrderItem-success","Bestilling objektet ble fjernet!"),result,"success"),repository.growl(translationService.translate("web-workorder-purchaseorder-removed","Bestilling objektet er fjernet fra bestillingen"),"success"),me.table.reload()})})},this.canEdit=function(purchaseOrderItem){return purchaseOrderItem&&$scope.hasEditAccess("PurchaseOrderItem")},this.canDelete=function(purchaseOrderItem){return purchaseOrderItem&&$scope.hasDeleteAccess("PurchaseOrderItem")&&"Proposal"===purchaseOrderItem.Status},this.contextMenuOptions=function(item){var options=[];return me.canEdit(item)&&options.push({html:' '+translationService.translate("web-workorder-purchaseorderitem-edit","Rediger konteringsobjekt")+"",click:function($itemScope,$event,modelValue,text,$li){me.update(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-workorder-purchaseorderitem-delete","Slett konteringsobjekt")+"",click:function($itemScope,$event,modelValue,text,$li){me.remove(item)}}),item.GuidPurchaseOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:item.GuidPurchaseOrder}),translationService.translate("web-workorder-viewPurchaseOrder","Se bestilling"),"fa-cart-shopping")),options}},$scope.standardTextInfo=new function(){var me=this;this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{"StandardText.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidPeriodicTask",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){repository.GetPaginated(repository.apiData.periodicTaskXStandardText.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(["CreationDate","StandardText.Id","StandardText.Description","StandardText.DescriptiveText"])).then(function(result){$scope.standardTexts=result.List,me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))},this.addNewStandardText=function(guidStandardText){var deferred=$q.defer();return repository.createSingle(repository.apiData.periodicTaskXStandardText.url,{GuidPeriodicTask:$scope.model.Guid,GuidStandardText:guidStandardText}).then(function(response){deferred.resolve(response)},function(error){deferred.reject(error)}),deferred.promise},this.add=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:"Velg standardtekster",columns:[{Title:translationService.translate("web-standardText-id"),Property:"Id"},{Title:translationService.translate("web-standardText-description"),Property:"Description"},{Title:translationService.translate("web-standardText-DescriptiveText"),Property:"DescriptiveText"}],url:repository.apiData.standardText.url,sorting:{Id:"asc"},filter:{ExcludeExisting:$scope.model.Guid},alreadySavedGuids:me.table.data.map(function(o){return o.GuidStandardText})}}}}).result.then(function(selectedGuids){var promises=[];selectedGuids.forEach(function(guid){promises.push(me.addNewStandardText(guid))}),$q.all(promises).then(function(){me.table.reload()},function(error){$scope.standardTextTable.reload(),swal("Error",error,"error")})},function(){})},this.openStandardText=function(standardText){$modal.open({templateUrl:"app/common/views/messageModal.html",size:"md",controller:"MessageModalController",resolve:{content:function(){return{header:standardText.StandardText.Id+" - "+standardText.StandardText.Description,message:standardText.StandardText.DescriptiveText,timestamp:standardText.CreationDate}}}})},this.remove=function(standardText){me.canDelete(standardText)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-standartText-message","Standardteksten vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-standartText-button-confirm","Ja, fjern standardteksten"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.periodicTaskXStandardText.url,standardText.Guid).then(function(result){swal(translationService.translate("web-swal-standartText-success","Standardteksten ble fjernet!"),result,"success"),me.table.reload()})})},this.canDelete=function(standardText){return standardText&&$scope.hasDeleteAccess("PeriodicTaskXStandardText")},this.contextMenuOptions=function(item){var options=[];return options.push({html:' '+translationService.translate("web-periodicTask-periodicTaskXStandardText-open","Åpne standardtekst")+"",click:function($itemScope,$event,modelValue,text,$li){me.openStandardText(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-periodicTask-periodicTaskXStandardText-delete","Slett standardtekst")+"",click:function($itemScope,$event,modelValue,text,$li){me.remove(item)}}),options}},$scope.onChangePeriod=function(value){"HourOfUse"===value?$scope.model.DueDateControlCode="CounterValue":"CounterValue"===$scope.model.DueDateControlCode&&($scope.model.DueDateControlCode="EndOfLastWorkOrder"),$scope.checkDueDate()},$scope.cancel=function(){$modalStack.dismissAll()},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.openCopyModal=function(){$modal.open({templateUrl:"app/periodicTask/views/copyPeriodicTaskModal.html",controller:"CopyPeriodicTaskModalController",size:"xl",resolve:{params:function(){return{GuidPeriodicTask:$scope.model.Guid,fieldRules:$scope.fieldRules}}}}).result.then(function(){},function(){})},$scope.checkDueDate=function(){if($scope.model.DueDate&&$scope.model.Period&&$scope.model.Interval){var dueDate=new Date($scope.model.DueDate).toISOString();if(dueDate){var season=$scope.model.Season;0!==season&&repository.getWithUrlParameter(repository.apiData.periodicTask.url+"validateDueDate","guid="+$scope.model.Guid+"&dueDate="+dueDate+"&season="+season+"&period="+$scope.model.Period+"&interval="+$scope.model.Interval).then(function(result){return!result.IsValid&&result.SuggestedNewDueDate?($scope.suggestedNewDueDate=result.SuggestedNewDueDate,void($scope.showSeasonConflictErrorMessage=!1)):result.IsValid?($scope.suggestedNewDueDate=null,void($scope.showSeasonConflictErrorMessage=!1)):($scope.suggestedNewDueDate=null,void($scope.showSeasonConflictErrorMessage=!0))},function(error){error&&repository.showError(error)})}}},$scope.setSuggestedDueDate=function(){$scope.model.DueDate=$scope.suggestedNewDueDate,$scope.suggestedNewDueDate=null}}angular.module("Plania").controller("PeriodicTaskController",["$scope","Repository","$stateParams","ngTableParams","$modal","$modalStack","authService","TranslationService","ListService","$localStorage","$q","RegisteredFieldService","$rootScope",controller])}(),function(){function controller($scope,repository,params,$modalInstance,translationService,$localStorage,$window,$rootScope,ngTableParams){$scope.periodicTaskGuids=_.clone(params.guids)||[],$scope.isRunningAction=!1,$scope.currentTab="info",$scope.estimatedElapsedTime=.5*$scope.periodicTaskGuids.length,$scope.showStartDate=$localStorage.generalOptions.AskForStartDateManualWo,$scope.totalFailedPeriodicTasks=0,$scope.periodicTaskResponses=[],$scope.errorMessage=null,$scope.generateOrders=function(askForStartDateManualWo){if(0!==$scope.periodicTaskGuids.length){var date=null;askForStartDateManualWo&&$scope.showStartDate&&(date=(new Date).toISOString()),$scope.isRunningAction=!0,repository.runAction(repository.apiData.periodicTask.endpoint.generateOrders,$scope.periodicTaskGuids,"startDate="+date).then(function(result){$scope.isRunningAction=!1,$scope.errorMessage=null,$scope.periodicTaskResponses=result,$scope.periodicTaskResponses.forEach(function(periodicTask){if(!periodicTask.ErrorMessages||0===periodicTask.ErrorMessages.length){var succededPeriodicTaskIndex=$scope.periodicTaskGuids.findIndex(function(guid){return guid===periodicTask.Guid});-1!==succededPeriodicTaskIndex&&$scope.periodicTaskGuids.splice(succededPeriodicTaskIndex,1)}}),$scope.estimatedElapsedTime=.5*$scope.periodicTaskGuids.length, 0===$scope.periodicTaskGuids.length?(repository.growl(translationService.translate("web-periodicTask-generateOrdersConfirmationModal-success","Arbeidsordre er blitt opprettet."),"success"),$modalInstance.close()):($scope.errorMessage=translationService.translate("web-periodicTask-generateOrdersConfirmationModal-failed","Periodiske rutiner feilet med å opprette AO, sjekk listen for feil."),repository.growl($scope.errorMessage,"warning"),$scope.currentTab="errorMessages",$scope.totalFailedPeriodicTasks=$scope.periodicTaskGuids.length,$scope.errorMessageTable.reload())},function(error){repository.showError(error),$scope.isRunningAction=!1})}},$scope.errorMessageTable=new ngTableParams({page:1,count:10},{total:$scope.periodicTaskResponses.length,counts:[5,10,20],getData:function($defer,params){$scope.errorMessageTable.settings().total=$scope.periodicTaskResponses.length,$defer.resolve($scope.periodicTaskResponses.filter(function(i){return 0!==i.ErrorMessages.length}).slice((params.page()-1)*params.count(),params.page()*params.count()))}}),$scope.contextMenuOptions=function(item){var options=[];return options.push({html:' '+translationService.translate("web-periodicTask-generateOrdersConfirmationModal-viewPeriodicTask","Åpne periodisk rutine i nytt vindu")+"",click:function($itemScope,$event,modelValue,text,$li){$window.open($rootScope.navigation.href("periodicTask.edit",{guid:item.Guid}),"_blank")}}),$scope.hasReadAccess("WorkOrder")&&item.GuidWorkOrder&&options.push({html:' '+translationService.translate("web-periodicTask-generateOrdersConfirmationModal-viewExistingWorkOrder","Åpne eksisterende arbeidsorde i nytt vindu")+"",click:function($itemScope,$event,modelValue,text,$li){$window.open($rootScope.navigation.href("workOrder.edit",{guid:item.GuidWorkOrder}),"_blank")}}),options},$scope.cancel=function(){$scope.isRunningAction?swal({title:translationService.translate("web-periodicTask-generateOrdersConfirmationModal-swal-title","Vil du lukke dette vinduet?"),text:translationService.translate("web-periodicTask-generateOrdersConfirmationModal-swal-text","Plania vil fortsette å opprette arbeidsordre til fra valgte rutiner, men du vil ikke kunne se potensielle feilmeldinger hvis du lukker dette vinduet."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-button-yes-continue","Ja, fortsett"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.periodicTaskGuids.length!==params.guids.length?$modalInstance.close():$modalInstance.dismiss("canceled")}):$scope.periodicTaskGuids.length!==params.guids.length?$modalInstance.close():$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("PeriodicTaskGenerateOrdersConfirmationModalController",["$scope","Repository","params","$modalInstance","TranslationService","$localStorage","$window","$rootScope","NgTableParams",controller])}(),function(){function controller($scope,repository,$stateParams,$filter,ngTableParams,$modal,authService,translationService,listService,$rootScope){$scope.update="person.edit"===$scope.navigation.current.name,$scope.isBuildingCollapsed=!0,$scope.restrictEdit=!authService.hasEditAccess("person"),$scope.model={Guid:$stateParams.guid},$scope.activateAutocomplete=!1,$scope.viewMode=!!$scope.update,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode};var updateAccess=function(){if($scope.update){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!authService.hasEditAccess(repository.commonService.prefix.Person,checkOtherDo),$scope.restrictDelete=!authService.hasDeleteAccess(repository.commonService.prefix.Person,checkOtherDo)}else $scope.restrictEdit=!authService.hasCreateAccess(repository.commonService.prefix.Person)};updateAccess();var setProperties=function(){var person=$scope.model;person.Department&&($scope.Department=$scope.getEntityCaption(person.Department)),person.Organization&&($scope.Organization=$scope.getEntityCaption(person.Organization)),person.OrganizationUnit&&($scope.OrganizationUnit=$scope.getEntityCaption(person.OrganizationUnit)),person.OrganizationSection&&($scope.OrganizationSection=$scope.getEntityCaption(person.OrganizationSection)),person.PersonRole&&($scope.PersonRole=$scope.getEntityCaption(person.PersonRole)),person.ResourceGroup&&($scope.ResourceGroup=$scope.getEntityCaption(person.ResourceGroup)),person.Area&&($scope.Area=$scope.getEntityCaption(person.Area))};if($scope.update){var columns=["Department.Id","Organization.Id","Organization.Description","OrganizationUnit.Id","OrganizationUnit.Description","OrganizationSection.Id","OrganizationSection.Description","PersonRole.Id","ResourceGroup.Id","Area.Id","Area.Description"];repository.getMainModel(repository.apiData.person.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){var person=response.Data;$scope.model=person,$scope.enableWebNavigation=$rootScope.userInfo.enableWebNavigation,updateAccess(),setProperties(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})}else{$scope.activateAutocomplete=!0,$scope.model.Hours=40;var webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){"object"==typeof prefill.Value?($scope[prefill.Property]=prefill.Value.Label,$scope.model["Guid"+prefill.Property]=prefill.Value.Guid):$scope.model[prefill.Property]=prefill.Value})}$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)},$scope.updatePerson=function(destination){var success=function(result){repository.growl($scope.update?"Person har blitt oppdatert":"Person har blitt lagret","success");var guid=$scope.update?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.update?repository.updateSingle(repository.apiData.person.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.person.url,$scope.model).then(success).catch(error)},$scope.removePerson=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-person-message","Personen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-person-button-confirm","Ja, fjern personen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.person.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-person-success","Personen ble fjernet!"),result,"success"),$scope.goBack("person.list",{menuGuid:$scope.navigation.params.menuGuid})},function(error){swal({title:"Kunne ikke slette personen!",text:error.Message+"

    Vil du deaktivere personen?",type:"error",html:!0,showCancelButton:!0,confirmButtonText:"Deaktiver",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.EmployeeNr="#"+$scope.model.EmployeeNr,$scope.model.IsDeactivated=!0,$scope.updatePerson("person.list"))})})})},$scope.onOrganizationSelect=function(organization){if(!organization)return void($scope.model.GuidOrganization="");$scope.model.GuidOrganization!==organization.Guid&&($scope.model.GuidOrganizationUnit="",$scope.model.GuidOrganizationSection="",delete $scope.model.OrganizationUnit,delete $scope.model.OrganizationSection),$scope.model.GuidOrganization=organization.Guid},$scope.onOrganizationUnitSelect=function(organizationUnit){if(!organizationUnit)return void($scope.model.GuidOrganizationUnit="");$scope.model.GuidOrganizationUnit!==organizationUnit.Guid&&($scope.model.GuidOrganization=organizationUnit.GuidOrganization,$scope.model.GuidOrganizationSection="",delete $scope.model.OrganizationSection),$scope.model.GuidOrganizationUnit=organizationUnit.Guid},$scope.onOrganizationSectionSelect=function(organizationSection){if(!organizationSection)return void($scope.model.GuidOrganizationSection="");$scope.model.GuidOrganizationSection!==organizationSection.Guid&&($scope.model.GuidOrganizationUnit=organizationSection.GuidOrganizationUnit,$scope.model.GuidOrganization=organizationSection.OrganizationUnit.GuidOrganization),$scope.model.GuidOrganizationSection=organizationSection.Guid},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"organization":return filter;case"organizationUnit":return $scope.model.GuidOrganization&&(filter.PropertyFilter=[{Property:"GuidOrganization",Operator:"=",Value:$scope.model.GuidOrganization}]),filter;case"organizationSection":return $scope.model.GuidOrganizationUnit&&(filter.PropertyFilter=[{Property:"GuidOrganizationUnit",Operator:"=",Value:$scope.model.GuidOrganizationUnit}]),filter}};var getMenuLink=function(url,text,icon){var htmlText='';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}};$scope.buildingPersonInfo=new function(){var me=this;this.isLoading=!1,this.columns=[{Position:1,Title:translationService.translate("web-person-buildingXPerson-building-id","ByggNr"),Property:"Building.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-person-buildingXPerson-building-description","Bygg beskrivelse"),Property:"Building.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-person-buildingXPerson-buildingcategory-description","Byggkategori"),Property:"Building.BuildingCategory.Description",PropertyType:"autocomplete",AutocompleteProperty:"GuidBuildingCategory",AutocompleteService:"buildingCategory"},{Position:4,Title:translationService.translate("web-person-buildingXPerson-building-address","Adresse"),Property:"Building.Address",PropertyType:"string"},{Position:5,Title:translationService.translate("web-person-buildingXPerson-building-postalcode","Postnummer"),Property:"Building.PostalCode",PropertyType:"string"},{Position:6,Title:translationService.translate("web-person-buildingXPerson-building-postalarea","Poststed"),Property:"Building.PostalArea",PropertyType:"string"},{Position:7,Title:translationService.translate("web-person-buildingXPerson-costcenter-id","Koststed"),Property:"Building.CostCenter.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidCostCenter",AutocompleteService:"costCenter"},{Position:8,Title:translationService.translate("web-person-buildingXPerson-personrole-id","Rolle"),Property:"PersonRole.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidPersonRole",AutocompleteService:"personRole"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{"Building.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidPerson",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),me.isLoading=!0,repository.GetPaginated(repository.apiData.buildingPerson.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){me.isLoading=!1,me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){me.isLoading=!1,repository.growl(error,"danger")})}}))},this.add=function(){$modal.open({templateUrl:"app/buildingPerson/views/createBuildingPerson.html",controller:"BuildingPersonController",resolve:{params:function(){return{GuidPerson:$scope.model.Guid,GuidPersonRole:$scope.model.GuidPersonRole,personRole:$scope.PersonRole,personCaption:$scope.model.FirstName+" "+$scope.model.LastName,selectedEntityGuids:_.map(me.table.data,function(row){return{GuidBuilding:row.GuidBuilding,GuidPerson:row.GuidPerson,GuidPersonRole:row.GuidPersonRole}}),isModal:!0}}}}).result.then(function(){me.table.reload()},function(){})},this.edit=function(item){$modal.open({templateUrl:"app/buildingPerson/views/editBuildingPerson.html",controller:"BuildingPersonController",resolve:{params:function(){return{modalParam:{isUpdate:!0},guid:item.Guid,isModal:!0}}}}).result.then(function(){me.table.reload()},function(){})},this.remove=function(item){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-person-building-message","Denne persones blir koblet bort fra bygningen!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-person-building-button-confirm","Ja, fjern knytningen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.buildingPerson.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-person-building-success","Knytning ble fjernet!"),result,"success"),me.table.reload()})})},this.contextMenuOptions=function(item){var options=[];return $scope.hasReadAccess("Building")&&options.push(getMenuLink($scope.navigation.href("building.edit",{guid:item.GuidBuilding}),translationService.translate("web-person-buildingXPerson-viewBuilding","Gå til bygg"))),me.canEdit(item)&&options.push({html:' '+translationService.translate("web-person-buildingXPerson-edit","Rediger")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.buildingPersonInfo.edit(item)}}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-person-buildingXPerson-delete","Slett knytning")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.buildingPersonInfo.remove(item)}}),options},this.canCreate=function(){return $scope.hasCreateAccess("BuildingXPerson")},this.canEdit=function(item){return item&&$scope.hasEditAccess("BuildingXPerson")},this.canDelete=function(item){return item&&$scope.hasDeleteAccess("BuildingXPerson")},this.initTable()},$scope.doorKeyXCustomerColumns=[{Position:1,Title:translationService.translate("web-doorKey-id"),Property:"DoorKey.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-doorKey-description"),Property:"DoorKey.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-doorKeyXUser-quantity"),Property:"Quantity",PropertyType:"number"},{Position:4,Title:translationService.translate("web-doorKey-creationDate"),Property:"CreationDate",PropertyType:"date"}],$scope.onClickDoorKeyXCustomer=function(entity,event){event.preventDefault(),event.stopPropagation(),$scope.navigation.go("doorKey.edit",{guid:entity.GuidDoorKey})},$scope.openMail=function(){window.location.href="mailto:"+$scope.model.Email},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("PersonController",["$scope","Repository","$stateParams","$filter","ngTableParams","$modal","authService","TranslationService","ListService","$rootScope",controller])}(),function(){function controller($scope,repository,$stateParams,translationService){$scope.isUpdate="personRole.edit"===$scope.navigation.current.name,$scope.isUpdate&&repository.getSingle(repository.apiData.personRole.url,$stateParams.guid).then(function(response){$scope.model=response.Data},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-personRole-success","Personrolle har blitt oppdatert."):translationService.translate("create-personRole-success","Personrolle har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.personRole.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.personRole.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-personrole-message","Personrollen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-personrole-button-confirm","Ja, fjern Personrollen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.personRole.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-personrole-success","Personrollen ble fjernet!"),result,"success"),repository.growl("Personrollen har blitt fjernet","success"),$scope.goBack("personRole.list",{menuGuid:$scope.navigation.params.menuGuid})})})}}angular.module("Plania").controller("PersonRoleController",["$scope","Repository","$stateParams","TranslationService",controller])}(),function(){function controller($scope,repository,generalOptionsService){$scope.model={},repository.getSingleWithNoParameter(repository.apiData.planiaSystem.url).then(function(response){$scope.reload=!0,$scope.model=response,$scope.packageArray=$scope.model.License.Packages.split(", "),$scope.moduleArray=$scope.model.License.Modules.split(", ")},function(error){repository.growl(error,"danger")}),repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix.Undefined).then(function(result){$scope.modules=result}),$scope.hasPackage=function(plPackage){return _.contains($scope.packageArray,plPackage)},$scope.hasModule=function(plModule){return _.contains($scope.moduleArray,plModule)},$scope.getModuleIcon=function(moduleName){return repository.moduleService.getModuleIcon(moduleName)},generalOptionsService.refreshGeneralOptions(),$scope.hasModule=$scope.$root.hasModule,$scope.exceededLicense=function(usedAmount,licensedAmount){return!!usedAmount&&parseInt(usedAmount)>parseInt(licensedAmount)}}angular.module("Plania").controller("PlaniaSystemController",["$scope","Repository","GeneralOptionsService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,constants,ngTableParams,$modal,listService,colorService){$scope.isUpdate="priority.edit"===$scope.navigation.current.name,$scope.model={DeadlinePeriodUnit:"Undefined",EntityType:"Undefined"},$scope.entityTypes=[{key:repository.apiData.workOrder.prefix,value:translationService.translate("web-enum-prefix-workorder")},{key:repository.apiData.condition.prefix,value:translationService.translate("web-enum-prefix-condition")},{key:repository.apiData.deviation.prefix,value:translationService.translate("web-enum-prefix-deviation")}];var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Priority,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Priority,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.Priority),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Priority)};$scope.isUpdate?repository.getSingle(repository.apiData.priority.url,$stateParams.guid).then(function(response){$scope.model=response.Data,$scope.model.Color=colorService.convertToRainbow($scope.model.Color),updateAccess()},function(error){repository.growl(error,"danger")}):$scope.model.Level=constants.priorityLevel.Normal,$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-priority-success","Prioritet har blitt oppdatert."):translationService.translate("create-priority-success","Prioritet har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack("priority."+destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.priority.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.priority.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-priority-message","Prioriteten vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-priority-button-confirm","Ja, fjern Prioriteten"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.priority.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-priority-success","Prioriteten ble fjernet!"),result,"success"),$scope.goBack("priority.list",{menuGuid:$scope.navigation.params.menuGuid})},function(error){var swalMessage=error.Message;error.IsDeactivateable&&(swalMessage+="

    Vil du deaktivere prioriteten?"),swal({title:"Kunne ikke slette prioriteten!",text:swalMessage,type:"error",html:!0,showCancelButton:!0,confirmButtonText:error.IsDeactivateable?"Deaktiver":"Ok",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.IsDeactivated=!0,$scope.model.Description=("#"+$scope.model.Description).substring(0,20),$scope.update("priority.list"))})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("PriorityController",["$scope","Repository","$stateParams","TranslationService","Constants","ngTableParams","$modal","ListService","ColorService",controller])}(),function(){function controller($scope,repository,$state){$scope.viewModel={},$scope.viewModel.OldPassword="",$scope.viewModel.NewPassword="",$scope.viewModel.ConfirmPassword="",$scope.changePassword=function(){repository.createSingle(repository.apiData.user.urlChangePassword,$scope.viewModel).then(function(){repository.growl("Passord har blitt oppdatert","success"),$state.go("profile.view")},function(error){repository.growl(error,"danger")})}}angular.module("Plania").controller("ChangePasswordController",["$scope","Repository","$state",controller])}(),function(){function controller($scope,rootScope,repository,config,$modal,$rootScope,$localStorage,Upload){$scope.activateAutocomplete=!1,$scope.imageApiUrl=config.baseUrlApi+repository.apiData.image.url,$scope.profileModel={},$scope.profileModel.GuidResourceGroup="",$scope.useTwoFactorAuthentication=!!$localStorage.generalOptions.TwoFactorAuthenticationOption,$scope.showError={resourceGroup:!1},repository.getSingle(repository.apiData.user.url,rootScope.userInfo.guidUser).then(function(result){$scope.user=result.Data,$scope.useTwoFactorAuthentication=$scope.user.IsTwoFactorAuthenticationEnabled,repository.getSingle(repository.apiData.person.url,$scope.user.GuidPerson,JSON.stringify(["ResourceGroup.Id"])).then(function(result){$scope.person=result.Data,$scope.person.ResourceGroup&&($scope.selectedResourceGroup=$scope.person.ResourceGroup.Id),setTimeout(function(){$scope.activateAutocomplete=!0},250)})}),$scope.autoCompleteFilter=function(filterName){switch(filterName){case"resourceGroup":return{PropertyFilter:[{Property:"DoesCleaningTasks",Operator:"=",Value:!0}]}}},$scope.setResourceGroup=function(resourceGroup){if(!resourceGroup)return void($scope.showError.resourceGroup=!0);$scope.showError.resourceGroup=!1,$scope.person.GuidResourceGroup=resourceGroup.Guid,$scope.profileModel.GuidResourceGroup=resourceGroup.Guid,$scope.selectedResourceGroup=resourceGroup.Id+" ",repository.createSingle(repository.apiData.user.urlChangeTeam,$scope.profileModel).then(function(result){repository.growl("Oppdatert brukers team","success")},repository.showError)},$scope.uploadImage=function(images){if(!(images.length<1)){$modal.open({templateUrl:"app/common/views/imageUploadModal.html",controller:"ImageUploadModalController",backdrop:"static",size:"lg",resolve:{params:function(){return{image:images[0],targetSize:300,areaType:"square"}}}}).result.then(function(croppedImage){function handleFileUpload(file,originalImage){var readCroppedImage=new Promise(function(resolve,reject){var reader=new FileReader;reader.onload=function(e){try{imageViewModel.ImageSrc=e.target.result.substr(e.target.result.indexOf("base64,")+"base64,".length),imageViewModel.Name=file.name,resolve()}catch(error){repository.growl(error),reject()}},reader.readAsDataURL(file)}),readOriginalImage=new Promise(function(resolve,reject){var reader=new FileReader;reader.onload=function(e){try{imageViewModel.OriginalImageSrc=e.target.result.substr(e.target.result.indexOf("base64,")+"base64,".length),resolve()}catch(error){repository.growl(error),reject()}},reader.readAsDataURL(originalImage)});Promise.allSettled([readCroppedImage,readOriginalImage]).then(uploadImages)}function uploadImages(){var files=[imageViewModel];repository.createMultiple(repository.apiData.image.url,files).then(function(imageResult){var newGuidImage=imageResult[0].Guid,changeUserImageDto={GuidImage:newGuidImage,GuidUser:rootScope.userInfo.guidUser};repository.createSingle(repository.apiData.user.urlChangeImage,changeUserImageDto).then(function(result){$scope.user.GuidImage=newGuidImage,$rootScope.userInfo.guidImage=newGuidImage,$localStorage.userData.guidImage=newGuidImage,repository.growl("Bilde oppdatert","success")},function(error){repository.growl(error,"danger")})},function(error){repository.growl(error,"danger")})}var imageViewModel={ImageSrc:null,Name:null,OriginalImageSrc:null,GuidUser:$scope.user.Guid};handleFileUpload(croppedImage,images[0])})}}}angular.module("Plania").controller("MyProfileController",["$scope","$rootScope","Repository","config","$modal","$rootScope","$localStorage","Upload",controller])}(),function(){function controller($scope,repository,registeredFieldService,translationService,ngTableParams,ListService){var userData=repository.authService.getUserData();$scope.activateAutocomplete=!0,$scope.missingMandatoryProperties=[],$scope.creationMethod="";var basicInformationFields=["Description","StartDate","EndDate","Text"],connectionsFields=["GuidEstate","GuidBuilding","GuidArea","GuidCostCenter","GuidProjectCategory"],responsiblesField=[];$scope.model={isTemplate:!1},userData.guidPerson&&($scope.model.ManagerPerson={Caption:userData.personFirstName+" "+userData.personLastName},$scope.model.GuidManagerPerson=userData.guidPerson,$scope.model.OwnerPerson={Caption:userData.personFirstName+" "+userData.personLastName},$scope.model.GuidOwnerPerson=userData.guidPerson),registeredFieldService.getRegisteredField(repository.commonService.prefix.Project).then(function(result){$scope.fieldRules=result}),$scope.steps=[{stepIndex:0,name:"startPage",hidden:!0},{stepIndex:1,name:"chooseTemplate",hidden:!1,title:translationService.translate("web-project-section-title-templates","Prosjektmal")},{stepIndex:2,name:"basicInfo",hidden:!1,title:translationService.translate("web-project-section-title-basicInformation","Basisinformasjon")},{stepIndex:3,name:"connections",hidden:!1,title:translationService.translate("web-project-section-title-connections","Tilknytninger")},{stepIndex:4,name:"responsibles",hidden:!1,title:translationService.translate("web-project-section-title-responsibles","Ansvarsfordeling")}],$scope.currentStep=$scope.steps[0],$scope.hasError=function(field){return!(!$scope.missingMandatoryProperties.includes(field)||$scope.model[field])||!(!$scope.missingMandatoryProperties.includes(field)||!$scope.model[field])&&(_.remove($scope.missingMandatoryProperties,function(property){return property===field}),!1)};var sectionIsValid=function(fields){return $scope.missingMandatoryProperties=[],fields.forEach(function(field){_.find($scope.fieldRules,{DomainFieldName:field,Mandatory:!0})&&!$scope.model[field]&&$scope.missingMandatoryProperties.push(field)}),!($scope.missingMandatoryProperties.length>0)};$scope.isEndDateValid=function(){return!($scope.model.EndDate&&$scope.model.EndDate<$scope.model.StartDate)},$scope.handleNextStep=function(){switch($scope.currentStep.name){case"startPage":"template"===$scope.creationMethod?($scope.steps=[{stepIndex:0,name:"startPage",hidden:!0},{stepIndex:1,name:"chooseTemplate",hidden:!1,title:translationService.translate("web-project-section-title-templates","Prosjektmal")},{stepIndex:2,name:"basicInfo",hidden:!1,title:translationService.translate("web-project-section-title-basicInformation","Basisinformasjon")},{stepIndex:3,name:"connections",hidden:!1,title:translationService.translate("web-project-section-title-connections","Tilknytninger")},{stepIndex:4,name:"responsibles",hidden:!1,title:translationService.translate("web-project-section-title-responsibles","Ansvarsfordeling")}],$scope.currentStep=_.find($scope.steps,{name:"chooseTemplate"})):($scope.steps=[{stepIndex:0,name:"startPage",hidden:!0},{stepIndex:1,name:"basicInfo",hidden:!1,title:translationService.translate("web-project-section-title-basicInformation","Basisinformasjon")},{stepIndex:2,name:"connections",hidden:!1,title:translationService.translate("web-project-section-title-connections","Tilknytninger")},{stepIndex:3,name:"responsibles",hidden:!1,title:translationService.translate("web-project-section-title-responsibles","Ansvarsfordeling")}],$scope.currentStep=_.find($scope.steps,{name:"basicInfo"}));break;case"chooseTemplate":$scope.currentStep=_.find($scope.steps,{name:"basicInfo"});break;case"basicInfo":sectionIsValid(basicInformationFields)&&$scope.isEndDateValid()&&($scope.currentStep=_.find($scope.steps,{name:"connections"}));break;case"connections":sectionIsValid(connectionsFields)&&($scope.currentStep=_.find($scope.steps,{name:"responsibles"}));break;case"responsibles":sectionIsValid(responsiblesField)&&$scope.create()}},$scope.handlePreviousStep=function(){for(var i=1;i<$scope.steps.length;i++){if($scope.steps[i].name===$scope.currentStep.name)return void("template"!==$scope.creationMethod&&"basicInfo"===$scope.currentStep.name?$scope.currentStep=_.find($scope.steps,{ name:"startPage"}):$scope.currentStep=$scope.steps[i-1])}},$scope.setCreationMethod=function(choice){"blank"===choice&&($scope.model.GuidProjectTemplate=""),$scope.creationMethod=choice,$scope.handleNextStep()},$scope.create=function(){$scope.hasCreateAccess("Project")&&($scope.isSaving||($scope.isSaving=!0,""===$.trim($scope.model.Id)&&($scope.model.Id=null),repository.createSingle(repository.apiData.project.url,$scope.model).then(function(response){$scope.isSaving=!1,$scope.model.Guid=response.Guid,$scope.model.Id=response.Id,repository.growl(translationService.translate("web-project-created","Opprettet prosjekt"),"success"),$scope.goBack("project.edit",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})},function(error){$scope.isSaving=!1,swal(translationService.translate("web-project-error","Feil ved opprettelse"),error,"error")})))},$scope.onProjectTemplateSelect=function(project){return project?project.Guid===$scope.model.GuidProjectTemplate?void($scope.model.GuidProjectTemplate=""):void($scope.model.GuidProjectTemplate=project.Guid):void($scope.model.GuidProjectTemplate="")},$scope.onEstateSelect=function(estate){if(!estate)return void($scope.model.GuidEstate="");$scope.model.GuidEstate!==estate.Guid&&($scope.model.GuidBuilding="",$scope.model.Building="",$scope.model.GuidArea="",$scope.model.Area=""),$scope.model.GuidEstate=estate.Guid},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidArea="",$scope.model.Area=""),$scope.model.GuidBuilding=building.Guid,$scope.model.GuidEstate&&""!==$scope.model.GuidEstate&&$scope.model.GuidEstate===building.GuidEstate||($scope.model.GuidEstate=building.GuidEstate,$scope.model.Estate={Caption:building.Estate.Id+" - "+building.Estate.Description}),building.CostCenter&&($scope.model.CostCenter={Caption:building.CostCenter.Caption},$scope.model.GuidCostCenter=building.GuidCostCenter)},$scope.onAreaSelect=function(area){if(!area)return void($scope.model.GuidArea="");$scope.model.GuidArea=area.Guid,$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding&&$scope.model.GuidBuilding===area.GuidBuilding||($scope.model.GuidBuilding=area.GuidBuilding,$scope.model.Building={Caption:area.Building.Caption}),$scope.model.GuidEstate&&""!==$scope.model.GuidEstate&&$scope.model.GuidEstate===area.Building.GuidEstate||($scope.model.GuidEstate=area.Building.Estate.Guid,$scope.model.Estate={Caption:area.Building.Estate.Caption})},$scope.onProjectCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidProjectCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidProjectCategory=category.Guid},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"estate":return filter;case"building":if($scope.model.GuidEstate){var estateFieldRule=_.filter($scope.fieldRules,function(o){return"GuidEstate"===o.FieldName});if(1===estateFieldRule.length&&estateFieldRule[0].Hidden)return filter;filter.PropertyFilter=[{Property:"GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]}return filter;case"area":return filter={GuidBuilding:$scope.model.GuidBuilding},$scope.model.GuidEstate&&(filter.PropertyFilter=[{Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]),filter;case"person":return filter;case"supplier":return filter.PropertyFilter=[{Property:"IsDeactivated",Operator:"=",Value:!1}],filter;case"project":return filter.PropertyFilter=[{Property:"IsTemplate",Operator:"=",Value:!0}],filter;case"projectCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}return filter},$scope.getPropertyValue=function(entity,column){return ListService.GetPropertyValue(entity,column)},$scope.projectTemplateColumns=[{Position:1,Title:translationService.translate("web-project-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-project-description","Beskrivelse"),Property:"Description",PropertyType:"string"}],$scope.projectTemplates=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{IsTemplate:!0}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,filterDelay:10,getData:function($defer,params){if($scope.hasReadAccess("Project")){var columns=[];$scope.projectTemplateColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.project.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),params.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}})}angular.module("Plania").controller("CreateProjectController",["$scope","Repository","RegisteredFieldService","TranslationService","ngTableParams","ListService",controller])}(),function(){function controller($scope,$modalInstance,modalParams,repository,translationService,$rootScope,$filter){$scope.budget=modalParams.budget,$scope.rootScope=$rootScope,$scope.newComment={text:""},$scope.budgetHasError=!1,$scope.budgetErrorMsg="";$scope.isBudgetValid=function(){return null===$scope.budget?($scope.budgetHasError=!0,$scope.budgetErrorMsg=translationService.translate("web-project-budget-error-empty","Budsjettfeltet kan ikke være tomt"),!1):void 0===$scope.budget?($scope.budgetHasError=!0,$scope.budgetErrorMsg=translationService.translate("web-project-budget-error-undefined","Feil i budsjettfelt"),!1):$scope.budget===modalParams.budget?($scope.budgetHasError=!0,$scope.budgetErrorMsg=translationService.translate("web-project-budget-error-unchanged","Budsjett er uendret"),!1):($scope.budgetHasError=!1,$scope.budgetErrorMsg="",!0)},$scope.update=function(){$scope.hasEditAccess("Project")&&$scope.isBudgetValid()&&repository.updateSingle(repository.apiData.project.endpoint.updateBudget,{Guid:modalParams.guid,BudgetAmount:$scope.budget,GuidUser:repository.authService.getUserData().guidUser}).then(function(){$scope.addComment(),repository.growl("Budsjett har blitt oppdatert","success"),$scope.$close($scope.budget)}).catch(function(err){repository.growl(err,"danger")})},$scope.addComment=function(){var comment=translationService.translate("web-project-budget-edit","Budsjettendring")+" "+$filter("number")($scope.budget,2)+" "+translationService.translate("web-project-budget-currency","kr");""!==$scope.newComment.text&&(comment+=" - "+$scope.newComment.text);var newComment={Comment:comment};newComment.GuidProject=modalParams.guid,repository.createSingle(repository.apiData.entityComment.url,newComment).then(function(result){},function(error){repository.growl(error,"danger")})}}angular.module("Plania").controller("EditProjectBudgetModalController",["$scope","$modalInstance","modalParams","Repository","TranslationService","$rootScope","$filter",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,$state,translationService,signalR,$timeout,$window,config,$location){$scope.model={Guid:$stateParams.guid,IsTemplate:"project.edit"!==$scope.navigation.current.name},$scope.viewMode=($scope.navigation.current.name,!0),$scope.isModelLoading=!0,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.forceReloadDocumentTable=!1,$scope.activateAutocomplete=!1;var updateAccess=function(){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.Project,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Project,checkOtherDO);var user=repository.authService.getUserData();$scope.isProjectAdministrator=$scope.model.GuidOwnerPerson===user.guidPerson||$scope.model.GuidManagerPerson===user.guidPerson||user.isSystemAdministrator||user.isProjectAdministrator,$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.Project,checkOtherDO)||!$scope.isProjectAdministrator},availableHashLocations=["#info","#progress","#economy","#resource","#documents","#deviations"],updateLocation=function(){var hash=window.location.hash;hash&&availableHashLocations.includes(hash)?$('#projectTabs a[data-target="'+hash+'"]').tab("show"):$('#projectTabs a[data-target="#info"]').tab("show"),$scope.currentPage=hash?hash.substr(1):"info"};updateLocation(),$scope.$on("$locationChangeSuccess",function(event,newUrl,oldUrl){updateLocation()}),$scope.setTab=function(tab){$location.hash(tab).replace()};var columns=["Estate.Id","Estate.Description","Estate.Guid","Building.Id","Building.Description","Area.Id","Area.Description","CostCenter.Id","CostCenter.Description","ProjectCategory.Description","Department.Id","Department.Description","Supplier.Id","Supplier.Description","Customer.Id","Customer.Description","ProjectType.Id","ManagerPerson.FirstName","ManagerPerson.LastName","OwnerPerson.FirstName","OwnerPerson.LastName","ResponsiblePerson.FirstName","ResponsiblePerson.LastName","ResponsiblePerson2.FirstName","ResponsiblePerson2.LastName","ProjectStatus.Id","ProjectStatus.Description","ProjectStatus.Stage","ProjectStatus.ProjectPhase.Id","ProjectStatus.ProjectPhase.Description","ProjectStatus.ProjectPhase.Guid","ProjectStatus.ProjectPhase.IndexPosition"];(function(){$scope.hasReadAccess("Project")&&repository.getMainModel(repository.apiData.project.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.reload=!0,$scope.reloadAlarmLogTable=!0,$scope.isModelLoading=!1,updateAccess(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})})(),$scope.update=function(destination){if($scope.hasCreateAccess("Project")){if($scope.isModelLoading)return void repository.growl(translationService.translate("web-wait-for-model","Kan ikke lagre før all data er lastet ned"),"success");var success=function(result){delete $scope.model.IsClosing,repository.growl("Prosjekt har blitt oppdatert","success"),repository.commonService.setLastRegisterGuid(destination,$scope.model.Guid),$scope.canChangePhase=$scope.userInfo.guidPerson===$scope.model.GuidManagerPerson||$scope.userInfo.guidPerson===$scope.model.GuidOwnerPerson||$scope.userInfo.isSystemAdministrator||$scope.userInfo.isProjectAdministrator,$scope.goBack(destination,{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){repository.growl("string"==typeof error?error:error.Data.Message,"danger"),$scope.model.IsClosing&&$scope.goBack(destination,{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid}),delete $scope.model.IsClosing};$scope.model.IsTemplate?repository.updateSingle(repository.apiData.project.endpoint.updateTemplate,$scope.model).then(success).catch(error):repository.updateSingle(repository.apiData.project.url,$scope.model).then(success).catch(error)}},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-project-message","Prosjektet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-project-button-confirm","Ja, fjern prosjektet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){$scope.hasDeleteAccess("Project")&&repository.deleteSingle(repository.apiData.project.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-project-delete-success","Prosjektet ble slettet!"),"","success"),$scope.goBack("project.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.sendEmail=function(){var filter={GuidProject:$scope.model.Guid};filter.ChildDocumentsOnProject=[],filter.ChildDocumentsOnProject.push(repository.commonService.prefix.Project),filter.ChildDocumentsOnProject.push(repository.commonService.prefix.WorkOrder),filter.ChildDocumentsOnProject.push(repository.commonService.prefix.PurchaseOrder),filter.ChildDocumentsOnProject.push(repository.commonService.prefix.Deviation),filter.ChildDocumentsOnProject.push(repository.commonService.prefix.Condition);var onNewDocument=function(){$scope.forceReloadDocumentTable=!1,$timeout(function(){$scope.forceReloadDocumentTable=!0},250)};$modal.open({templateUrl:"app/common/views/emailModal.html",controller:"EmailModalController",size:"lg",resolve:{params:function(){return{entity:"Project",model:$scope.model,onNewDocument:onNewDocument}}}}).result.then(function(){$scope.reloadAlarmLogTable=!0})},signalR.on("UpdatedProjectSums"+$scope.model.Guid,function(economyColumns){$scope.hasReadAccess("Project")&&($scope.updateBudgetFunctions.isCalculating=!0,repository.getSingle(repository.apiData.project.url,$stateParams.guid).then(function(response){economyColumns.forEach(function(field){$scope.model[field]=response.Data[field]}),$scope.updateBudgetFunctions.isCalculating=!1},function(error){repository.growl(error,"danger"),$scope.updateBudgetFunctions.isCalculating=!1}))}),$scope.$on("$destroy",function(){signalR.off("UpdatedProjectSums"+$scope.model.Guid)}),$scope.updateBudgetFunctions={isCalculating:!1,update:function(){$scope.updateBudgetFunctions.isCalculating&&!$scope.hasReadAccess("Project")||repository.getSingle(repository.apiData.project.endpoint.updateSingleSum,$scope.model.Guid).then(function(){$scope.updateBudgetFunctions.isCalculating=!0,repository.growl(translationService.translate("web-project-update-sum-started","Rekalkulering av summer har startet"),"success")},function(error){repository.growl(error,"danger")})}},$scope.hasEditAccessBudget=function(){return repository.authService.getUserData().isUserAdministrator||repository.authService.getUserData().guidPerson===$scope.model.GuidOwnerPerson||repository.authService.getUserData().guidPerson===$scope.model.GuidManagerPerson},$scope.modifyBudget=function(){$modal.open({templateUrl:"app/project/views/editProjectBudgetModal.html",controller:"EditProjectBudgetModalController",resolve:{modalParams:function(){return{budget:$scope.model.BudgetAmount,guid:$scope.model.Guid}}}}).result.then(function(newBudget){$scope.model.BudgetAmount=newBudget})},$scope.showHourTypes=function(){$modal.open({templateUrl:"app/hourType/views/listHourTypeModal.html",controller:"HourTypeModalController",resolve:{modalParams:function(){return{Project:$scope.model}}},size:"lg"})}}angular.module("Plania").controller("ProjectController",["$scope","Repository","$stateParams","$modal","$state","TranslationService","SignalR","$timeout","$window","config","$location",controller])}(),function(){function controller($scope,$rootScope,repository,translationService,$modal,autoCompleteService,listService,ngTableParams,$window){$scope.rootScope=$rootScope,$scope.deviationSetting={},$scope.conditionSetting={},listService.getWebListViews(null,repository.apiData.deviation.prefix,!1,null,{}).then(function(result){$scope.deviationSetting.deviationListOptions=result.listOptions,$scope.deviationSetting.deviationListSetup=result.selectedListSetup,$scope.deviationTable=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{PropertyFilter:[{Property:"WorkOrder.GuidProject",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];$scope.deviationSetting.deviationListSetup.Columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.deviation.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.deviationTable.settings().total=result.TotalCount,$scope.deviationTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})}),$scope.$watch("deviationSetting.deviationListSetup",function(newValue,oldValue){oldValue!==newValue&&$scope.deviationTable&&($scope.deviationTable.$params.sorting=$scope.deviationSetting.deviationListSetup.Sorting,$scope.deviationSetting.deviationListSetup.GroupBy?$scope.deviationTable.settings().groupBy=function(obj){return!!$scope.deviationSetting.deviationListSetup.GroupBy&&($scope.deviationSetting.deviationListSetup.GroupBy.split(".").forEach(function(attr){obj=obj?obj[attr]:""}),obj)}:$scope.deviationTable.settings().groupBy=null,$scope.deviationTable.reload())}),listService.getWebListViews(null,repository.apiData.condition.prefix,!1,null,{}).then(function(result){$scope.conditionSetting.conditionListOptions=result.listOptions,$scope.conditionSetting.conditionListSetup=result.selectedListSetup,$scope.conditionTable=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{PropertyFilter:[{Property:"WorkOrder.GuidProject",Operator:"=",Value:$scope.model.Guid}],isCorrectiveAction:!0}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];$scope.conditionSetting.conditionListSetup.Columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.condition.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.conditionTable.settings().total=result.TotalCount,$scope.conditionTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})}),$scope.$watch("conditionSetting.conditionListSetup",function(newValue,oldValue){oldValue!==newValue&&$scope.conditionTable&&($scope.conditionTable.$params.sorting=$scope.conditionSetting.conditionListSetup.Sorting,$scope.conditionSetting.conditionListSetup.GroupBy?$scope.conditionTable.settings().groupBy=function(obj){return!!$scope.conditionSetting.conditionListSetup.GroupBy&&($scope.conditionSetting.conditionListSetup.GroupBy.split(".").forEach(function(attr){obj=obj?obj[attr]:""}),obj)}:$scope.conditionTable.settings().groupBy=null,$scope.conditionTable.reload())}),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.selectedDeviations=[],$scope.allDeviationsSelected=!1,$scope.selectedConditions=[],$scope.allConditionsSelected=!1,$scope.selectAllRows=function(table,selectedList,allSelectedProperty){$scope[allSelectedProperty]?(table.data.forEach(function(row){var index=_.findIndex(selectedList,function(o){return o===row.Guid});selectedList.splice(index,1)}),$scope[allSelectedProperty]=!1):(table.data.forEach(function(row){_.contains(selectedList,row.Guid)||selectedList.push(row.Guid)}),$scope[allSelectedProperty]=!0)},$scope.itemIsSelected=function(guid,selectedList){return _.contains(selectedList,guid)},$scope.selectItem=function(guid,selectedList){if(_.contains(selectedList,guid)){for(var i=0;i';return htmlText+=icon?' ':' ',htmlText+=text+"",{html:htmlText,isHref:!0}},addDefaultParentObjectNavigation=function(item,options){if($rootScope.userInfo.enableWebNavigation){var navigationOptions=[];!item.GuidEstate||item.GuidBuilding||item.GuidEquipment||item.GuidArea||!$scope.rootScope.hasReadAccess("Estate")||navigationOptions.push(getMenuLink($rootScope.navigation.href("estate.edit",{guid:item.GuidEstate}),translationService.translate("web-project-contextMenu-viewEstate","Gå til eiendom"))),item.GuidBuilding&&!item.GuidEquipment&&!item.GuidArea&&$scope.rootScope.hasReadAccess("Building")&&navigationOptions.push(getMenuLink($rootScope.navigation.href("building.edit",{guid:item.GuidBuilding}),translationService.translate("web-project-contextMenu-viewBuilding","Gå til bygg"))),item.GuidEquipment&&$scope.rootScope.hasReadAccess("Equipment")&&navigationOptions.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:item.GuidEquipment}),translationService.translate("web-project-contextMenu-viewEquipment","Gå til anlegg"))),item.GuidArea&&$scope.rootScope.hasReadAccess("Area")&&(item.Area&&item.Area.IsHousing?navigationOptions.push(getMenuLink($rootScope.navigation.href("housing.edit",{guid:item.GuidArea}),translationService.translate("web-project-contextMenu-viewHousing","Gå til bolig"))):navigationOptions.push(getMenuLink($rootScope.navigation.href("area.edit",{guid:item.GuidArea}),translationService.translate("web-project-contextMenu-viewArea","Gå til areal")))),navigationOptions.length>0&&(navigationOptions[0].hasTopDivider=!!options.length,navigationOptions.forEach(function(o){options.push(o)}))}};$scope.conditionMenuOptions=function(item){var options=[];return"CorrectiveAction"===item.Type?options.push(getMenuLink($rootScope.navigation.href("condition.edit",{guid:item.Guid}),translationService.translate("web-projectCondition-contextMenu-viewCorrectiveAction","Åpne tiltak"))):"CurrentConditionInfo"===item.Type?options.push(getMenuLink($rootScope.navigation.href("condition.edit",{guid:item.Guid}),translationService.translate("web-projectCondition-contextMenu-viewCurrentConditionInfo","Åpne gjeldende tiltak"))):options.push(getMenuLink($rootScope.navigation.href("condition.edit",{guid:item.Guid}),translationService.translate("web-projectCondition-contextMenu-viewCondition","Åpne tilstand"))),"CurrentConditionInfo"!==item.Type&&$scope.rootScope.hasReadAccess("WorkOrder")&&$rootScope.userInfo.enableWebNavigation&&(item.GuidInspectionWorkOrder&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidInspectionWorkOrder}),translationService.translate("web-projectCondition-contextMenu-viewInspectionWorkOrder","Gå til arbeidsordre som opprettet tiltaket"))),item.GuidCorrectiveWorkOrder&&("Closed"===item.Status?options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidCorrectiveWorkOrder}),translationService.translate("web-projectCondition-contextMenu-viewCorrectiveWorkOrderClosed","Gå til arbeidsordre som lukket tiltaket"))):options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidCorrectiveWorkOrder}),translationService.translate("web-projectCondition-contextMenu-viewCorrectiveWorkOrder","Gå til arbeidsordre som jobber med tiltaket"))))),addDefaultParentObjectNavigation(item,options),options},$scope.deviationMenuOptions=function(item){var options=[];return options.push(getMenuLink($rootScope.navigation.href("deviation.edit",{guid:item.Guid}),translationService.translate("web-projectDeviation-contextMenu-viewDeviation","Åpne avvik"))),$scope.rootScope.hasReadAccess("WorkOrder")&&$rootScope.userInfo.enableWebNavigation&&(item.GuidInspectionWorkOrder&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidInspectionWorkOrder}),translationService.translate("web-projectDeviation-contextMenu-viewInspectionWorkOrder","Gå til arbeidsordre som opprettet avviket"))),item.GuidCorrectiveWorkOrder&&("Closed"===item.Status?options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidCorrectiveWorkOrder}),translationService.translate("web-projectDeviation-contextMenu-viewCorrectiveWorkOrderClosed","Gå til arbeidsordre som lukket avviket"))):options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidCorrectiveWorkOrder}),translationService.translate("web-projectDeviation-contextMenu-viewCorrectiveWorkOrder","Gå til arbeidsordre som jobber med avviket"))))),addDefaultParentObjectNavigation(item,options),options}}angular.module("Plania").directive("projectDeviations",function(){return{restrict:"E",scope:{model:"=ngModel",viewMode:"=viewMode",update:"=update",restrictEdit:"=restrictEdit",isModelLoading:"=isModelLoading"},controller:["$scope","$rootScope","Repository","TranslationService","$modal","AutoCompleteService","ListService","ngTableParams","$window",controller],templateUrl:"app/project/views/projectDeviationsDirective.html"}})}(),function(){function controller($scope,$rootScope,repository,translationService,documentService,$modal,listService,ngTableParams){$scope.rootScope=$rootScope,$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.projectDocumentsColumns=[{Position:1,Title:translationService.translate("web-document-id"),Property:"Document.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-document-description"),Property:"Document.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-document-filename"),Property:"Document.FilePath",PropertyType:"string"},{Position:4,Title:translationService.translate("web-document-documentType"),Property:"Document.DocumentType.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-document-documentCategory"),Property:"Document.DocumentCategory.Description",PropertyType:"string"}],$scope.showProjectDocuments=!0,$scope.showWorkOrderDocuments=!0,$scope.showPurchaseOrderDocuments=!0,$scope.showDeviationDocuments=!0,$scope.showConditionDocuments=!0,$scope.documentSearch={},$scope.projectDocumentsTable=new ngTableParams({page:1,count:20,sorting:{"Document.Description":"asc"},filter:{GuidProject:$scope.model.Guid}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var cols=[];$scope.projectDocumentsColumns.forEach(function(col){cols.push(col.Property)});var filter=$scope.projectDocumentsTable.filter();filter.ChildDocumentsOnProject=[],$scope.showProjectDocuments&&filter.ChildDocumentsOnProject.push(repository.commonService.prefix.Project),$scope.showWorkOrderDocuments&&filter.ChildDocumentsOnProject.push(repository.commonService.prefix.WorkOrder),$scope.showPurchaseOrderDocuments&&filter.ChildDocumentsOnProject.push(repository.commonService.prefix.PurchaseOrder),$scope.showDeviationDocuments&&filter.ChildDocumentsOnProject.push(repository.commonService.prefix.Deviation),$scope.showConditionDocuments&&filter.ChildDocumentsOnProject.push(repository.commonService.prefix.Condition),repository.GetPaginated(repository.apiData.documentXEntity.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(cols)).then(function(result){$scope.projectDocumentsTable.settings().total=result.TotalCount,$scope.projectDocumentsTable.settings().filterDelay=500,$defer.resolve(result.List)})}});var setFiltername=function(){var activeFilters=[];$scope.showProjectDocuments&&activeFilters.push(translationService.translate("web-enum-prefix-project","Prosjekt")),$scope.showWorkOrderDocuments&&activeFilters.push(translationService.translate("web-enum-prefix-workorder","Arbeidsordre")),$scope.showPurchaseOrderDocuments&&activeFilters.push(translationService.translate("web-enum-prefix-purchaseorder","Bestilling")),$scope.showDeviationDocuments&&activeFilters.push(translationService.translate("web-enum-prefix-deviation","Avvik")),$scope.showConditionDocuments&&activeFilters.push(translationService.translate("web-enum-prefix-condition","Tilstand/Tiltak")),$scope.selectedFilterName=activeFilters.join(", ")};$scope.SetChildOptions=function(option){switch(option){case"Project":$scope.showProjectDocuments=!$scope.showProjectDocuments;break;case"WorkOrder":$scope.showWorkOrderDocuments=!$scope.showWorkOrderDocuments;break;case"PurchaseOrder":$scope.showPurchaseOrderDocuments=!$scope.showPurchaseOrderDocuments;break;case"Deviation":$scope.showDeviationDocuments=!$scope.showDeviationDocuments;break;case"Condition":$scope.showConditionDocuments=!$scope.showConditionDocuments}setFiltername(),$scope.projectDocumentsTable.reload()},setFiltername();var resolveParams=function(){return{guidProject:$scope.model.Guid}};$scope.addNewDocument=function(){$modal.open({templateUrl:"app/document/views/createDocumentModal.html",controller:"CreateDocumentXEntityController",size:"lg",resolve:{params:resolveParams}}).result.then(function(){$scope.projectDocumentsTable.reload()},function(msg){$scope.projectDocumentsTable.reload()})},$scope.addExistingDocument=function(){$modal.open({templateUrl:"app/document/views/addExistingDocument.html",controller:"AddExistingDocumentController",resolve:{params:resolveParams}}).result.then(function(){$scope.projectDocumentsTable.reload()},function(msg){})},$scope.removeDocument=function(document){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-document-message","Dokumentet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-document-button-confirm","Ja, fjern dokumentet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.documentXEntity.url,document.Guid).then(function(result){swal(translationService.translate("web-swal-document-success","Dokumentet ble fjernet!"),result,"success"),repository.growl("Dokumentet har blitt fjernet","success"),$scope.projectDocumentsTable.reload()})})},$scope.canDeleteFromProject=function(document){if($scope.model.ClosedDate)return!1;var checkOtherDO=document.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;return document.GuidProject?$rootScope.hasDeleteAccess("DocumentXEntity","Project",checkOtherDO):document.GuidWorkOrder?$rootScope.hasDeleteAccess("DocumentXEntity","WorkOrder",checkOtherDO):document.GuidPurchaseOrder?$rootScope.hasDeleteAccess("DocumentXEntity","PurchaseOrder",checkOtherDO):document.GuidDeviation?$rootScope.hasDeleteAccess("DocumentXEntity","Deviation",checkOtherDO):!!document.GuidCondition&&$rootScope.hasDeleteAccess("DocumentXEntity","Condition",checkOtherDO)},$scope.canEditFromProject=function(document){var checkOtherDO=document.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;return document.GuidProject?$rootScope.hasEditAccess("DocumentXEntity","Project",checkOtherDO):document.GuidWorkOrder?$rootScope.hasEditAccess("DocumentXEntity","WorkOrder",checkOtherDO):document.GuidPurchaseOrder?$rootScope.hasEditAccess("DocumentXEntity","PurchaseOrder",checkOtherDO):document.GuidDeviation?$rootScope.hasEditAccess("DocumentXEntity","Deviation",checkOtherDO):!!document.GuidCondition&&$rootScope.hasEditAccess("DocumentXEntity","Condition",checkOtherDO)},$scope.editDocument=function(document){$modal.open({templateUrl:"app/document/views/editDocumentMetadataModal.html",size:"lg",controller:"EditDocumentController",resolve:{$stateParams:function(){return{guid:document.GuidDocument,isModal:!0}}}}).result.then(function(){$scope.projectDocumentsTable.reload(),$scope.isCollapsed=!1},function(reloadTable){reloadTable&&$scope.projectDocumentsTable.reload(),$scope.isCollapsed=!1})},$scope.openDocument=function(document){documentService.openDocument(document.Document).then(function(result){$scope.isCollapsed=!1})};var getMenuLink=function(url,icon,text){return{html:' '+text+"",isHref:!0}};$scope.menuOptions=function(projectDocument){var options=[];return!projectDocument.GuidProject&&$rootScope.userInfo.enableWebNavigation&&(projectDocument.GuidWorkOrder?options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:projectDocument.GuidWorkOrder }),"fa-suitcase",translationService.translate("web-project-open-workorder","Åpne arbeidsordre"))):projectDocument.GuidPurchaseOrder?options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:projectDocument.GuidPurchaseOrder})," fa-cart-shopping",translationService.translate("web-project-open-purchaseorder","Åpne bestilling"))):projectDocument.GuidDeviation?options.push(getMenuLink($rootScope.navigation.href("deviation.edit",{guid:projectDocument.GuidDeviation}),"fa-octagon-exclamation",translationService.translate("web-project-open-deviation","Åpne avvik"))):projectDocument.GuidCondition&&options.push(getMenuLink($rootScope.navigation.href("condition.edit",{guid:projectDocument.GuidCondition}),"fa-plaster",translationService.translate("web-project-open-condition","Åpne tiltak")))),options.push({html:' '+translationService.translate("web-list-document-show","Vis dokument")+"",compile:!0}),$scope.canEditFromProject(projectDocument)&&options.push({html:' '+translationService.translate("web-button-edit","Rediger")+"",compile:!0}),$scope.canDeleteFromProject(projectDocument)&&options.push({html:' '+translationService.translate("web-button-delete","Slett")+"",compile:!0}),options},$scope.$watch("reloadDocumentTable",function(){$scope.reloadDocumentTable&&$scope.projectDocumentsTable.reload()})}angular.module("Plania").directive("projectDocuments",function(){return{restrict:"E",scope:{model:"=ngModel",reloadAlarmLogTable:"=reloadAlarmLogTable",viewMode:"=viewMode",update:"=update",restrictEdit:"=restrictEdit",isModelLoading:"=isModelLoading",reloadDocumentTable:"=reloadDocumentTable"},controller:["$scope","$rootScope","Repository","TranslationService","DocumentService","$modal","ListService","ngTableParams",controller],templateUrl:"app/project/views/projectDocumentsDirective.html"}})}(),function(){function controller($scope,$rootScope,repository,translationService,$modal,autoCompleteService,listService,ngTableParams,$window){if($scope.rootScope=$rootScope,$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.hasVisitedTab="economy"===$scope.currentPage,$scope.search={},$scope.isRestOpen=0!==$scope.model.RestExternalEstimatedAmountAfterOrder&&0!==$scope.model.RestBudgetEstimatedAmount,$scope.model.IsTemplate){$scope.periodicTaskPurchaseOrderItemColumns=[{Position:1,Title:translationService.translate("web-projectTemplate-periodicTask-purchaseOrderItem-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-projectTemplate-periodicTask-purchaseOrderItem-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-projectTemplate-periodicTask-purchaseOrderItem-explanatoryText","Tekst"),Property:"ExplanatoryText",PropertyType:"string"},{Position:4,Title:translationService.translate("web-projectTemplate-periodicTask-purchaseOrderItem-orderedQuantity","Antall"),Property:"OrderedQuantity",PropertyType:"number"},{Position:5,Title:translationService.translate("web-projectTemplate-periodicTask-purchaseOrderItem-unit","Enhet"),Property:"Unit",PropertyType:"string"},{Position:6,Title:translationService.translate("web-projectTemplate-periodicTask-purchaseOrderItem-periodicTaskId","Periodisk Id"),Property:"PeriodicTask.Id",PropertyType:"string"},{Position:7,Title:translationService.translate("web-projectTemplate-periodicTask-purchaseOrderItem-updatedDate","Oppdatert"),Property:"UpdatedDate",PropertyType:"date"}];var periodicTaskPurchaseOrderFilter={PropertyFilter:[{Property:"PeriodicTask.GuidProject",Operator:"=",Value:$scope.model.Guid}]};$scope.periodicTaskPurchaseOrderItemTable=new ngTableParams({page:1,count:50,sorting:{Id:"asc"},filter:periodicTaskPurchaseOrderFilter},{total:0,filterDelay:10,counts:[50,100,150],getData:function($defer,params){var columns=[];$scope.periodicTaskPurchaseOrderItemColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.purchaseOrderItem.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.periodicTaskPurchaseOrderItemTable.settings().total=result.TotalCount,$scope.periodicTaskPurchaseOrderItemTable.settings().filterDelay=500,$defer.resolve(result.List)})}})}else{var purchaseOrderItemFilter={PropertyFilter:[{Property:"WorkOrder.GuidProject",Operator:"=",Value:$scope.model.Guid}]};(function(){var resourceGroupKpi={Prefix:"purchaseOrderItem",FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,PropertyFilter:purchaseOrderItemFilter.PropertyFilter,Properties:[{Property:"OrderedAmount",Function:"sum"}]};repository.createSingle(repository.apiData.kpi.url,resourceGroupKpi).then(function(result){$scope.SumOrderedAmount=result[0].Result[0].Value})})(),$scope.$watch("purchaseOrderItemInfo.listSetup",function(newValue,oldValue){oldValue!==newValue&&$scope.purchaseOrderItemInfo.table&&($scope.purchaseOrderItemInfo.table.$params.sorting=$scope.purchaseOrderItemInfo.listSetup.Sorting,$scope.purchaseOrderItemInfo.listSetup.GroupBy?$scope.purchaseOrderItemInfo.table.settings().groupBy=function(obj){return!!$scope.purchaseOrderItemInfo.listSetup.GroupBy&&($scope.purchaseOrderItemInfo.listSetup.GroupBy.split(".").forEach(function(attr){obj=obj?obj[attr]:""}),obj)}:$scope.purchaseOrderItemInfo.table.settings().groupBy=null,$scope.purchaseOrderItemInfo.table.reload())}),$scope.purchaseOrderItemInfo=new function(){var me=this;this.apiData=repository.apiData.purchaseOrderItem,this.jsPrefix=_.camelCase(this.apiData.prefix),this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:50,sorting:{Id:"desc"},filter:{PropertyFilter:[{Property:"WorkOrder.GuidProject",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[50,100,150],getData:function($defer,params){var columns=[];me.listSetup.Columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(me.apiData.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)})}}))},listService.getWebListViews(null,this.apiData.prefix,!1,null,{}).then(function(result){me.listOptions=result.listOptions,me.listSetup=result.selectedListSetup,$scope.purchaseOrderItemInfo.initTable()})},$scope.$watch("costInfo.listSetup",function(newValue,oldValue){oldValue!==newValue&&$scope.costInfo.table&&($scope.costInfo.table.$params.sorting=$scope.costInfo.listSetup.Sorting,$scope.costInfo.listSetup.GroupBy?$scope.costInfo.table.settings().groupBy=function(obj){return!!$scope.costInfo.listSetup.GroupBy&&($scope.costInfo.listSetup.GroupBy.split(".").forEach(function(attr){obj=obj?obj[attr]:""}),obj)}:$scope.costInfo.table.settings().groupBy=null,$scope.costInfo.table.reload())}),$scope.costInfo=new function(){var me=this;this.apiData=repository.apiData.cost,this.jsPrefix=_.camelCase(this.apiData.prefix),this.canCreate=function(){return!$scope.restrictEdit&&$scope.rootScope.hasCreateAccess(this.apiData.prefix)},this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:50,sorting:{UpdatedDate:"desc"},filter:{PropertyFilter:[{Property:"WorkOrder.GuidProject",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.listSetup.Columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(me.apiData.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))},this.create=function(){if(me.canCreate()){var persistedData={};persistedData.GuidProject=$scope.model.Guid,repository.persistedData.setPersistedData(me.jsPrefix+".create",persistedData),$scope.$parent.navigation.go(me.jsPrefix+".create",{showPersistantData:!0},{reload:!0})}},this.update=function(item,event){$scope.$root.navigation.go("cost.edit",{guid:item.Guid})},listService.getWebListViews(null,this.apiData.prefix,!1,null,{}).then(function(result){me.listOptions=result.listOptions,me.listSetup=result.selectedListSetup,$scope.costInfo.initTable()})}}$scope.updatePurchaseOrderItem=function(purchaseOrderItem){$modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"xl",resolve:{params:function(){return{Guid:purchaseOrderItem.Guid}}}}).result.then(function(result){$scope.model.EstimatedCost=$scope.model.EstimatedCost?$scope.model.EstimatedCost+result.estimatedCost-purchaseOrderItem.UnitPrice*purchaseOrderItem.OrderedQuantity:result.estimatedCost,$scope.purchaseOrderItemInfo.table.reload()},function(){})};var getMenuLink=function(url,icon,text){return{html:' '+text+"",isHref:!0}};$scope.menuOptions=function(purchaseOrderItem){var options=[];return $rootScope.hasEditAccess("PurchaseOrderItem")&&options.push({html:' '+translationService.translate("web-project-purchaseOrderItem-edit","Rediger konteringsobjekt")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.updatePurchaseOrderItem(purchaseOrderItem)}}),purchaseOrderItem.GuidPurchaseOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:purchaseOrderItem.GuidPurchaseOrder})," fa-cart-shopping",translationService.translate("web-project-open-purchaseorder","Åpne bestilling"))),purchaseOrderItem.GuidWorkOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:purchaseOrderItem.GuidWorkOrder}),"fa-suitcase",translationService.translate("web-project-open-workorder","Åpne arbeidsordre"))),purchaseOrderItem.GuidPeriodicTask&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:purchaseOrderItem.GuidPeriodicTask}),"fa-calendar-note",translationService.translate("web-project-open-periodicTask","Åpne periodisk rutine"))),$scope.rootScope.hasCreateAccess("Cost")&&"Proposal"!==purchaseOrderItem.Status&&"Closed"!==purchaseOrderItem.Status&&options.push({html:' '+translationService.translate("web-workorder-purchaseorderitem-createCost","Legg til kostnad")+"",click:function($itemScope,$event,modelValue,text,$li){var persistedData={};persistedData.GuidPurchaseOrderItem=purchaseOrderItem.Guid,repository.persistedData.setPersistedData("cost.create",persistedData),$scope.$parent.navigation.go("cost.create",{showPersistantData:!0},{reload:!0})}}),options};var loadingListener=$scope.$watchGroup(["isModelLoading"],function(){!1===$scope.isModelLoading&&($scope.telerikInfo.updateTelerikParameters(),loadingListener())},!0);$scope.$watch("currentPage",function(newVal,oldVal){newVal!==oldVal&&"economy"===newVal&&($scope.telerikInfo.reloadReports=!$scope.telerikInfo.reloadReports,$scope.hasVisitedTab=!0)}),$scope.telerikInfo=new function(){this.parameters={GuidProject:$scope.model.Guid},this.displayReports=!1,this.endDate=new Date,this.reloadReports=!1,this.updateTelerikParameters=function(){if(!$scope.model.IsTemplate){var endDate=$scope.model.EndDate?new Date($scope.model.EndDate):null,startDate=$scope.model.StartDate?new Date($scope.model.StartDate):new Date;null!==endDate&&void 0!==endDate||(endDate=$scope.telerikInfo.endDate),endDate.getTime()0&&$scope.model.ProjectStatus&&$scope.model.ProjectStatus.ProjectPhase){var projectPhase=_.find($scope.projectPhases,function(o){return o.Guid===$scope.model.ProjectStatus.ProjectPhase.Guid});$scope.projectPhaseStatuses=projectPhase?angular.copy(projectPhase.ProjectStatuses):null}};repository.GetPaginated(repository.apiData.projectPhase.url,-1,-1,{IndexPosition:"asc"},{PropertyFilter:[{Property:"GuidProject",Operator:"=",Value:$scope.model.Guid}]},"",JSON.stringify(["Id","IndexPosition"])).then(function(result){$scope.projectPhases=result.List,setProjectPhaseStatuses()}),$scope.onProjectCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidProjectCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidProjectCategory=category.Guid},$scope.setProjectPhase=function(phase){$scope.model.ProjectStatus&&$scope.model.ProjectStatus.ProjectPhase&&$scope.model.ProjectStatus.ProjectPhase.Guid===phase.Guid||($scope.model.GuidProjectStatus=phase.ProjectStatuses[0].Guid,$scope.model.ProjectStatus=phase.ProjectStatuses[0],$scope.model.ProjectStatus.ProjectPhase=phase,$scope.projectPhaseStatuses=angular.copy(phase.ProjectStatuses),delete $scope.model.ProjectStatus.ProjectPhase.ProjectStatuses,$scope.update())};var updateProjectStatus=function(status){status.ProjectPhase=$scope.model.ProjectStatus.ProjectPhase,$scope.model.GuidProjectStatus=status.Guid,"Closed"!==status.Stage||$scope.model.ProjectStatus&&"Closed"===$scope.model.ProjectStatus.Stage||($scope.model.IsClosing=!0),$scope.model.ProjectStatus=status,$scope.update($scope.model.IsTemplate?"projectTemplate.edit":"project.edit")};$scope.setProjectStatus=function(status){if(status.Guid!==$scope.model.GuidProjectStatus)return"Closed"===status.Stage?void swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-project-stage-close","Handlingen vil validere om prosjektet er lovlig å lukkes, evtl. aktive, men fullførte arbeidsordre vil sendes til historikk. Et lukket prosjekt kan ikke gjenåpnes. Ønsker du å fortsette?"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-project-stage-close-confirm","Ja, lukk prosjektet"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){updateProjectStatus(status)}):void updateProjectStatus(status)},$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var updateDateProgress=function(){var dateProgress={start:new Date($scope.model.StartDate).getTime(),now:(new Date).getTime(),end:new Date($scope.model.EndDate).getTime(),color:"blue",progress:0};try{dateProgress.now>dateProgress.end&&(dateProgress.now=dateProgress.end),dateProgress.progress=100*(dateProgress.now-dateProgress.start)/(dateProgress.end-dateProgress.start),dateProgress.progress<0&&(dateProgress.progress=0),dateProgress.progress>100&&(dateProgress.progress=100)}catch(ex){}$scope.model&&($scope.model.ClosedDate?dateProgress.color="green":dateProgress.now>dateProgress.end?dateProgress.color="red":dateProgress.progress>100*$scope.model.AverageCompletionRate?dateProgress.color="red":dateProgress.progress<=100*$scope.model.AverageCompletionRate&&(dateProgress.color="green")),$scope.dateProgress=dateProgress};updateDateProgress(),$scope.GetEstimateType=function(real,estimate){if(!real||!estimate)return"success";var factor=real/estimate;return factor>1?"danger":factor>.9?"warning":"success"},$scope.getProgressType=function(percent){var type="primary";return percent<10?type="danger":percent<50?type="warning":percent<100?type="info":100===percent&&(type="success"),type},$scope.getRiskFactorColor=function(value){switch(value){case"Green":return"btn-success";case"Yellow":return"btn-warning";case"Red":return"btn-danger"}return"btn-success"},$scope.riskSelectOptions=[{text:translationService.translate("web-enum-ProjectRiskFactor-green","Lav"),value:"Green"},{text:translationService.translate("web-enum-ProjectRiskFactor-yellow","Middels"),value:"Yellow"},{text:translationService.translate("web-enum-ProjectRiskFactor-red","Høy"),value:"Red"}],$scope.updateRisk=function(riskType){var riskFactorProperty=riskType+"Factor",riskFactorCommentProperty=riskType+"FactorComment";$scope.currentRisk={value:$scope.model[riskFactorProperty],comment:$scope.model[riskFactorCommentProperty],riskType:riskType},$modal.open({templateUrl:"app/project/views/projectRiskModal.html",scope:$scope}).result.then(function(riskToSave){$scope.model[riskFactorProperty]=riskToSave.value,$scope.model[riskFactorCommentProperty]=riskToSave.comment,$scope.update()},function(){})},$scope.selectPerson=function(personProperty,guidProperty){$modal.open({templateUrl:"app/common/views/tableModal.html",controller:"TableModalController",resolve:{content:function(){return{header:translationService.translate("web-lookup-title","Oppslagsliste"),idTitle:translationService.translate("autocomplete-lookup-header-person","Navn"),data:autoCompleteService.persons,params:{},singleValue:!0}}}}).result.then(function(selected){$scope.model[personProperty]=selected.object,$scope.model[guidProperty]=selected.guid,$scope.update()},function(){})},$scope.removePerson=function(personProperty,guidProperty){delete $scope.model[guidProperty],delete $scope.model[personProperty],$scope.update()},function(){var totalWorkOrderKpi=(new Date(0).toISOString(),$scope.model.Guid,{Prefix:"WorkOrder",FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,PropertyFilter:[{Property:"GuidProject",Operator:"=",Value:$scope.model.Guid}],Properties:[{Property:"EndDate",Function:"count"},{Property:"CompletionRate",Function:"average"}]}),completedWorkOrdersCount={Prefix:"WorkOrder",FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,PropertyFilter:[{Property:"GuidProject",Operator:"=",Value:$scope.model.Guid},{Property:"EndDate",Operator:"<>",Value:null}],Properties:[{Property:"EndDate",Function:"count"}]},hoursSum={Prefix:"WorkOrder",FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,PropertyFilter:[{Property:"GuidProject",Operator:"=",Value:$scope.model.Guid}],Properties:[{Property:"EstimatedTime",Function:"sum"},{Property:"RealTime",Function:"sum"},{Property:"EstimatedCost",Function:"sum"},{Property:"RealCost",Function:"sum"}]};repository.createSingle(repository.apiData.kpi.url,hoursSum).then(function(result){$scope.sumEstimatedtime=Number(result[0].Result[0].Value),$scope.sumRealTime=Number(result[0].Result[1].Value),$scope.sumEstimatedCost=Number(result[0].Result[2].Value),$scope.sumRealCost=Number(result[0].Result[3].Value),$scope.maxTime=$scope.sumEstimatedtime>$scope.sumRealTime?$scope.sumEstimatedtime:$scope.sumRealTime,0===$scope.maxTime&&($scope.maxTime=100),$scope.maxCost=$scope.sumEstimatedCost>$scope.sumRealCost?$scope.sumEstimatedCost:$scope.sumRealCost,0===$scope.maxCost&&($scope.maxCost=100)}),repository.createSingle(repository.apiData.kpi.url,totalWorkOrderKpi).then(function(result){$scope.totalWorkOrders=result[0].Result[0].Value,$scope.totalAverageCompletionPercent=Number((100*result[0].Result[1].Value).toFixed(2))}),repository.createSingle(repository.apiData.kpi.url,completedWorkOrdersCount).then(function(result){$scope.completedWorkOrders=result[0].Result[0].Value})}(),$scope.onEstateSelect=function(estate){if(!estate)return void($scope.model.GuidEstate="");$scope.model.GuidEstate!==estate.Guid&&($scope.model.GuidBuilding="",$scope.model.Building="",$scope.model.GuidArea="",$scope.model.Area=""),$scope.model.GuidEstate=estate.Guid},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidArea="",$scope.model.Area=""),$scope.model.GuidBuilding=building.Guid,$scope.model.GuidEstate&&""!==$scope.model.GuidEstate&&$scope.model.GuidEstate===building.GuidEstate||($scope.model.GuidEstate=building.GuidEstate,$scope.model.Estate={Caption:building.Estate.Id+" - "+building.Estate.Description}),building.CostCenter&&($scope.model.CostCenter={Caption:building.CostCenter.Caption},$scope.model.GuidCostCenter=building.GuidCostCenter)},$scope.onAreaSelect=function(area){if(!area)return void($scope.model.GuidArea="");$scope.model.GuidArea=area.Guid,$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=area.GuidBuilding,$scope.model.Building={Caption:area.Building.Id+" - "+area.Building.Description}),$scope.model.GuidEstate&&""!==$scope.model.GuidEstate||($scope.model.GuidEstate=area.GuidEstate||area.Building.Estate.Guid,$scope.model.Estate={Caption:area.Building.Estate.Id+" - "+area.Building.Estate.Description})},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"estate":return filter;case"building":if($scope.model.IsTemplate)return{};if($scope.model.GuidEstate){var estateFieldRule=_.filter($scope.fieldRules,function(o){return"GuidEstate"===o.FieldName});if(1===estateFieldRule.length&&estateFieldRule[0].Hidden)return filter;filter.PropertyFilter=[{Property:"GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]}return filter;case"area":return filter={GuidBuilding:$scope.model.GuidBuilding},$scope.model.GuidEstate&&(filter.PropertyFilter=[{Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]),filter;case"person":case"customer":return filter;case"supplier":return filter.PropertyFilter=[{Property:"IsDeactivated",Operator:"=",Value:"false"}],filter;case"projectCategory":return filter.PropertyFilter=[{Property:"IsAbstract",Operator:"=",Value:!1}],filter}},$scope.images=[],$scope.uploadImage=function(images){images.length<1||$modal.open({templateUrl:"app/common/views/imageUploadModal.html",controller:"ImageUploadModalController",size:"lg",resolve:{params:function(){return{image:images[0],targetSize:1040,areaType:"rectangle"}}}}).result.then(function(croppedImage){function handleFileUpload(file){var reader=new FileReader;reader.onload=function(e){var newFile={ImageSrc:e.target.result.substr(e.target.result.indexOf("base64,")+"base64,".length),Name:file.name,GuidProject:$scope.model.Guid,size:file.size};files.push(newFile),onLoadEndHandler()},reader.readAsDataURL(file)}function onLoadEndHandler(image){files.forEach(function(file){$scope.images.push(file)}),$scope.model.Images.length>0?(repository.deleteSingle(repository.apiData.image.url,$scope.model.Images[0].Guid).then(function(result){saveImages()}),$scope.model.Images=[]):saveImages()}var files=[];handleFileUpload(croppedImage)})};var saveImages=function(){if(!$scope.images||$scope.images.length<1)return void $rootScope.goBack("project.edit",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid});repository.createMultiple(repository.apiData.image.url,$scope.images).then(function(result){repository.growl("Prosjekt har blitt opprettet","success"),repository.commonService.setLastRegisterGuid("project.edit",$scope.model.Guid),$rootScope.goBack("project.edit",{guid:$scope.model.Guid,menuGuid:$rootScope.navigation.params.menuGuid})},function(error){repository.growl(error,"danger")})};$scope.$watch("isModelLoading",function(newVal){!1===newVal&&($scope.model.ClosedDate?$scope.canChangePhase=!1:$scope.canChangePhase=$rootScope.userInfo.guidPerson===$scope.model.GuidManagerPerson||$rootScope.userInfo.guidPerson===$scope.model.GuidOwnerPerson||$rootScope.userInfo.isSystemAdministrator||$rootScope.userInfo.isProjectAdministrator,updateDateProgress(),setProjectPhaseStatuses())}),$scope.$watch("currentPage",function(newVal,oldVal){newVal!==oldVal&&"info"===newVal&&($scope.telerikInfo.reloadReports=!$scope.telerikInfo.reloadReports,$scope.hasVisitedTab=!0)}),$scope.telerikInfo=new function(){this.parameters={GuidProject:$scope.model.Guid},this.displayReports=!1,this.endDate=new Date,this.reloadReports=!1,this.updateTelerikParameters=function(){if(!$scope.model.IsTemplate){var endDate=$scope.model.EndDate?new Date($scope.model.EndDate):null,startDate=$scope.model.StartDate?new Date($scope.model.StartDate):new Date;null!==endDate&&void 0!==endDate||(endDate=$scope.telerikInfo.endDate),endDate.getTime()0){var first=result.List[0];$scope.project=first.Project}}),$scope.selectedItem={},$scope.clickAction=function(item,phase){"ProjectStatus"===item.Prefix&&($scope.activePhase=phase),$scope.selectedItem=item},$scope.treeOptions={accept:function(sourceNodeScope,destNodeScope,destIndex){return destNodeScope.$modelValue.some(function(s){return s.Guid===sourceNodeScope.$modelValue.Guid})}},$scope.IsActivePhase=function(phase){return phase.ProjectStatuses.some(function(status){return status.Guid===$scope.project.GuidProjectStatus})},$scope.copyPhase=function(phase){var newPhase=angular.copy(phase);newPhase.IndexPosition=$scope.ProjectPhases.length,delete newPhase.Guid,newPhase.ProjectStatuses.forEach(function(status){delete status.Guid}),$scope.ProjectPhases.push(newPhase)},$scope.addPhase=function(){var maxPosition=0;$scope.ProjectPhases&&$scope.ProjectPhases.length&&(maxPosition=_.max($scope.ProjectPhases,function(phase){return phase.IndexPosition})),$scope.selectedItem={Id:"",Description:"",Prefix:"ProjectPhase",ProjectStatuses:[],IndexPosition:++maxPosition,isNew:!0}},$scope.updateRemovedStatus=function(item){if("ProjectStatus"===item.Prefix&&$scope.activePhase.removed)return void(item.removed=!0);item.removed?item.removed=!1:item.removed=!0,"ProjectPhase"===item.Prefix&&item.ProjectStatuses.forEach(function(status){status.removed=item.removed})},$scope.addStatus=function(phase){var maxPosition=0;$scope.ProjectStatuses&&$scope.ProjectStatuses.length&&(maxPosition=_.max($scope.ProjectStatuses,function(status){return status.IndexPosition})),$scope.selectedItem={Id:"",Description:"",Stage:"Active",Prefix:"ProjectStatus",IndexPosition:++maxPosition,isNew:!0,phase:phase}},$scope.saveNewItem=function(){"ProjectStatus"===$scope.selectedItem.Prefix&&($scope.selectedItem.phase.ProjectStatuses.push($scope.selectedItem),$scope.selectedItem.isNew=!1,delete $scope.selectedItem.phase),"ProjectPhase"===$scope.selectedItem.Prefix&&($scope.ProjectPhases.push($scope.selectedItem),$scope.selectedItem.isNew=!1)},$scope.savePhaseSetup=function(destination){_.remove($scope.ProjectPhases,function(phase){return phase.removed});for(var indexPosition=0,i=0;i<$scope.ProjectPhases.length;i++){var phase=$scope.ProjectPhases[i];if(!phase.removed){phase.IndexPosition=indexPosition++;var statusIndexPosition=0;_.remove(phase.ProjectStatuses,function(status){return status.removed});for(var j=0;j1)return void swal("Ingen valg",translationService.translate("web-project-progrss-copyWorkOrder-toomanyselected","Du kan kun kopiere én arbeidsordre om gangen."),"error");guidWorkOrder=$scope.selectedWorkOrders[0]}repository.persistedData.setPersistedData("workOrder.create",{model:{DueDate:$scope.model.EndDate},guidEstate:$scope.model.Estate?$scope.model.Estate.Guid:null,estate:$scope.model.Estate?$scope.model.Estate.Caption:null,guidBuilding:$scope.model.GuidBuilding,building:$scope.model.Building?$scope.model.Building.Caption:null,guidArea:$scope.model.GuidArea,area:$scope.model.Area?$scope.model.Area.Caption:null,guidEquipment:$scope.model.GuidEquipment,equipment:$scope.model.Equipment?$scope.model.Equipment.Caption:null,guidProject:$scope.model.Guid,project:$scope.model.Caption}),$rootScope.navigation.go("workOrder.create",{guidEntityToCopy:guidWorkOrder,showPersistantData:!0},{reload:!0})},$scope.moveWorkOrders=function(){if($scope.isProjectAdministrator)if($scope.selectedWorkOrders&&0!==$scope.selectedWorkOrders.length){var filter={FilterModel:{Condition:"and",Rules:[{Property:"ClosedDate",Operator:"=",value:null},{Property:"IsTemplate",Operator:"=",value:0},{Property:"Guid",Operator:"<>",value:$scope.model.Guid}]}};user.isSystemAdministrator||user.isProjectAdministrator||filter.FilterModel.Rules.push({Condition:"or",Rules:[{Property:"GuidOwnerPerson",Operator:"=",value:user.guidPerson},{Property:"GuidManagerPerson",Operator:"=",value:user.guidPerson}]}),verifyWithUser().then(function(){$modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:translationService.translate("web-workOrder-connect-project","Velg prosjekt å koble arbeidsordrene til"),url:repository.apiData.project.url,sorting:{CreationDate:"desc"},filter:filter,columns:[{Title:translationService.translate("web-project-Id","Prosjekt Nr"),Property:"Id"},{Title:translationService.translate("web-project-Description","Beskrivelse"),Property:"Description"},{Title:translationService.translate("web-project-Building-Id","Bygg Id"),Property:"Building.Id"},{Title:translationService.translate("web-project-Building-Description","Byggbeskrivelse"),Property:"Building.Description"}]}}}}).result.then(function(selectedEntity){repository.updateMultipleWithGuid(repository.apiData.project.endpoint.addWorkOrders,selectedEntity.Guid,$scope.selectedWorkOrders).then(function(result){repository.growl(translationService.translate("web-project-connect-workOrder-success","Arbeidsordrene har blitt koblet til prosjektet"),"success"),$scope.workOrderTable.reload()},function(error){swal(translationService.translate("web-project-connectWorkOrders-error-title","En eller flere feiler oppstod under kobling til prosjekt"),error,"error"),$scope.workOrderTable.reload()})})})}else swal("Ingen valg",translationService.translate("web-list-connectProject-edit-missingSelect","Ingen valg. Velg en eller flere rader fra listen for å koble til prosjekt"),"error")},$scope.connectWorkOrders=function(){if($scope.isProjectAdministrator){var filter={FilterModel:{Condition:"and",Rules:[{Property:"GuidProject",Value:$scope.model.Guid,Operator:"<>"},{Property:"Stage",Value:2,Operator:"<>"}]},ActivityStatus:"Undefined"};user.isSystemAdministrator||user.isProjectAdministrator||filter.FilterModel.Rules.push({Condition:"or",Rules:[{Property:"GuidProject",Value:null,Operator:"="},{Property:"Project.GuidOwnerPerson",Operator:"=",value:user.guidPerson},{Property:"Project.GuidManagerPerson",Operator:"=",value:user.guidPerson}]}),verifyWithUser().then(function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:"Velg arbeidsordrer",columns:[{Title:translationService.translate("web-workOrder-id","AO Nr"),Property:"Id"},{Title:translationService.translate("web-workOrder-description","Ao Beskrivelse"),Property:"Description"},{Title:translationService.translate("web-workOrder-Building-Id","Bygg Id"),Property:"Building.Id"},{Title:translationService.translate("web-workOrder-Building-Description","Byggbeskrivelse"),Property:"Building.Description"},{Title:translationService.translate("web-workOrder-Project-Id","Prosjekt Id"),Property:"Project.Id"},{Title:translationService.translate("web-workOrder-Project-Description","Prosjektbeskrivelse"),Property:"Project.Description"}],url:repository.apiData.workOrder.url,sorting:{Id:"desc"},filter:filter}}}}).result.then(function(selectedEntities){repository.updateMultipleWithGuid(repository.apiData.project.endpoint.addWorkOrders,$scope.model.Guid,selectedEntities).then(function(result){repository.growl(translationService.translate("web-project-connect-workOrder-success","Arbeidsordrene har blitt koblet til prosjektet"),"success"),$scope.workOrderTable.reload()},function(error){swal(translationService.translate("web-project-connectWorkOrders-error-title","En eller flere feiler oppstod under kobling til prosjekt"),error,"error"),$scope.workOrderTable.reload()})})})}},$scope.disconnectWorkOrders=function(){if($scope.isProjectAdministrator)return $scope.selectedWorkOrders&&0!==$scope.selectedWorkOrders.length?void verifyWithUser().then(function(){repository.updateMultipleWithGuid(repository.apiData.project.endpoint.removeWorkOrders,$scope.model.Guid,$scope.selectedWorkOrders).then(function(result){repository.growl(translationService.translate("web-project-disconnect-workOrder-success","Arbeidsordrene har blitt koblet fra prosjektet"),"success"),$scope.workOrderTable.reload()},function(error){swal(translationService.translate("web-project-connectWorkOrders-error-title","En eller flere feiler oppstod under kobling til prosjekt"),error,"error"),$scope.workOrderTable.reload()})}):void swal("Ingen valg",translationService.translate("list-noselectedrows","Ingen valg. Velg en eller flere rader fra listen for å utføre handlingen"),"error")},$scope.updateCompletionRate=function(workOrder){if("History"!==workOrder.Stage&&!$scope.model.ClosedDate){var updateCompletionRate=function(){repository.runAction(repository.apiData.workOrder.endpoint.setCompletionRate+workOrder.Guid,null,"completionRate="+workOrder.CompletionRate/100).then(function(result){repository.growl(translationService.translate("web-project-workorder-completionrateupdated","Arbeidsordren ble oppdatert"),"success"),workOrder.showEditDialog=!1,$scope.workOrderTable.reload(),getKpis()}).catch(errorCallback)},errorCallback=function(error){error&&workOrderService.isWorkOrderStage0(error)?workOrderService.shouldActivateWorkOrder(workOrder.Guid,error).then(function(result){updateCompletionRate()},function(error){error&&repository.growl(error)}):repository.growl(error.Message||error,"danger")};updateCompletionRate()}};var originalPercent=0;if($scope.showWorkOrderEditDialog=function(guid){var workOrders=[];$scope.workOrderSetting.workOrderListSetup.GroupBy?$scope.workOrderTable.data.forEach(function(grp){grp&&grp.data&&grp.data.forEach(function(d){workOrders.push(d)})}):workOrders=$scope.workOrderTable.data,workOrders.forEach(function(workOrder){!workOrder.EndDate&&$rootScope.hasEditAccess("WorkOrder")&&("History"===workOrder.Stage||$scope.model.ClosedDate||(workOrder.Guid===guid?(workOrder.showEditDialog=!0,originalPercent=angular.copy(workOrder.CompletionRate)):workOrder.showEditDialog=!1))})},$scope.cancelEditDialog=function(workOrder){workOrder.CompletionRate=originalPercent,originalPercent=0,workOrder.showEditDialog=!1},$scope.selectedWorkOrders=[],$scope.allWorkOrdersSelected=!1,$scope.activateWorkOrders=function(guid){return!$scope.model.ClosedDate&&(guid||$scope.selectedWorkOrders&&0!==$scope.selectedWorkOrders.length?void workOrderService.activateWorkOrders(guid?[guid]:$scope.selectedWorkOrders).then(function(result){$scope.workOrderTable.reload(),repository.growl(translationService.translate("web-workorder-activate-success","Arbeidsordren er aktivert"),"success")}).catch(function(error){repository.growl(error,"danger")}):void swal("Ingen valg",translationService.translate("list-noselectedrows","Ingen valg. Velg en eller flere rader fra listen for å utføre handlingen"),"error"))},listService.getWebListViews(null,repository.apiData.workOrder.prefix,!1,null,{}).then(function(result){$scope.workOrderSetting.workOrderListOptions=result.listOptions,$scope.workOrderSetting.workOrderListSetup=result.selectedListSetup;var filter={PropertyFilter:[{Property:"GuidProject",Operator:"=",Value:$scope.model.Guid}]};$scope.workOrderTable=new ngTableParams({page:1,count:-1,sorting:{Id:"desc"},filter:filter},{total:0,filterDelay:10,counts:[],getData:function($defer,params){var columns=[];$scope.workOrderSetting.workOrderListSetup.Columns.forEach(function(col){columns.push(col.Property)});var filter=angular.copy(params.filter()),propertyFilter=filter.PropertyFilter;propertyFilter&&_.remove(propertyFilter,function(obj){return"Stage"===obj.Property}),filter.PropertyFilter=propertyFilter,filter.ActivityStatus="Undefined",filter.Stages=[],$scope.workOrderFilters.active&&filter.Stages.push("Active"),$scope.workOrderFilters.project&&filter.Stages.push("Project"),$scope.workOrderFilters.history&&filter.Stages.push("History"),_.some(columns,"CompletionRate")||columns.push("CompletionRate"),_.some(columns,"Stage")||columns.push("Stage"),repository.GetPaginated(repository.apiData.workOrder.url,params.page()-1,-1,params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){$scope.workOrderTable.settings().total=result.TotalCount,$scope.workOrderTable.settings().filterDelay=500,$scope.averageCompletionPercent=0,result.List.forEach(function(workOrder){workOrder.CompletionRate=Number((100*workOrder.CompletionRate).toFixed(0)),$scope.averageCompletionPercent+=workOrder.CompletionRate}),$scope.averageCompletionPercent=$scope.averageCompletionPercent/result.List.length;var dates=result.List.filter(function(row){return row.DueDate}).map(function(row){return row.DueDate?new Date(row.DueDate):new Date});if(dates.length>0){var latestRegisteredDate=new Date(Math.max.apply(null,dates));latestRegisteredDate.getTime()>$scope.telerikInfo.endDate.getTime()&&($scope.telerikInfo.endDate=latestRegisteredDate)}$scope.isWorkOrderTableLoading=!1,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})}),$scope.model.IsTemplate){$scope.periodicTaskColumns=[{Position:1,Title:translationService.translate("web-projectTemplate-periodicTask-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-projectTemplate-periodicTask-description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-projectTemplate-periodicTask-resourceGroup-Id","Ressurs Id"),Property:"ResourceGroup.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-projectTemplate-periodicTask-department-Id","Avdeling Id"),Property:"Department.Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-projectTemplate-periodicTask-activityCategory-Description","Kategori"),Property:"ActivityCategory.Description",PropertyType:"string"},{Position:6,Title:translationService.translate("web-projectTemplate-periodicTask-activityCategory-NbPurchaseOrderItem","Bestillingsobjekter"),Property:"NbPurchaseOrderItem",PropertyType:"bool"}];var periodicTaskFilter={IncludeOnProject:!0,PropertyFilter:[{Property:"GuidProject",Operator:"=",Value:$scope.model.Guid}],PeriodicTaskTemplateType:"WorkOrderTemplate"};$scope.periodicTaskTable=new ngTableParams({page:1,count:10,sorting:{Description:"asc"},filter:periodicTaskFilter},{total:0,filterDelay:10,counts:[10,20,30],getData:function($defer,params){var columns=[];$scope.periodicTaskColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.periodicTask.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.periodicTaskTable.settings().total=result.TotalCount,$scope.periodicTaskTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.createPeriodicTask=function(){repository.persistedData.setPersistedData("periodicTask.create",{model:{DueDate:$scope.model.EndDate},guidProject:$scope.model.Guid,project:$scope.model.Caption}),$rootScope.navigation.go("workOrderTemplate.create",{showPersistantData:!0},{reload:!0})}}$scope.selectAllRows=function(table,selectedList,allSelectedProperty){$scope[allSelectedProperty]?(table.data.forEach(function(row){var index=_.findIndex(selectedList,function(o){return o===row.Guid});selectedList.splice(index,1)}),$scope[allSelectedProperty]=!1):(table.data.forEach(function(row){_.contains(selectedList,row.Guid)||selectedList.push(row.Guid)}),$scope[allSelectedProperty]=!0)},$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.itemIsSelected=function(guid,selectedList){return _.contains(selectedList,guid)},$scope.selectItem=function(guid,selectedList){if(_.contains(selectedList,guid)){for(var i=0;i '+text+"",isHref:!0}};$scope.menuOptions=function(workOrder){var options=[];return options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:workOrder.Guid}),"fa-suitcase",translationService.translate("web-open-workorder","Åpne arbeidsordre"))),$scope.rootScope.hasCreateAccess("WorkOrder")&&options.push({html:' '+translationService.translate("web-project-workOrderContextMenu-copy","Kopier arbeidsordre")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.copyWorkOrder(workOrder.Guid)}}),options.push({html:' '+translationService.translate("print-tooltip-details","Print detaljer")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.selectItem(workOrder.Guid,$scope.selectedWorkOrders),$timeout(function(){angular.element("#printWorkOrderDetails a").triggerHandler("click"),$scope.selectItem(workOrder.Guid,$scope.selectedWorkOrders)},0)}}),"Project"!==workOrder.Stage||$scope.model.IsTemplate||$scope.model.ClosedDate||options.push({html:' '+translationService.translate("web-workorder-list-activateWorkOrders","Aktiver arbeidsordre")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.activateWorkOrders(workOrder.Guid)}}),"Project"!==workOrder.Stage&&$scope.rootScope.hasCreateAccess("Cost")&&"Proposal"!==workOrder.Status&&"Closed"!==workOrder.Status&&options.push({html:' '+translationService.translate("web-workorder-purchaseorderitem-createCost","Legg til kostnad")+"",click:function($itemScope,$event,modelValue,text,$li){var persistedData={};persistedData.GuidWorkOrder=workOrder.Guid,repository.persistedData.setPersistedData("cost.create",persistedData),$scope.$parent.navigation.go("cost.create",{showPersistantData:!0},{reload:!0})}}),options}}angular.module("Plania").directive("projectProgress",function(){return{restrict:"E",scope:{model:"=ngModel",viewMode:"=viewMode",update:"=update",restrictEdit:"=restrictEdit",isModelLoading:"=isModelLoading",currentPage:"=currentPage"},controller:["$scope","$rootScope","Repository","TranslationService","ListService","ngTableParams","$modal","$timeout","WorkOrderService","$q",controller],templateUrl:"app/project/views/projectProgressDirective.html"}})}(),function(){function controller($scope,commonService,$localStorage,$rootScope,$window,$timeout){$scope.sharedController={};var hasResized=!1;$scope.refreshReport=function(){$scope.sharedController.refresh()},$scope.toggleReportFilters=function(){$scope.sharedController.toggleFilters()},$scope.toggleZoomMode=function(){$scope.sharedController.toggleZoomMode()},$scope.printLabel=function(){var params=$scope.reportParams;$localStorage.reportParams=JSON.stringify(params);var reportName=$scope.reportName,url=$rootScope.navigation.href("report.print",{reportName:reportName,reportParams:JSON.stringify(params)});$window.open(url,"_blank")};var onResize=function(){$scope.active||(hasResized=!0)};angular.element($window).on("resize",onResize),$scope.$on("$destroy",function(){angular.element($window).off("resize",onResize)}),$scope.$watch("reload",function(newVal,oldVal){newVal!==oldVal&&$timeout(function(){if($scope.sharedController.getReportId){kendo.resize($("#"+$scope.sharedController.getReportId()));$("#"+$scope.sharedController.getReportId()+' .trv-report-page[style*="width"]')[0]&&!hasResized||($scope.refreshReport(),$scope.reportReloaded=!0,hasResized=!1)}},200)})}angular.module("Plania").directive("projectReportDirective",function(){return{restrict:"E",scope:{reportParams:"=",reportName:"=",reload:"=",active:"="},controller:["$scope","CommonService","$localStorage","$rootScope","$window","$timeout",controller],templateUrl:"app/project/views/projectReportDirective.html"}})}(),function(){function controller($scope,$rootScope,repository,translationService,$modal,autoCompleteService,listService,ngTableParams,$localStorage,registeredFieldService){$scope.rootScope=$rootScope,$scope.hasVisitedTab="resource"===$scope.currentPage,registeredFieldService.getRegisteredField(repository.commonService.prefix.WorkOrderXResourceGroup).then(function(registeredFields){var isExternalUser=$localStorage.userData.isExternalUser,estimatedTimeRule=_.filter(registeredFields,{DomainFieldName:"EstimatedTime"})[0],realTimeRule=_.filter(registeredFields,{DomainFieldName:"RealTime"})[0],estimatedCostRule=_.filter(registeredFields,{DomainFieldName:"EstimatedCost"})[0],realCostRule=_.filter(registeredFields,{DomainFieldName:"RealCost"})[0],noteRule=_.filter(registeredFields,{DomainFieldName:"Note"})[0];$scope.resourceGroupInfo.TimeAndCostVisibility={showEstimatedTime:!estimatedTimeRule.Hidden&&(!isExternalUser||!estimatedTimeRule.ExternallyHidden),showRealTime:!realTimeRule.Hidden&&(!isExternalUser||!realTimeRule.ExternallyHidden),showEstimatedCost:!estimatedCostRule.Hidden&&(!isExternalUser||!estimatedCostRule.ExternallyHidden),showRealCost:!realCostRule.Hidden&&(!isExternalUser||!realCostRule.ExternallyHidden),showNote:!noteRule.Hidden&&(!isExternalUser||!noteRule.ExternallyHidden)},$scope.resourceGroupInfo.initTable()}),function(){var resourceGroupKpi={Prefix:"WorkOrderXResourceGroup",FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,PropertyFilter:[{Property:"WorkOrder.GuidProject",Operator:"=",Value:$scope.model.Guid}],Properties:[{Property:"EstimatedCost",Function:"sum"},{Property:"EstimatedTime",Function:"sum"},{Property:"RealCost",Function:"sum"},{Property:"RealTime",Function:"sum"}]};repository.createSingle(repository.apiData.kpi.url,resourceGroupKpi).then(function(result){$scope.sumEstimatedCost=result[0].Result[0].Value,$scope.sumEstimatedTime=result[0].Result[1].Value,$scope.sumRealCost=result[0].Result[2].Value,$scope.sumRealTime=result[0].Result[3].Value})}(),$scope.resourceGroupInfo=new function(){var me=this;this.isLoading=!0,this.search={},this.menuOptions=function(resourceGroup){var options=[];return $scope.model.IsTemplate?options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:resourceGroup.GuidPeriodicTask}),"fa-suitcase",translationService.translate("web-open-project-template-workorder","Åpne arbeidsordre mal"))):options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:resourceGroup.GuidWorkOrder}),"fa-suitcase",translationService.translate("web-open-workorder","Åpne arbeidsordre"))),options};var setColumns=function(){$scope.model.IsTemplate?(me.columns=[{Position:1,Title:translationService.translate("web-project-hour-resourcegroup-Caption","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-project-hour-estimatedTime","Estimert tid"),Property:"EstimatedTime",PropertyType:"double"},{Position:3,Title:translationService.translate("web-project-hour-updatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}],me.sorting={"ResourceGroup.Caption":"asc"}):(me.columns=[{Position:1,Title:translationService.translate("web-project-hour-workOrder-Id","AO Id"),Property:"WorkOrder.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-project-hour-resourcegroup-Caption","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-project-hour-person-caption","Person"),Property:"Person.FirstName",PropertyType:"string"}],me.TimeAndCostVisibility.showEstimatedTime&&me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-project-hour-estimatedTime","Estimert tid"),Property:"EstimatedTime",PropertyType:"double"}),me.TimeAndCostVisibility.showEstimatedCost&&me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-project-hour-estimatedCost","Estimert kostnad"),Property:"EstimatedCost",PropertyType:"double"}),me.TimeAndCostVisibility.showRealTime&&me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-project-hour-realtime","Reel tid"),Property:"RealTime",PropertyType:"double"}),me.TimeAndCostVisibility.showRealCost&&me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-project-hour-realcost","Reel kostnad"),Property:"RealCost",PropertyType:"double"}),me.TimeAndCostVisibility.showNote&&!me.TimeAndCostVisibility.showRealTime&&me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-WorkOrderXResourceGroup-note","Kommentar"),Property:"Note",PropertyType:"string"}),me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-WorkOrderXResourceGroup-registeredDate","Registrert Dato"),Property:"RegisteredDate",PropertyType:"date"}),me.sorting={RegisteredDate:"desc"})};this.initTable=function(){me.table||(setColumns(),me.table=new ngTableParams({page:1,count:10,sorting:me.sorting,filter:{PropertyFilter:[]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("Person.LastName"),columns.push("ResourceGroup.Description"),columns.push("ResourceGroup.Guid"),me.TimeAndCostVisibility.showEstimatedCost||columns.push("EstimatedCost"),me.TimeAndCostVisibility.showEstimatedTime||columns.push("EstimatedTime"),me.TimeAndCostVisibility.showRealCost||columns.push("RealCost"),me.TimeAndCostVisibility.showRealTime||columns.push("RealTime"),columns.push("Note");var filter=angular.copy(params.filter()),url="",sorting=params.sorting();if($scope.model.IsTemplate?(url=repository.apiData.periodicTaskXResourceGroup.url,filter.PropertyFilter.push({Property:"PeriodicTask.GuidProject",Operator:"=",Value:$scope.model.Guid})):(url=repository.apiData.workOrderXResourceGroup.url,filter.PropertyFilter.push({Property:"WorkOrder.GuidProject",Operator:"=",Value:$scope.model.Guid})),-1!==Object.keys(sorting)[0].indexOf(".Caption")){var key=Object.keys(sorting)[0],order=sorting[key];key.includes("ResourceGroup")?key=key.replace(".Caption",".Id"):key.includes("Person")&&(key=key.replace(".Caption",".Firstname")),sorting={},sorting[key]=order}repository.GetPaginated(url,params.page()-1,params.count(),sorting,filter,null,JSON.stringify(columns)).then(function(result){var dates=result.List.filter(function(row){return row.RegisteredDate}).map(function(row){return new Date(row.RegisteredDate)});if(dates.length>0){var latestRegisteredDate=new Date(Math.max.apply(null,dates));latestRegisteredDate>$scope.telerikInfo.endDate&&($scope.telerikInfo.endDate=latestRegisteredDate)}me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,me.isLoading=!1,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))}},$scope.hourTypeMenuOptions=function(hourType){var options=[];return $scope.rootScope.hasEditAccess("HourType")&&options.push({html:' '+translationService.translate("web-project-hourType-edit","Rediger timetype")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.updateHourType(hourType)}}),$scope.rootScope.hasDeleteAccess("HourType")&&options.push({html:' '+translationService.translate("web-project-hourType-delete","Slett timetype")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.deleteHourType(hourType)}}),options},$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)};var getMenuLink=function(url,icon,text){return{html:' '+text+"",isHref:!0}};$scope.$watch("model",function(newValue,oldValue){newValue!==oldValue&&($scope.canManageHourTypes=$rootScope.userInfo.guidPerson===$scope.model.GuidManagerPerson||$rootScope.userInfo.guidPerson===$scope.model.GuidOwnerPerson||$rootScope.userInfo.isSystemAdministrator)});var loadingListener=$scope.$watchGroup(["resourceGroupInfo.isLoading","isModelLoading"],function(){!1===$scope.isModelLoading&&!1===$scope.resourceGroupInfo.isLoading&&($scope.telerikInfo.updateTelerikParameters(),loadingListener())},!0);$scope.$watch("currentPage",function(newVal,oldVal){newVal!==oldVal&&"resource"===newVal&&"resource"===newVal&&($scope.telerikInfo.reloadReports=!$scope.telerikInfo.reloadReports,$scope.hasVisitedTab=!0)}),$scope.telerikInfo=new function(){var me=this;this.parameters={GuidProject:$scope.model.Guid},this.displayReports=!1,this.endDate=new Date,this.reloadReports=!1,this.updateTelerikParameters=function(){if(!$scope.model.IsTemplate){var endDate=$scope.model.EndDate?new Date($scope.model.EndDate):null,startDate=$scope.model.StartDate?new Date($scope.model.StartDate):new Date;null!==endDate&&void 0!==endDate||(endDate=me.endDate),endDate.getTime()b.GroupCaption?1:0}):isNum?tableData.sort(function(a,b){return b.GroupCaption-a.GroupCaption}):tableData.sort(function(a,b){return a.GroupCaptionb.GroupCaption?1:0}).reverse():(tableData.sort(function(a,b){var valA,valB;return a.Result.forEach(function(property){sorting[property.Property]&&(valA=property.Value)}),b.Result.forEach(function(property){sorting[property.Property]&&(valB=property.Value)}),isNum?valA-valB>0?-1:1:valA>valB?-1:1}),"asc"===sorting[Object.keys(sorting)[0]]&&tableData.reverse()),tableData};$scope.getPropertyValue=function(item,column){if(item.Property===column.Property)return item.Value}}angular.module("Plania").directive("projectResourceGroupTableWidget",function(){return{restrict:"E",scope:{guid:"="},controller:["$scope","Repository","TranslationService","ngTableParams","ListService","RegisteredFieldService",controller],templateUrl:"app/project/widgets/projectResourceGroupTableWidget.html"}})}(),function(){function controller($scope,repository,modalParams,modalInstance,translationService,$modal,ngTableParams,listService){$scope.model={},$scope.isUpdate=!1,$scope.isTemplate=modalParams.IsTemplate,modalParams.Milestone?($scope.model=angular.copy(modalParams.Milestone),$scope.isUpdate=!0):$scope.model.GuidProject=modalParams.GuidProject,$scope.saveMilestone=function(){if($scope.isUpdate){var changeSet={Id:$scope.model.Id,Description:$scope.model.Description,DueDate:$scope.model.DueDate,EndDate:$scope.model.EndDate};repository.patch(repository.apiData.projectMilestone.url,$scope.model.Guid,changeSet).then(function(result){modalInstance.close()}).catch(function(error){swal("Feil ved lagring",error,"error")})}else repository.createSingle(repository.apiData.projectMilestone.url,$scope.model).then(function(result){modalInstance.close()}).catch(function(error){swal("Feil ved lagring",error,"error")})}}angular.module("Plania").controller("ProjectMilestoneModalController",["$scope","Repository","modalParams","$modalInstance","TranslationService","$modal","ngTableParams","ListService",controller])}(),function(){function controller($scope,$modal,repository,$rootScope,translationService){$scope.hasCreateAccess=$rootScope.hasCreateAccess("ProjectMilestone")&&!$scope.project.ClosedDate,$scope.hasEditAccess=$rootScope.hasEditAccess("ProjectMilestone"),$scope.hasDeleteAccess=$rootScope.hasDeleteAccess("ProjectMilestone");var getMilestones=function(){if(!$scope.project.Guid)return void console.warn("Project milestone directive expected project guid, got: "+$scope.project.Guid);repository.GetPaginated(repository.apiData.projectMilestone.url,0,-1,{DueDate:"asc",EndDate:"asc"},{PropertyFilter:[{Property:"GuidProject",Operator:"=",Value:$scope.project.Guid}]},"",JSON.stringify(["Id","Description","DueDate","EndDate"])).then(function(result){$scope.milestones=result.List})};getMilestones(),$scope.milestoneCreateModal=function(){$modal.open({templateUrl:"app/projectMilestone/views/editMilestoneModal.html",controller:"ProjectMilestoneModalController",resolve:{modalParams:function(){return{GuidProject:$scope.project.Guid,IsTemplate:$scope.project.IsTemplate}}}}).result.then(function(responseResult){getMilestones()})},$scope.milestoneUpdateModal=function(milestone){$modal.open({templateUrl:"app/projectMilestone/views/editMilestoneModal.html",controller:"ProjectMilestoneModalController",resolve:{modalParams:function(){return{Milestone:milestone,IsTemplate:$scope.project.IsTemplate}}}}).result.then(function(responseResult){getMilestones()})},$scope.milestoneEndToday=function(milestone){milestone.EndDate=moment().toDate(),repository.updateSingle(repository.apiData.projectMilestone.url,milestone).then(function(result){getMilestones(),repository.growl(translationService.translate("web-swal-projectmilestone-endtoday-success","Milepælen ble fullført!"),"success")}).catch(function(error){repository.growl(error,"danger")})},$scope.milestoneDelete=function(milestone){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-projectmilestone-message","Milepælen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-supplier-projectmilestone-button-confirm","Ja, fjern milepælen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.projectMilestone.url,milestone.Guid).then(function(result){swal(translationService.translate("web-swal-projectmilestone-delete-success","Milepælen ble fjernet!"),result,"success"),getMilestones()})})}}angular.module("Plania").directive("projectMilestone",function(){return{restrict:"E",scope:{project:"=project",isExpanded:"=expanded",restrictEdit:"=restrictEdit"},controller:["$scope","$modal","Repository","$rootScope","TranslationService",controller],templateUrl:"app/projectMilestone/views/projectMilestoneDirective.html"}})}(),function(){function controller($scope,repository,registeredFieldService,ngTableParams,translationService,listService){$scope.isSaving=!1,$scope.activateAutocomplete=!0,$scope.missingMandatoryProperties=[],$scope.projectTemplatesInfo={search:!1,focus:!1},$scope.model={isTemplate:!0},registeredFieldService.getRegisteredField(repository.commonService.prefix.Project).then(function(result){$scope.fieldRules=result}),$scope.hasError=function(field){return!(!$scope.missingMandatoryProperties.includes(field)||$scope.model[field])||!(!$scope.missingMandatoryProperties.includes(field)||!$scope.model[field])&&(_.remove($scope.missingMandatoryProperties,function(property){return property===field}),!1)};var sectionIsValid=function(fields){return $scope.missingMandatoryProperties=[],fields.forEach(function(field){_.find($scope.fieldRules,{DomainFieldName:field,Mandatory:!0})&&!$scope.model[field]&&$scope.missingMandatoryProperties.push(field)}),!($scope.missingMandatoryProperties.length>0)};$scope.update=function(destination){if($scope.hasCreateAccess("Project")&&!$scope.isSaving&§ionIsValid(["Id","Description","Text"])){$scope.isSaving=!0;var success=function(result){$scope.isSaving=!1,repository.growl("Prosjektmal har blitt laget","success"),destination&&(repository.commonService.setLastRegisterGuid(destination,$scope.model.Guid),$scope.goBack(destination,{guid:result.Guid,menuGuid:$scope.navigation.params.menuGuid}))},error=function(error){$scope.isSaving=!1,"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Message,"danger")};repository.createSingle(repository.apiData.project.endpoint.createTemplate,$scope.model).then(success).catch(error)}},$scope.onProjectTemplateSelect=function(project){return project?project.Guid===$scope.model.GuidProjectTemplate?void($scope.model.GuidProjectTemplate=""):void($scope.model.GuidProjectTemplate=project.Guid):void($scope.model.GuidProjectTemplate="")},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidArea="",$scope.model.Area=""),$scope.model.GuidBuilding=building.Guid,$scope.model.GuidEstate&&""!==$scope.model.GuidEstate&&$scope.model.GuidEstate===building.GuidEstate||($scope.model.GuidEstate=building.GuidEstate,$scope.model.Estate={Caption:building.Estate.Id+" - "+building.Estate.Description}),building.CostCenter&&($scope.model.CostCenter={Caption:building.CostCenter.Caption},$scope.model.GuidCostCenter=building.GuidCostCenter)},$scope.getPropertyValue=function(entity,column){return listService.GetPropertyValue(entity,column)},$scope.projectTemplateColumns=[{Position:1,Title:translationService.translate("web-project-id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-project-description","Beskrivelse"),Property:"Description",PropertyType:"string"}],$scope.projectTemplates=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{IsTemplate:!0}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,filterDelay:10,getData:function($defer,params){if($scope.hasReadAccess("Project")){var columns=[];$scope.projectTemplateColumns.forEach(function(col){col.Property&&columns.push(col.Property)}),repository.GetPaginated(repository.apiData.project.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),params.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}})}angular.module("Plania").controller("CreateProjectTemplateController",["$scope","Repository","RegisteredFieldService","ngTableParams","TranslationService","ListService",controller])}(),function(){function controller($scope,$modalInstance,params,repository,translationService,$localStorage,workOrderService){$scope.isSaving=!1,$scope.readyToIssue=!1,$scope.validationMessage=null,$scope.model=params.model,$scope.canChangeStatus=!$localStorage.generalOptions.SendPoOnlyByMail,$scope.canActivateWorkOrder=!1,$scope.model.OrderingDate&&(repository.growl(translationService.translate("web-swal-purchaseOrder-issueOrder-alreadyIssued","Ordren er allerede bestilt"),"danger"),$scope.cancel());var workOrderActivationErrorMessage;repository.runAction(repository.apiData.purchaseOrder.endpoint.canIssue+$scope.model.Guid).then(function(response){$scope.readyToIssue=!0},function(errorMessage){errorMessage&&(workOrderService.isWorkOrderStage0(errorMessage)&&$scope.hasEditAccess(repository.commonService.prefix.WorkOrder)?($scope.canActivateWorkOrder=!0,$scope.readyToIssue=!0,workOrderActivationErrorMessage=errorMessage):workOrderService.isWorkOrderStage0(errorMessage)&&!$scope.hasEditAccess(repository.commonService.prefix.WorkOrder)&&(errorMessage=translationService.translate("web-purchaseOrder-workOrder-activate-missingAccess","Kan ikke bestille med en eller flere bestillingsobjekter koblet til en planlagt arbeidsordre og bruker mangler rettighet til å aktivere arbeidsordren")),$scope.validationMessage=errorMessage)}),$scope.continue=function(sendEmail){if(!$scope.ValidationMessage&&!$scope.isSaving){var issueOrder=function(){$scope.isSaving=!0,$modalInstance.close(sendEmail?{ReportId:$scope.model.GuidPurchaseOrderForm?$scope.model.PurchaseOrderForm.Report.Id:"PrintPurchaseOrder",ButtonTitle:translationService.translate("web-purchaseOrder-printPurchaseOrder-preview","Forhåndsvis bestillingsraport")}:"changeStatus")};$scope.canActivateWorkOrder?workOrderService.shouldActivateWorkOrder(params.guidWorkOrder,workOrderActivationErrorMessage).then(function(result){$scope.isSaving=!1,issueOrder()},function(error){$scope.isSaving=!1,error&&repository.growl(error,"danger")}):issueOrder()}},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("IssuePurchaseOrderModalController",["$scope","$modalInstance","params","Repository","TranslationService","$localStorage","WorkOrderService",controller])}(),function(){function controller($scope,$modalInstance,params,repository,translationService,enumService,$state,$rootScope){$scope.model={},$scope.modelProperties={quantityToReceive:1},$scope.maxQuantityToReceive=0;var columns=["SparePart.Inventory"];$scope.units=enumService.getUnits(),$scope.getUnitValue=function(value){var unit=_.find($scope.units,function(o){return o.value===value});return unit?unit.translatedValue:value},repository.getMainModel(repository.apiData.purchaseOrderItem.url,params.Guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.maxQuantityToReceive=$scope.model.Rest,$scope.modelProperties.quantityToReceive=$scope.model.Rest},function(error){repository.growl(error,"danger")}),$scope.save=function(){$scope.model.ReceivedQuantity=$scope.model.ReceivedQuantity+$scope.modelProperties.quantityToReceive,$scope.model.Rest=$scope.model.OrderedQuantity-$scope.model.ReceivedQuantity,$modalInstance.close($scope.model)},$scope.cancel=function(){$modalInstance.close()}}angular.module("Plania").controller("PartiallyReceiveItemController",["$scope","$modalInstance","params","Repository","TranslationService","EnumService","$state","$rootScope",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,$rootScope,ngTableParams,$window,translationService,$q,$localStorage,listService,$timeout){function sendEmail(previewItem,emailEntityLists){var emailPrefill={body:"",subject:"Bestilling "+$scope.model.Caption},contactPersonEmail=$scope.model.ContactPerson&&$scope.model.ContactPerson.Email?mailAddress($scope.model.ContactPerson.Email):null,supplierEmail=$scope.model.Supplier&&$scope.model.Supplier.Email?mailAddress($scope.model.Supplier.Email):null;contactPersonEmail?(emailPrefill.to=[contactPersonEmail],emailPrefill.copy=supplierEmail?[supplierEmail]:[]):(emailPrefill.to=supplierEmail?[supplierEmail]:[],emailPrefill.copy=[]),_.forEach(emailEntityLists,function(entity){var emailAddress=mailAddress(entity.RecipientEmailAddress);emailAddress.isLocked=!0,entity.IsCopy?_.find(emailPrefill.copy,function(mail){return mail.Email===emailAddress.Email})||emailPrefill.copy.push(emailAddress):_.find(emailPrefill.to,function(mail){return mail.Email===emailAddress.Email})||emailPrefill.to.push(emailAddress)});var onNewDocument=function(){$scope.forceReloadDocumentTable=!1,$timeout(function(){$scope.forceReloadDocumentTable=!0},250)};$modal.open({templateUrl:"app/common/views/emailModal.html",controller:"EmailModalController",size:"lg",resolve:{params:function(){return{entity:"PurchaseOrder",model:$scope.model,reportPreviewItems:previewItem?[previewItem]:[],email:emailPrefill,returnEmailObject:!0,onNewDocument:onNewDocument}}}}).result.then(function(alarmLog){$scope.reloadAlarmLogTable=!0;var success=function(result){updateSuccess(result,"purchaseOrder.edit")};repository.runAction(repository.apiData.purchaseOrder.endpoint.issue+$scope.model.Guid,alarmLog).then(success,updateError)})}$scope.isUpdate="purchaseOrder.edit"===$scope.navigation.current.name,$scope.model={Guid:$stateParams.guid},$scope.activateAutocomplete=!1,$scope.modelDto={},$scope.viewMode=!!$scope.isUpdate,$scope.isPurchaseOrderClosedViaProject=!1,$scope.allRowsSelected=!1,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode},$scope.documents=[],$scope.alarmLogs=[],$scope.isDocumentsCollapsed=!0,$scope.reloadDocumentTable=!1,$scope.forceReloadDocumentTable=!1,$scope.reloadAlarmLogTable=!1,$scope.reloadEmailEntityListTable=!1,$scope.counts={documentTotalCount:0},$scope.validCharacters="^(?!.*<[a-zA-ZæøåÆØÅ]+).*",$scope.getPropertyValue=function(entity,field){return listService.GetPropertyValue(entity,field)},$scope.selectedItems=[],$scope.itemIsSelected=function(guid){return _.contains($scope.selectedItems,guid)},$scope.selectAllRows=function(){$scope.allRowsSelected?($scope.purchaseOrderItemTable.data.forEach(function(row){var index=_.findIndex($scope.selectedItems,function(o){return o===row.Guid});$scope.selectedItems.splice(index,1)}),$scope.allRowsSelected=!1):($scope.purchaseOrderItemTable.data.forEach(function(row){_.contains($scope.selectedItems,row.Guid)||$scope.selectedItems.push(row.Guid)}),$scope.allRowsSelected=!0)},$scope.addItem=function(guid){if(_.contains($scope.selectedItems,guid)){for(var i=0;i<$scope.selectedItems.length;i++)if($scope.selectedItems[i]===guid)return void $scope.selectedItems.splice(i,1)}else $scope.selectedItems.push(guid)},$scope.receiveSelectedItems=function(){if(0===$scope.selectedItems.length)return void swal(translationService.translate("web-no-choice-header","Ingen valg"),translationService.translate("purchase-order-purchase-order-item-list-noSelect","Ingen reservedeler valgt. Velg en eller flere fra listen for å motta"),"error");var nrSuccessCalls=0;swal({title:translationService.translate("web-swal-purchase-order-item-receive","Bekreft mottak av reservedeler"),text:translationService.translate("web-swal-purchase-order-item-receive-message","Er du sikker på at du vil motta reservedeler?"),type:"info",showCancelButton:!0,confirmButtonColor:"#2196f3",confirmButtonText:translationService.translate("web-swal-purchase-order-item-receive-confirm","Motta reservedeler"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){$scope.selectedItems.forEach(function(item){updateItem(item)}),$scope.reloadMainEntity()});var updateItem=function(guid){repository.runAction(repository.apiData.purchaseOrderItem.endpoint.receive+guid).then(function(result){++nrSuccessCalls===$scope.selectedItems.length&&(swal(translationService.translate("web-swal-purchase-order-item-receive-success","Reservedelene er mottatt!"),"","success"),$scope.purchaseOrderItemTable.reload())})}},$scope.receiveItem=function(item){swal({title:translationService.translate("web-swal-purchase-order-item-receive","Bekreft mottak av reservedeler"),text:translationService.translate("web-swal-purchase-order-item-receive-message","Er du sikker på at du vil motta reservedeler?"),type:"info",showCancelButton:!0,confirmButtonColor:"#2196f3",confirmButtonText:translationService.translate("web-swal-purchase-order-item-receive-confirm","Motta reservedeler!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){repository.runAction(repository.apiData.purchaseOrderItem.endpoint.receive+item).then(function(result){swal(translationService.translate("web-swal-purchase-order-item-receive-success","Reservedelene er mottatt!"),result.Id,"success"),$scope.purchaseOrderItemTable.reload(),$scope.reloadMainEntity()},function(error){swal(translationService.translate("web-error","Feil"),error,"error")})})},$scope.receiveItemPartially=function(guid){$modal.open({templateUrl:"app/PurchaseOrder/views/ReceivePartiallyModal.html",controller:"PartiallyReceiveItemController",resolve:{params:function(){return{Guid:guid}}}}).result.then(function(item){repository.updateSingle(repository.apiData.purchaseOrderItem.url,item).then(function(result){repository.growl(translationService.translate("web-purchase-order-item-updated","Objektet er oppdatert"),"success"),$scope.purchaseOrderItemTable.reload(),$scope.reloadMainEntity()})})};var updateAccess=function(){if($scope.isUpdate){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.PurchaseOrder,checkOtherDo),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.PurchaseOrder,checkOtherDo)||"Proposal"!==$scope.model.Status,$scope.canReceive=$localStorage.generalOptions.UseReception&&("Ordered"===$scope.model.Status||"PartiallyReceived"===$scope.model.Status)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.PurchaseOrder)};updateAccess();var getCardTables=function(){$scope.purchaseOrderItemTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{PropertyFilter:[{Property:"GuidPurchaseOrder",Operator:"=",Value:$scope.model.Guid}]}},{total:0,counts:[10,20,50],filterDelay:10,paginationMaxBlocks:6,getData:function($defer,params){var columns=[];$scope.purchaseOrderItemColumns.forEach(function(col){columns.push(col.Property)}),columns.push("WorkOrder.Project.ClosedDate"),repository.GetPaginated(repository.apiData.purchaseOrderItem.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){result.List.forEach(function(item){item.WorkOrder&&item.WorkOrder.Project&&item.WorkOrder.Project.ClosedDate&&($scope.isPurchaseOrderClosedViaProject=!0)}),$scope.purchaseOrderItemTable.settings().total=result.TotalCount,$scope.purchaseOrderItemTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})},columns=["Building.Id","Building.Description","Building.GuidCostCenter","Equipment.Id","Equipment.Description","Area.Id","Area.Description","ContactPerson.FirstName","ContactPerson.LastName","ContactPerson.Email","Customer.Id","Customer.Description","DeliveryTerm.Id","PaymentTerm.Id","PurchaseOrderForm.Description","PurchaseOrderForm.Report.Id","PurchaseOrderForm.GuidReport","Supplier.Id","Supplier.Description","Supplier.Telephone","Supplier.Email","UserPrintedBy.RealName","UserReceivedBy.RealName","UserUpdatedBy.RealName","UserCreatedBy.RealName"],setProperties=function(){var purchaseOrder=$scope.model;purchaseOrder.Building&&($scope.modelDto.building=$scope.getEntityCaption(purchaseOrder.Building)),purchaseOrder.Equipment&&($scope.modelDto.equipment=$scope.getEntityCaption(purchaseOrder.Equipment)),purchaseOrder.Area&&($scope.modelDto.area=$scope.getEntityCaption(purchaseOrder.Area)),purchaseOrder.ContactPerson&&($scope.modelDto.contactPerson=purchaseOrder.ContactPerson.FirstName+" "+purchaseOrder.ContactPerson.LastName),purchaseOrder.Customer&&($scope.modelDto.customer=$scope.getEntityCaption(purchaseOrder.Customer)),purchaseOrder.DeliveryTerm&&($scope.modelDto.deliveryTerm=purchaseOrder.DeliveryTerm.Id),purchaseOrder.PaymentTerm&&($scope.modelDto.paymentTerm=purchaseOrder.PaymentTerm.Id),purchaseOrder.PurchaseOrderForm&&($scope.modelDto.purchaseOrderForm=purchaseOrder.PurchaseOrderForm.Description),purchaseOrder.Supplier&&($scope.modelDto.supplier=$scope.getEntityCaption(purchaseOrder.Supplier)),purchaseOrder.UserPrintedBy&&($scope.modelDto.userPrintedBy=purchaseOrder.UserPrintedBy.RealName),purchaseOrder.UserReceivedBy&&($scope.modelDto.userReceivedBy=purchaseOrder.UserReceivedBy.RealName),purchaseOrder.UserCreatedBy&&($scope.modelDto.userCreatedBy=purchaseOrder.UserCreatedBy.RealName)};if($scope.isUpdate)repository.getMainModel(repository.apiData.purchaseOrder.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.reloadDocumentTable=!0,updateAccess(),setProperties(),getCardTables(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger"),$scope.activateAutocomplete=!0});else{var date=new Date;$scope.model.BudgetDate=new Date(date.getFullYear(),date.getMonth(),1),$scope.model.IsLockedProposal=$localStorage.generalOptions.CanLockPoProposal,$scope.model.GuidPurchaseOrderForm=$localStorage.generalOptions.GuidDefaultOrderForm,$scope.activateAutocomplete=!0}var updateSuccess=function(result,destination){repository.growl($scope.isUpdate?translationService.translate("update-purchaseOrder-success","Bestilling har blitt oppdatert."):translationService.translate("create-purchaseOrder-success","Bestilling har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},updateError=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.update=function(destination){var success=function(result){updateSuccess(result,destination)};$scope.isUpdate?repository.updateSingle(repository.apiData.purchaseOrder.url,$scope.model).then(success,updateError):repository.createSingle(repository.apiData.purchaseOrder.url,$scope.model).then(success,updateError)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-purchaseOrder-message","Bestilling vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-purchaseOrder-button-confirm","Ja, fjern bestilling"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.purchaseOrder.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-purchaseOrder-success","Bestilling ble fjernet!"),result,"success"),$scope.goBack("purchaseOrder.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.reloadMainEntity=function(){var deferred=$q.defer();return repository.getMainModel(repository.apiData.purchaseOrder.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,deferred.resolve(response)},function(error){deferred.reject(error)}),deferred.promise},$scope.getEntityCaption=function(item){return item.Id+" "+item.Description},$scope.purchaseOrderItemColumns=[],$scope.purchaseOrderItemColumns.AddColumn=function(translationId,defaultText,property,propertyType){return this.push({Position:this.length,Title:translationService.translate(translationId,defaultText),Property:property,PropertyType:propertyType}),this},$scope.purchaseOrderItemColumns.AddColumn("web-purchaseOrderItem-Id","Id","Id","string").AddColumn("web-purchaseOrderItem-Description","Beskrivelse","Description","string").AddColumn("web-workOrder-Id","AO Id","WorkOrder.Id","number").AddColumn("web-supplier-description","Leverandør","Supplier.Description","string").AddColumn("web-purchaseOrderItem-OrderedQuantity","Bestilt antall","OrderedQuantity","number").AddColumn("web-purchaseOrderItem-UnitPrice","Enhetspris","UnitPrice","double").AddColumn("web-purchaseOrderItem-OrderedAmount","Bestilt beløp","OrderedAmount","double").AddColumn("web-purchaseOrderItem-Status","Status","Status","enum.purchaseorderitemstatus"),$scope.costColumns=[],$scope.costColumns.addColumn=function(translationId,defaultText,property,propertyType){return this.push({Position:this.length,Title:translationService.translate(translationId,defaultText),Property:property,PropertyType:propertyType}),this},$scope.costColumns.addColumn("web-cost-InvoiceNumber","Fakturanr.","InvoiceNumber","string").addColumn("web-account-id","Konto","Account.Id","string").addColumn("web-account-description","Beskrivelse","Account.Description","string").addColumn("web-cost-amount","Beløp","Amount","double").addColumn("web-cost-InvoiceDate","Fakturadato","InvoiceDate","date").addColumn("web-supplier-description","Leverandør","Supplier.Description","string").addColumn("web-cost-vouchernumber","Bilagsnr","VoucherNumber","string"),$scope.entityEmailListColumns=[],$scope.entityEmailListColumns.addColumn=function(translationId,defaultText,property,propertyType){return this.push({Position:this.length,Title:translationService.translate(translationId,defaultText),Property:property,PropertyType:propertyType}),this},$scope.entityEmailListColumns.addColumn("web-entityEmailList-recipientName","Navn","RecipientName","string").addColumn("web-entityEmailList-recipientEmailAddress","Epost","RecipientEmailAddress","string").addColumn("web-entityEmailList-sentDate","Sendt","SentDate","date").addColumn("web-entityEmailList-status","Status","Status","enum.EntityEmailListStatus").addColumn("web-entityEmailList-isCopy","Kopi (cc)","IsCopy","bool"),$scope.addPurchaseOrderItem=function(){if(!$scope.model.GuidSupplier)return repository.growl(translationService.translate("web-purchaseOrderItem-Create-PurchaseOrderWithoutSupplier","Du må velge leverandør for bestillingen før du kan opprette bestillingsobjekter"),"danger"),!1;$modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"md",resolve:{params:function(){return{purchaseOrderItem:{GuidPurchaseOrder:$scope.model.Guid,GuidBuilding:$scope.model.GuidBuilding,GuidSupplier:$scope.model.GuidSupplier,Supplier:$scope.model.Supplier,GuidDataOwner:repository.commonService.getFilterData().selectedDataOwner.Guid,GuidCostCenter:$scope.model.Building.GuidCostCenter}}}}}).result.then(function(){$scope.purchaseOrderItemTable.reload(),$scope.reloadMainEntity()})},$scope.updatePurchaseOrderItem=function(guid){$scope.hasEditAccess("PurchaseOrderItem")&&$modal.open({ templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"xl",resolve:{params:function(){return{Guid:guid}}}}).result.then(function(){$scope.purchaseOrderItemTable.reload(),$scope.reloadMainEntity()})},$scope.removePurchaseOrderItem=function(purchaseOrderItemGuid){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-purchaseOrderItem-message","Bestilling objektet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-purchaseOrderItem-button-confirm","Ja, fjern bestilling objektet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.purchaseOrderItem.url,purchaseOrderItemGuid).then(function(result){swal(translationService.translate("web-swal-purchaseOrderItem-success","Bestilling objektet ble fjernet!"),result,"success"),repository.growl("Bestilling objektet er fjernet fra bestillingen","success"),$scope.purchaseOrderItemTable.reload(),$scope.reloadMainEntity()})})},$scope.updatCost=function(guid){$modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"xl",resolve:{params:function(){return{Guid:guid}}}}).result.then(function(){$scope.purchaseOrderItemTable.reload()})},$scope.removeCost=function(costGuid){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-purchaseOrderItem-message","Bestilling objektet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cost-button-confirm","Ja, fjern kostnad!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.cost.url,costGuid).then(function(result){swal(translationService.translate("web-swal-cost-success","Kostnad ble fjernet!"),result,"success"),repository.growl("Kostnad er fjernet fra bestillingen","success"),$scope.costTable.reload()})})},$scope.onSupplierSelect=function(supplier){if(!supplier)return void($scope.model.GuidSupplier="");$scope.model.GuidSupplier!==supplier.Guid&&($scope.model.GuidContactPerson="",$scope.modelDto.contactPerson=""),$scope.model.GuidSupplier=supplier.Guid,$scope.model.Supplier=supplier},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"contactPerson":filter.PropertyFilter=[{Property:"GuidSupplier",Operator:"=",Value:$scope.model.GuidSupplier}];break;case"equipment":filter.PropertyFilter=[],filter.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:!1}),$scope.model.GuidBuilding&&filter.PropertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:$scope.model.GuidBuilding});break;case"area":$scope.model.GuidBuilding&&(filter.PropertyFilter=[{Property:"GuidBuilding",Operator:"=",Value:$scope.model.GuidBuilding}]);break;case"supplier":filter.PropertyFilter=[{Property:"IsDeactivated",Operator:"=",Value:"false"},{Property:"HasNotRequisition",Operator:"=",Value:"false"}]}return filter},$scope.issueOrder=function(){var guidWorkOrder=$scope.purchaseOrderItemTable.data[0].GuidWorkOrder;$scope.reloadMainEntity().then(function(response){$modal.open({templateUrl:"app/purchaseOrder/views/issuePurchaseOrderModal.html",controller:"IssuePurchaseOrderModalController",size:"md",resolve:{params:function(){return{model:$scope.model,guidWorkOrder:guidWorkOrder}}}}).result.then(function(response){if("changeStatus"===response){var success=function(result){updateSuccess(result,"purchaseOrder.edit")};repository.runAction(repository.apiData.purchaseOrder.endpoint.issue+$scope.model.Guid).then(success,updateError)}else startEmailDialogWithPreviewItems(response)},function(error){error&&repository.growl(error,"danger")})})};var mailAddress=function(emailAddress){return{Name:emailAddress,Email:emailAddress,DisplayProperty:emailAddress+(new Date).valueOf(),isLocked:!1}},startEmailDialogWithPreviewItems=function(previewItem){repository.GetPaginated(repository.apiData.entityEmailList.url,0,-1,{RecipientName:"asc"},{PropertyFilter:[{Property:"GuidPurchaseOrder",Operator:"=",Value:$scope.model.Guid}]},null,JSON.stringify(["RecipientEmailAddress","IsCopy","Status"])).then(function(result){sendEmail(previewItem,result.List)},function(error){sendEmail(previewItem,[]),repository.showError(error)})};$scope.print=function(){$localStorage.reportParams=JSON.stringify({Guid:$scope.model.Guid});var reportId=$scope.model.GuidPurchaseOrderForm?$scope.model.PurchaseOrderForm.Report.Id:"PrintPurchaseOrder",url=$scope.navigation.href("report.print",{reportName:reportId});$window.open(url,"_blank")},$scope.sendEmail=function(){var onNewDocument=function(){$scope.forceReloadDocumentTable=!1,$timeout(function(){$scope.forceReloadDocumentTable=!0},250)};$modal.open({templateUrl:"app/common/views/emailModal.html",controller:"EmailModalController",size:"lg",resolve:{params:function(){return{entity:"PurchaseOrder",model:$scope.model,onNewDocument:onNewDocument}}}}).result.then(function(){$scope.reloadAlarmLogTable=!0})},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.showPurchaseButton=function(){return $localStorage.generalOptions.ActivatePurchaseOrderInWeb&&$scope.model&&$scope.model.Supplier&&$scope.isUpdate&&!$scope.restrictEdit&&!$scope.model.OrderingDate&&!$scope.isPurchaseOrderClosedViaProject&&$scope.purchaseOrderItemTable&&$scope.purchaseOrderItemTable.data&&$scope.purchaseOrderItemTable.data.length>0&&"Proposal"===$scope.model.Status},$scope.canEditPurchaseOrderItem=function(purchaseOrderItem){return purchaseOrderItem&&$scope.isUpdate&&!$scope.restrictEdit};var getMenuLink=function(url,icon,text){return{html:' '+text+"",isHref:!0}};$scope.canReceiveItem=function(item){return"Ordered"===item.Status||"PartiallyReceived"===item.Status},$scope.contextMenuOptions=function(item){var options=[];return $scope.hasEditAccess("PurchaseOrderItem")&&options.push({html:' '+translationService.translate("web-workorder-purchaseorderitem-edit","Rediger konteringsobjekt")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.updatePurchaseOrderItem(item.Guid)}}),$scope.hasDeleteAccess("PurchaseOrderItem")&&"Proposal"===item.Status&&options.push({html:' '+translationService.translate("web-workorder-purchaseorderitem-delete","Slett konteringsobjekt")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.removePurchaseOrderItem(item.Guid)}}),item.GuidWorkOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidWorkOrder}),"fa-suitcase",translationService.translate("web-listview-open-workorder","Åpne arbeidsordre"))),$scope.hasCreateAccess("Cost")&&"Proposal"!==item.Status&&"Closed"!==item.Status&&options.push({html:' '+translationService.translate("web-workorder-purchaseorderitem-createCost","Legg til kostnad")+"",click:function($itemScope,$event,modelValue,text,$li){var persistedData={};persistedData.GuidPurchaseOrderItem=item.Guid,repository.persistedData.setPersistedData("cost.create",persistedData),$scope.$parent.navigation.go("cost.create",{showPersistantData:!0},{reload:!0})}}),$scope.hasEditAccess("PurchaseOrderItem")&&$scope.canReceiveItem(item)&&options.push({html:' '+translationService.translate("web-workorder-purchaseorderitem-receive-partial","Registrer delmottak...")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.receiveItemPartially(item.Guid)}}),options},$scope.addEmailEntityList=function(){$modal.open({templateUrl:"app/entityEmailList/views/entityEmailListModal.html",controller:"EntityEmailListModalController",resolve:{modalParams:function(){return{guidPurchaseOrder:$scope.model.Guid,guidSupplier:$scope.model.GuidSupplier}}}}).result.then(function(result){$scope.reloadEmailEntityListTable=!$scope.reloadEmailEntityListTable})},$scope.editEntityEmailList=function(item){$modal.open({templateUrl:"app/entityEmailList/views/entityEmailListModal.html",controller:"EntityEmailListModalController",resolve:{modalParams:function(){return{guid:item.Guid,guidPurchaseOrder:$scope.model.Guid,guidSupplier:$scope.model.GuidSupplier}}}}).result.then(function(result){$scope.reloadEmailEntityListTable=!$scope.reloadEmailEntityListTable})},$scope.emailEntityListContextMenuOptions=function(item){var options=[];return options.push({html:' '+translationService.translate("web-purchaseOrder-entityEmailList-contextMenu-edit","Rediger")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.editEntityEmailList(item)}}),options.push({html:' '+translationService.translate("web-purchaseOrder-entityEmailList-contextMenu-delete","Fjern")+"",click:function($itemScope,$event,modelValue,text,$li){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-entityEmailList-message","Epostmottaker fjernes"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-button-delete","Fjern"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.entityEmailList.url,item.Guid).then(function(result){repository.growl("Epostmottaker fjernet","success"),$scope.reloadEmailEntityListTable=!$scope.reloadEmailEntityListTable})})}}),options}}angular.module("Plania").controller("PurchaseOrderController",["$scope","Repository","$stateParams","$modal","$rootScope","ngTableParams","$window","TranslationService","$q","$localStorage","ListService","$timeout",controller])}(),function(){function controller($scope,$modalInstance,params,repository,translationService,enumService,ngTableParams,ListService,$localStorage,$state,$rootScope,signalR){$scope.isUpdate=!!params.Guid,$scope.rootScope=$rootScope,$scope.model={},$scope.activateAutocomplete=!1,$scope.lockCostCenter=$localStorage.generalOptions.GetPoItemAccountingFromWo,$scope.restrictEdit=!1,$scope.restrictEditMessage="",$scope.isLoadingEntities=!1,$scope.isWorkOrderClosedViaProject=!1,$scope.isFromProjectTemplate=params.isFromProjectTemplate;var originalModel={};$scope.prefix=repository.commonService.prefix.PurchaseOrderItem,$scope.getPropertyValue=function(entity,column){return ListService.GetPropertyValue(entity,column)},params.purchaseOrderItem&¶ms.purchaseOrderItem.GuidSupplier&¶ms.purchaseOrderItem.GuidPurchaseOrder&&($scope.lockSupplier=!0),$scope.validCharacters='^[^<>"%{}|^~`]+$',$scope.generalOptions=$localStorage.generalOptions,$scope.generalOptions.DefaultPoEntityType===repository.commonService.prefix.Component?$scope.hasReadAccess("Component")?$scope.info={selectedLinkedEntity:"Component"}:$scope.hasReadAccess("Article")?$scope.info={selectedLinkedEntity:"Article"}:$scope.hasModule("SparePart")&&$scope.hasReadAccess("SparePart")&&($scope.info={selectedLinkedEntity:"SparePart"}):$scope.generalOptions.DefaultPoEntityType===repository.commonService.prefix.Article?$scope.hasReadAccess("Article")?$scope.info={selectedLinkedEntity:"Article"}:$scope.hasReadAccess("Component")?$scope.info={selectedLinkedEntity:"Component"}:$scope.hasModule("SparePart")&&$scope.hasReadAccess("SparePart")&&($scope.info={selectedLinkedEntity:"SparePart"}):$scope.generalOptions.DefaultPoEntityType===repository.commonService.prefix.SparePart?$scope.hasModule("SparePart")&&$scope.hasReadAccess("SparePart")?$scope.info={selectedLinkedEntity:"SparePart"}:$scope.hasReadAccess("Article")?$scope.info={selectedLinkedEntity:"Article"}:$scope.hasReadAccess("Component")&&($scope.info={selectedLinkedEntity:"Component"}):$scope.hasReadAccess("Component")?$scope.info={selectedLinkedEntity:"Component"}:$scope.hasReadAccess("Article")?$scope.info={selectedLinkedEntity:"Article"}:$scope.hasModule("SparePart")&&$scope.hasReadAccess("SparePart")&&($scope.info={selectedLinkedEntity:"SparePart"}),$scope.isUpdate?$scope.tabs=[{heading:translationService.translate("web-purchaseOrderItemWizard-purchaseOrderItemProduct-purchaseInfo","KonteringsObjekt"),step:0}]:$scope.tabs=[{heading:translationService.translate("web-purchaseOrderItemWizard-purchaseOrderItemProduct","Velg produkt"),step:0},{heading:translationService.translate("web-purchaseOrderItemWizard-purchaseOrderItem","Bestilling"),step:1},{heading:translationService.translate("web-purchaseOrderItemWizard-accounting","Kontering"),step:2},{heading:translationService.translate("web-purchaseOrderItemWizard-confirmation","Bekreftelse"),step:3}],$scope.units=enumService.getUnits(),$scope.getUnitValue=function(value){var unit=_.find($scope.units,function(o){return o.value===value});return unit?unit.translatedValue:value},$scope.step=0,$scope.isCurrentStep=function(step){return $scope.step===step},$scope.setCurrentStep=function(step){$scope.isValid(step)&&($(".tab-content").css("overflow","hidden"),setTimeout(function(){$(".tab-content").css("overflow","visible")},500),$scope.step=step)},$scope.isLastStep=function(){return $scope.step===$scope.tabs.length-1},$scope.getNextLabel=function(){return $scope.isLastStep()?translationService.translate("web-button-confirm","Bekreft"):translationService.translate("web-button-next","Neste")},$scope.handlePrevious=function(){$scope.setCurrentStep($scope.step-(0===$scope.step?0:1))},$scope.handleNext=function(){$scope.isLastStep()?$scope.update(!0):$scope.setCurrentStep($scope.step+=1)},$scope.isValid=function(step){if($scope.isUpdate)return!0;var valid=!0;switch(step){case 0:break;case 1:case 2:case 3:$scope.model.GuidComponent||$scope.model.GuidArticle||$scope.model.GuidSparePart||(valid=!1)}return valid};var accountingColumns=[{Property:"Department.Id",hidden:!0},{Property:"Department.Description",hidden:!0},{Property:"CostCenter.Id",hidden:!0},{Property:"CostCenter.Description",hidden:!0},{Property:"Account.Id",hidden:!0},{Property:"Account.Description",hidden:!0},{Property:"Accounting0.Id",hidden:!0},{Property:"Accounting0.Description",hidden:!0},{Property:"Accounting1.Id",hidden:!0},{Property:"Accounting1.Description",hidden:!0},{Property:"Accounting2.Id",hidden:!0},{Property:"Accounting2.Description",hidden:!0},{Property:"Accounting3.Id",hidden:!0},{Property:"Accounting3.Description",hidden:!0},{Property:"Accounting4.Id",hidden:!0},{Property:"Accounting4.Description",hidden:!0},{Property:"DataOwner.Dimension1",hidden:!0},{Property:"DataOwner.Dimension2",hidden:!0},{Property:"DataOwner.Dimension3",hidden:!0},{Property:"DataOwner.Dimension4",hidden:!0},{Property:"DataOwner.Dimension5",hidden:!0},{Property:"DataOwner.DepartmentCost",hidden:!0},{Property:"DataOwner.LastDimensionCost",hidden:!0}];$scope.articleColumns=accountingColumns.slice(0).concat([{Position:1,Title:translationService.translate("web-article-id"),Property:"Id",sortable:!0},{Position:2,Title:translationService.translate("web-article-description"),Property:"Description"},{Position:3,Title:translationService.translate("web-article-unitPrice"),Property:"UnitPrice"},{Property:"Unit",hidden:!0}]),$scope.componentColumns=accountingColumns.slice(0).concat([{Position:1,Title:translationService.translate("web-component-id"),Property:"Id",sortable:!0},{Position:2,Title:translationService.translate("web-component-description"),Property:"Description"},{Property:"Unit",hidden:!0}]),$scope.sparePartColumns=accountingColumns.slice(0).concat([{Position:1,Title:translationService.translate("web-sparePart-component-id","Id"),Property:"Component.Id",sortable:!0},{Position:2,Title:translationService.translate("web-sparePart-component-description","Beskrivelse"),Property:"Component.Description"},{Position:3,Title:translationService.translate("web-sparePart-price","Enhetspris"),Property:"ComponentXSupplier.Price"},{Position:4,Title:translationService.translate("web-sparePart-inventory","Beholdning"),Property:"Inventory"},{Property:"Component.Unit",hidden:!0}]),$scope.$watch("info.selectedLinkedEntity",function(newValue,oldValue){newValue!==oldValue&&("Article"!==newValue&&($scope.model.GuidArticle=null),"Component"!==newValue&&($scope.model.GuidComponent=null),"SparePart"!==newValue&&($scope.model.GuidSparePart=null),newValue&&$scope.items.reload())});var previousSelectedEntity="";$scope.items=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){if($scope.info&&$scope.info.selectedLinkedEntity){var filter=$scope.autoCompleteFilter($scope.info.selectedLinkedEntity)||{};params.filter().searchString&&(filter.searchString=params.filter().searchString),$scope.columns=[];var url="",columnProperties=[];switch($scope.info.selectedLinkedEntity){case"Article":url=repository.apiData.article.url,$scope.articleColumns.forEach(function(column){column.hidden||$scope.columns.push(column),columnProperties.push(column.Property)}),"Article"!==previousSelectedEntity&¶ms.sorting({UnitPrice:"asc"});break;case"Component":url=repository.apiData.component.url,$scope.componentColumns.forEach(function(column){column.hidden||$scope.columns.push(column),columnProperties.push(column.Property)}),"Component"!==previousSelectedEntity&¶ms.sorting({Description:"asc"});break;case"SparePart":url=repository.apiData.sparePart.url,$scope.sparePartColumns.forEach(function(column){column.hidden||$scope.columns.push(column),columnProperties.push(column.Property)}),"SparePart"!==previousSelectedEntity&¶ms.sorting({Inventory:"asc"})}previousSelectedEntity=$scope.info.selectedLinkedEntity,$scope.isLoadingEntities=!0,repository.GetPaginated(url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columnProperties)).then(function(result){$scope.isLoadingEntities=!1,params.total(result.TotalCount),$defer.resolve(result.List)},function(error){$scope.isLoadingEntities=!1,repository.growl(error,"danger")})}}}),$scope.selectEntity=function(entity){if(!$scope.isLoadingEntities){entity.GuidCostCenter&&!$scope.lockCostCenter&&($scope.model.GuidCostCenter=entity.GuidCostCenter),$scope.model.GuidDepartment||($scope.model.GuidDepartment=entity.GuidDepartment),$scope.model.GuidAccount||($scope.model.GuidAccount=entity.GuidAccount),$scope.model.GuidAccounting0||($scope.model.GuidAccounting0=entity.GuidAccounting0),$scope.model.GuidAccounting1||($scope.model.GuidAccounting1=entity.GuidAccounting1),$scope.model.GuidAccounting2||($scope.model.GuidAccounting2=entity.GuidAccounting2),$scope.model.GuidAccounting3||($scope.model.GuidAccounting3=entity.GuidAccounting3),$scope.model.GuidAccounting4||($scope.model.GuidAccounting4=entity.GuidAccounting4),$scope.entity=entity;var setUnit=function(unitValue){if(!unitValue)return void($scope.model.Unit=null);var unit=$scope.units.find(function(unit){return unit.translatedValue.toLowerCase()===unitValue.toLowerCase()||unit.value===unitValue});$scope.model.Unit=unit?unit.value:null};"Article"===$scope.info.selectedLinkedEntity&&($scope.model.GuidArticle=entity.Guid,$scope.model.Id=entity.Id,$scope.model.Description=entity.Description,$scope.model.UnitPrice=entity.UnitPrice,setUnit(entity.Unit)),"Component"===$scope.info.selectedLinkedEntity&&($scope.model.GuidComponent=entity.Guid,$scope.model.Id=entity.Id,$scope.model.Description=entity.Description,setUnit(entity.Unit),entity.ComponentXSuppliers&&1===entity.ComponentXSuppliers.length&&($scope.model.UnitPrice=entity.ComponentXSuppliers[0].Price)),"SparePart"===$scope.info.selectedLinkedEntity&&($scope.model.GuidSparePart=entity.Guid,$scope.model.Id=entity.Component.Id,$scope.model.Description=entity.Component.Description,entity.Component&&setUnit(entity.Component.Unit),entity.ComponentXSupplier&&($scope.model.UnitPrice=entity.ComponentXSupplier.Price)),$scope.setCurrentStep(1)}},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName.toLowerCase()){case"component":return params.purchaseOrderItem.GuidSupplier&&(filter.PropertyFilter=[{Property:"ComponentXSuppliers.GuidSupplier",Value:params.purchaseOrderItem.GuidSupplier,Operator:"="}]),filter;case"sparepart":return params.purchaseOrderItem.GuidSupplier&&(filter.PropertyFilter=[{Property:"ComponentXSupplier.GuidSupplier",Value:params.purchaseOrderItem.GuidSupplier,Operator:"="}]),filter;case"equipment":return $scope.model.GuidBuilding&&(filter.PropertyFilter=[{Property:"GuidBuilding",Value:$scope.model.GuidBuilding,Operator:"="}]),filter;case"supplier":return filter.PropertyFilter=[{Property:"IsDeactivated",Operator:"=",Value:"false"},{Property:"HasNotRequisition",Operator:"=",Value:"false"}],filter;case"article":return filter.FilterModel={Condition:"or",Rules:[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null}]},filter}},$scope.$watch("model.OrderedQuantity",function(newValue,oldValue){$scope.model.OrderedAmount=newValue&&$scope.model.UnitPrice?newValue*$scope.model.UnitPrice:0,$scope.model.OrderedAmount>=0?$scope.model.OrderedAmount>$scope.model.EstimatedAmount&&($scope.model.EstimatedAmount=$scope.model.OrderedAmount):$scope.model.EstimatedAmount=$scope.model.OrderedAmount},!0),$scope.$watch("model.UnitPrice",function(newValue,oldValue){$scope.model.OrderedAmount=newValue&&$scope.model.OrderedQuantity?newValue*$scope.model.OrderedQuantity:0,$scope.model.OrderedAmount>=0?$scope.model.OrderedAmount>$scope.model.EstimatedAmount&&($scope.model.EstimatedAmount=$scope.model.OrderedAmount):$scope.model.EstimatedAmount=$scope.model.OrderedAmount},!0);var columns=["Building.Id","Building.Description","Supplier.Id","Supplier.Description","Account.Id","Account.Decription","Accounting0.Id","Accounting0.Description","Accounting1.Id","Accounting1.Description","Accounting2.Id","Accounting2.Description","Accounting3.Id","Accounting3.Description","Accounting4.Id","Accounting4.Description","Article.Id","Article.Description","Equipment.Id","Equipment.Description","Component.Id","Component.Description","SparePart.Id","SparePart.Description","CostCenter.Id","CostCenter.Description","Department.Id","Department.Description","PurchaseOrder.GuidSupplier","PurchaseOrder.Status","PurchaseOrder.Id","PurchaseOrder.Description","PurchaseOrder.OrderingDate","WorkOrder.Id","WorkOrder.Description","WorkOrder.Project.ClosedDate","WorkOrder.Stage","WorkOrder.EndDate","DataOwner.Dimension1","DataOwner.Dimension2","DataOwner.Dimension3","DataOwner.Dimension4","DataOwner.Dimension5","DataOwner.DepartmentCost","DataOwner.LastDimensionCost"];(function(){return repository.getSingle(repository.apiData.purchaseOrderItem.url,$scope.isUpdate?params.Guid:"00000000-0000-0000-0000-000000000000",JSON.stringify(columns))})().then(function(response){var purchaseOrderItem=$scope.isUpdate?response.Data:params.purchaseOrderItem;$scope.model=purchaseOrderItem;var unit=_.find($scope.units,{translatedValue:$scope.model.Unit});unit&&($scope.model.Unit=unit.value),$scope.model.OrderedQuantity||($scope.model.OrderedQuantity=1),$scope.fieldRules=response.FieldRules,$scope.reload=!0,$scope.isUpdate&&"Proposal"!==$scope.model.Status&&($scope.tabs=[{heading:translationService.translate("web-purchaseOrderItemWizard-purchaseOrderItemProduct-purchaseInfo","KonteringsObjekt"),step:0},{heading:translationService.translate("web-purchaseOrderItemWizard-purchaseOrderItem-costTabel","Kostnader"),step:1}]),$scope.isWorkOrderClosedViaProject="Proposal"===$scope.model.Status&&$scope.model.WorkOrder&&$scope.model.WorkOrder.Project&&$scope.model.WorkOrder.Project.ClosedDate,setTimeout(function(){$scope.activateAutocomplete=!0,originalModel=angular.copy($scope.model)},250),$scope.isUpdate&&!$scope.restrictEdit&&($scope.model.WorkOrder&&"History"===$scope.model.WorkOrder.Stage?($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-purchaseOrderItem-restrictEditMessage-woIsHistory","Redigering og sletting er ikke tilgjengelig når arbeidsordren som denne konteringsobjektet er koblet til er hisorisk.")):$scope.model.WorkOrder&&$scope.model.WorkOrder.EndDate?($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-purchaseOrderItem-restrictEditMessage-woHasEndDate","Redigering og sletting er ikke tilgjengelig når arbeidsordren som denne konteringsobjektet er koblet til er fullført.")):$scope.model.WorkOrder&&$scope.model.WorkOrder.Project&&"Project"===$scope.model.WorkOrder.Stage&&$scope.model.WorkOrder.Project.ClosedDate?($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-purchaseOrderItem-restrictEditMessage-projectIsCompleted","Redigering og sletting er ikke tilgjengelig når prosjektet via tilknyttet arbeidsordre er fullført.")):$scope.model.IsInvoiced&&($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-purchaseOrderItem-restrictEditMessage-isInvoiced","Redigering og sletting er ikke tilgjengelig fordi denne ressursen er fakturert.")))},function(error){repository.growl(error,"danger")}),$scope.parentProperties=["Account","Accounting0","Accounting1","Accounting2","Accounting3","Accounting4","Article","Building","Component","CostCenter","DataOwner","Department","Equipment","PeriodicTask","PurchaseOrder","SparePart","Supplier","UserUpdatedBy","UserCreatedBy","WorkOrder"],$scope.getPayloadEntity=function(){var payloadEntity=angular.copy($scope.model);return $scope.parentProperties.forEach(function(field){delete payloadEntity[field]}),payloadEntity},$scope.refreshModel=function(result){$scope.parentProperties.forEach(function(field){!result[field]&&$scope.model[field]&&(result[field]=angular.copy($scope.model[field]))}),$scope.model=result},$scope.close=function(){$modalInstance.close({estimatedCost:$scope.model.UnitPrice*$scope.model.OrderedQuantity})},$scope.update=function(closeOnSave){var success=function(result){$scope.refreshModel(result),originalModel=angular.copy($scope.model),repository.growl($scope.isUpdate?translationService.translate("update-purchaseOrderItem-success","Bestilling objekt har blitt oppdatert."):translationService.translate("create-purchaseOrderItem-success","Bestilling objekt har blitt opprettet."),"success"),closeOnSave&&$scope.close()},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.purchaseOrderItem.url,$scope.getPayloadEntity()).then(success,error):repository.createSingle(repository.apiData.purchaseOrderItem.url,$scope.model).then(success,error)},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.onComponentSelect=function(component){component.Guid!==$scope.model.Component.Guid&&($scope.model.Id=component.Id,$scope.model.Description=component.Description,$scope.model.GuidComponent=component.Guid)},$scope.onSparePartSelect=function(component){sparePart.Guid!==$scope.model.sparePart.Guid&&($scope.model.Id=sparePart.Component.Id,$scope.model.Description=sparePart.Component.Description,$scope.model.GuidSparePart=component.Guid)},$scope.onArticleSelect=function(article){article.Guid!==$scope.model.Article.Guid&&($scope.model.Id=article.Id,$scope.model.Description=article.Description,$scope.model.GuidArticle=article.Guid)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-purchaseOrderItem-message","Bestilling objektet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-purchaseOrderItem-button-confirm","Ja, fjern bestilling objekt"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.purchaseOrderItem.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-purchaseOrderItem-success","Bestilling objekt ble fjernet!"),result,"success"),$scope.goBack("purchaseOrderItem.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.isFieldEnabled=function(fieldName){if($scope.restrictEdit)return!1;var isConfirmed=$scope.model.Status&&"Proposal"!==$scope.model.Status;if($scope.isWorkOrderClosedViaProject&&"EstimateAmount"!==fieldName)return!1;switch(fieldName){case"OrderedQuantity":case"UnitPrice":return!isConfirmed||$localStorage.generalOptions.CanEditPoItemAfterOrder;case"GuidSupplier":return $scope.model.PurchaseOrder?!isConfirmed&&$scope.model.PurchaseOrder&&!$scope.model.PurchaseOrder.GuidSupplier:!isConfirmed;case"BudgetDate":return!isConfirmed;case"EstimateAmount":return!0;case"GuidCostCenter":return $scope.lockCostCenter;default:return!isConfirmed}},$scope.enableSaveButton=function(){var isConfirmed=$scope.model.Status&&"Proposal"!==$scope.model.Status;return!isConfirmed||$localStorage.generalOptions.CanEditPoItemAfterOrder||!isConfirmed&&$scope.model.PurchaseOrder&&!$scope.model.PurchaseOrder.GuidSupplier},$scope.unitSetterGetter=function(val){return arguments.length?$scope.model.Unit=val:$scope.getUnitValue($scope.model.Unit)};var forceNavigation=!1;$scope.isUpdate&&($scope.$on("modal.closing",function(event,reason,closed){void 0!==reason||JSON.stringify(originalModel)===JSON.stringify($scope.model)||forceNavigation||event.preventDefault()}),$scope.$on("$stateChangeStart",function(event,toState,toParams,fromState,fromParams){JSON.stringify(originalModel)===JSON.stringify($scope.model)||forceNavigation||(event.preventDefault(),swal({title:translationService.translate("web-swal-purchaseOrderItem-notsaved","Ikke alt er lagret"),text:translationService.translate("web-swal-purchaseOrderItem-navigation-message","Du vil miste forandringene som er gjort hvis du navigerer vekk"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-purchaseOrderItem-navigation-button-confirm","Ja, naviger vekk"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt")},function(choice){window.onkeydown=null,window.onfocus=null,choice?(forceNavigation=!0,$state.go(toState,toParams)):forceNavigation=!1}))})),$scope.isUpdate&&($scope.costInfo=new function(){var me=this;this.apiData=repository.apiData.cost,this.jsPrefix=_.camelCase(this.apiData.prefix),this.canCreate=function(){return!$scope.restrictEdit&&$scope.rootScope.hasCreateAccess(this.apiData.prefix)&&"Proposal"!==$scope.model.Status},this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{UpdatedDate:"desc"},filter:{PropertyFilter:[{Property:"GuidPurchaseOrderItem",Operator:"=",Value:params.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[] ;me.listSetup.Columns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(me.apiData.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))},this.create=function(){if(me.canCreate()){var persistedData={};persistedData.GuidPurchaseOrderItem=$scope.model.Guid,repository.persistedData.setPersistedData(me.jsPrefix+".create",persistedData),$scope.$parent.navigation.go(me.jsPrefix+".create",{showPersistantData:!0},{reload:!0})}},this.update=function(item,event){$scope.$root.navigation.go("cost.edit",{guid:item.Guid})},ListService.getWebListViews(null,this.apiData.prefix,!1,null,{}).then(function(result){me.listOptions=result.listOptions,me.listSetup=result.selectedListSetup,$scope.costInfo.initTable()})}),$scope.isUpdate&&(signalR.on("UpdatedPurchaseOrderItemSums"+params.Guid,function(economyColumns){repository.getSingle(repository.apiData.purchaseOrderItem.url,params.Guid).then(function(response){JSON.parse(economyColumns).forEach(function(field){$scope.model[field]=response.Data[field]})},function(error){repository.growl(error,"danger")})}),$scope.$on("$destroy",function(){signalR.off("UpdatedPurchaseOrderItemSums"+params.Guid)}))}angular.module("Plania").controller("PurchaseOrderItemModalController",["$scope","$modalInstance","params","Repository","TranslationService","EnumService","ngTableParams","ListService","$localStorage","$state","$rootScope","SignalR",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,$modalStack,ngTableParams,$window,translationService,$localStorage,listService){$scope.isUpdate="purchaseOrderForm.edit"===$scope.navigation.current.name,$scope.model={Guid:$stateParams.guid};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.PurchaseOrderForm,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.PurchaseOrderForm,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.PurchaseOrderForm),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.PurchaseOrderForm)},columns=["Report.Name"];$scope.isUpdate&&repository.getSingle(repository.apiData.purchaseOrderForm.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.reload=!0,updateAccess()},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("web-purchaseOrderForm-update-success","Bestillingsskjema har blitt oppdatert."):translationService.translate("web-purchaseOrderForm-create-success","Bestillingsskjema har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.purchaseOrderForm.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.purchaseOrderForm.url,$scope.model).then(success,error)},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"report":return filter.FilterModel={Condition:"or",Rules:[{Property:"ReportType",Operator:"=",Value:"1"},{Property:"ReportType",Operator:"=",Value:"2"}]},filter}return filter},$scope.delete=function(){}}angular.module("Plania").controller("PurchaseOrderFormController",["$scope","Repository","$stateParams","$modal","$modalStack","ngTableParams","$window","TranslationService","$localStorage","ListService",controller])}(),function(){function controller($scope,repository,modalParams,$modalInstance,translationService,$localStorage,$window,$rootScope,ngTableParams){$scope.referenceDatas={},$scope.referenceDatasArray=[],$scope.referenceType={},$scope.currentModel={Guid:$scope.guidReferenceData},$scope.initialModel={},$scope.guidReferenceData=modalParams.guid,$scope.viewMode=!0;var referenceDataColumns=["ReferenceType.Id","ReferenceType.Description","ReferenceType.ExplanatoryText"],addToReferenceDataArray=function(referenceData){$scope.referenceDatasArray.push(referenceData),$scope.referenceDatasArray=_.sortBy($scope.referenceDatasArray,"IndexPosition")},getReferenceData=function(){repository.getSingle(repository.apiData.referenceData.url,$scope.currentModel.Guid,JSON.stringify(referenceDataColumns)).then(function(result){$scope.referenceDatas[result.Data.Guid]=result.Data,addToReferenceDataArray(result.Data),$scope.currentModel=result.Data,$scope.initialModel=result.Data,$scope.currentModel.ReferenceType&&($scope.referenceType=$scope.currentModel.ReferenceType),result.Data.GuidParent&&getReferenceDataParent()},function(error){repository.growl(error,"danger")})},getReferenceDataParent=function(){$scope.currentModel&&$scope.currentModel.GuidParent&&($scope.referenceDatas[$scope.currentModel.GuidParent]||repository.getSingle(repository.apiData.referenceData.url,$scope.currentModel.GuidParent,JSON.stringify(referenceDataColumns)).then(function(result){$scope.referenceDatas[result.Data.Guid]=result.Data,$scope.referenceDatas[result.Data.Guid].GuidChild=$scope.currentModel.Guid,addToReferenceDataArray(result.Data)},function(error){repository.growl(error,"danger")}))};$scope.onReferenceDataClick=function(model){$scope.currentModel=model,getReferenceDataParent()},$scope.onParentClick=function(parentModel){$scope.currentModel=parentModel,getReferenceDataParent()},$scope.goBackToChild=function(childModel){$scope.currentModel=childModel},modalParams.initialModel?($scope.referenceDatas[modalParams.initialModel.Guid]=modalParams.initialModel,$scope.currentModel=modalParams.initialModel,$scope.initialModel=modalParams.initialModel,addToReferenceDataArray(modalParams.initialModel),$scope.currentModel.ReferenceType&&($scope.referenceType=$scope.currentModel.ReferenceType),getReferenceDataParent()):getReferenceData(),$scope.cancel=function(){$modalInstance.dismiss("cancel")}}angular.module("Plania").controller("ReferenceDataInfoModalController",["$scope","Repository","modalParams","$modalInstance","TranslationService","$localStorage","$window","$rootScope","NgTableParams",controller])}(),function(){function controller($scope,repository,$stateParams,$timeout,translationService,$interval){$scope.isUpdate="referenceType.edit"===$scope.navigation.current.name,$scope.model={Guid:$stateParams.guid},$scope.viewMode=!!$scope.isUpdate,$scope.referenceDatas=[],$scope.selectedReferenceData=null,$scope.isRunningReferenceDataAction=!1,$scope.focus={referenceDataId:!1},$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var buildReferenceDataTree=function(referenceDatas){var treeList=[],referenceDataCopy=angular.copy(referenceDatas);return referenceDataCopy.forEach(function(referenceData){if(referenceData.ReferenceDatas||(referenceData.ReferenceDatas=[]),referenceData.GuidParent){var parentReferenceData=_.find(referenceDataCopy,{Guid:referenceData.GuidParent});parentReferenceData&&(parentReferenceData.ReferenceDatas||(parentReferenceData.ReferenceDatas=[]),parentReferenceData.ReferenceDatas.push(referenceData))}else treeList.push(referenceData)}),treeList},buildFlatList=function(referenceDatas){var flatList=[];return angular.copy(referenceDatas).forEach(function(referenceData){if(flatList.push(referenceData),referenceData.ReferenceDatas){if(referenceData.ReferenceDatas.length){var childFlatList=buildFlatList(referenceData.ReferenceDatas);flatList=flatList.concat(childFlatList)}delete referenceData.ReferenceDatas}}),flatList},getReferenceDatas=function(guidSelectedReferenceData){$scope.hasReadAccess("ReferenceData")&&($scope.isRunningReferenceDataAction=!0,repository.GetPaginated(repository.apiData.referenceData.url,0,-1,{IndexPosition:"asc"},{PropertyFilter:[{Property:"GuidReferenceType",Operator:"=",Value:$stateParams.guid}]}).then(function(response){if($scope.isRunningReferenceDataAction=!1,response){if(guidSelectedReferenceData&&($scope.selectedReferenceData=_.find(response.List,{Guid:guidSelectedReferenceData})),response.List.forEach(function(referenceData){referenceData.isDisabled=!!referenceData.DisabledFromDate}),$scope.referenceDatas.length){var flatList=buildFlatList($scope.referenceDatas);response.List.forEach(function(referenceData){var existingReferenceData=_.find(flatList,{Guid:referenceData.Guid});existingReferenceData&&(referenceData.isExpanded=existingReferenceData.isExpanded)})}$scope.referenceDatas=buildReferenceDataTree(response.List)}},function(error){$scope.isRunningReferenceDataAction=!1,repository.growl(error,"danger")}))},columns=[];$scope.isUpdate?(repository.getSingle(repository.apiData.referenceType.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data},function(error){repository.growl(error,"danger")}),getReferenceDatas()):($scope.model.Context="",$scope.$watch("model.Context",function(newVal,oldVal){newVal!==oldVal&&("BuildingType"===newVal?$scope.model.EntityType=repository.apiData.building.prefix:"ControlListCauseNotExecuted"===newVal?($scope.model.IsHierarchy=!1,$scope.model.EntityType=repository.apiData.controlList.prefix):"BusinessUnit"===newVal?delete $scope.model.EntityType:($scope.model.IsHierarchy=!1,$scope.model.EntityType=repository.apiData.deviation.prefix))})),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("web-referenceType-update-success","Referansen har blitt oppdatert."):translationService.translate("web-referenceType-create-success","Referansen har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?(repository.updateSingle(repository.apiData.referenceType.url,$scope.model).then(success,error),null!==$scope.selectedReferenceData&&!$scope.selectedReferenceData.isNew&&$scope.hasEditAccess("ReferenceData")&&$scope.updateReferenceData($scope.selectedReferenceData)):repository.createSingle(repository.apiData.referenceType.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-referenceType-delete-title","Er du sikker?"),text:translationService.translate("web-swal-referenceType-delete-message","Referansen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-referenceType-delete-confirm","Ja, fjern referansen"),cancelButtonText:translationService.translate("web-swal-referenceType-delete-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.referenceType.url,$scope.model.Guid).then(function(result){swal.close(),repository.growl(translationService.translate("web-referenceType-delete-success","Referansen har blitt slettet"),"success"),$scope.goBack("referenceType.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.onReferenceDataClick=function(referenceData){$scope.selectedReferenceData=referenceData},$scope.isReferenceDataDisabled=function(referenceData){return referenceData.DisabledFromDate&&new Date(referenceData.DisabledFromDate)<=new Date};var getHighestIndexPosition=function(){if(0===$scope.referenceDatas.length)return 0;var maxReferenceData=_.max(buildFlatList($scope.referenceDatas),function(referenceData){return referenceData.IndexPosition});return maxReferenceData?maxReferenceData.IndexPosition:0};$scope.addReferenceData=function(parentReferenceData){var index=getHighestIndexPosition();if(parentReferenceData)if(0===parentReferenceData.ReferenceDatas.length)index=parentReferenceData.IndexPosition;else{var highestChildReferenceData=_.max(parentReferenceData.ReferenceDatas,function(referenceData){return referenceData.IndexPosition});index=highestChildReferenceData?highestChildReferenceData.IndexPosition:parentReferenceData.IndexPosition}var newReferenceData={GuidReferenceType:$stateParams.guid,isNew:!0,IndexPosition:++index,parentReferenceData:parentReferenceData};parentReferenceData&&(newReferenceData.GuidParent=parentReferenceData.Guid),$scope.selectedReferenceData=newReferenceData,$scope.focus.referenceDataId=!0},$scope.createReferenceData=function(referenceData){for(var flatList=buildFlatList($scope.referenceDatas),i=0;i=referenceData.IndexPosition?flatList[i].IndexPosition=i+1:flatList[i].IndexPosition=i;var dto={ReferenceDatas:flatList,NewReferenceData:referenceData};$scope.isRunningReferenceDataAction=!0,repository.runAction(repository.apiData.referenceType.url+$scope.model.Guid+"/updateReferenceDatas",dto).then(function(result){$scope.isRunningReferenceDataAction=!1,result&&result.GuidCreatedReferenceData?(repository.growl(translationService.translate("web-referenceType-referenceData-create-success","Referansedataen har blitt opprettet."),"success"),getReferenceDatas(result.GuidCreatedReferenceData)):getReferenceDatas()},function(error){$scope.isRunningReferenceDataAction=!1,"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")})},$scope.updateReferenceData=function(referenceData){var success=function(result){$scope.isRunningReferenceDataAction=!1,repository.growl(translationService.translate("web-referenceType-referenceData-update-success","Referansedataen har blitt oppdatert."),"success"),getReferenceDatas()},error=function(error){$scope.isRunningReferenceDataAction=!1,"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};referenceData.DisabledFromDate&&(referenceData.DisabledFromDate=new Date(referenceData.DisabledFromDate).toISOString()),$scope.isRunningReferenceDataAction=!0,repository.updateSingle(repository.apiData.referenceData.url,referenceData).then(success,error)},$scope.deleteReferenceData=function(referenceData){if(referenceData.Guid){var flatList=buildFlatList($scope.referenceDatas);flatList=_.filter(flatList,function(d){return d.Guid!==referenceData.Guid});for(var i=0;ib.Id?1:0});for(var i=0;i=flatList.length)&&(startIndex=0),(void 0===endIndex||endIndex<=startIndex)&&(endIndex=flatList.length-1),($scope.model.IsHierarchy&&flatList.length!==$scope.referenceDatas.length||hasDuplicateIndexPositions(flatList))&&(startIndex=0,endIndex=flatList.length-1),!(endIndex<=startIndex)){for(var changeList=[],i=startIndex;i<=endIndex;i++){var referenceData=flatList[i];if(referenceData){referenceData.IndexPosition=i;var changeObject={Guid:referenceData.Guid,IndexPosition:referenceData.IndexPosition};$scope.model.IsHierarchy&&(changeObject.GuidParent=referenceData.GuidParent),changeObject.GuidParent&&changeObject.GuidParent===changeObject.GUID&&(changeObject.GuidParent=null),changeList.push(changeObject)}}var dto={ReferenceDatas:changeList};0!==dto.ReferenceDatas.length&&($scope.isRunningReferenceDataAction=!0,repository.runAction(repository.apiData.referenceType.url+$scope.model.Guid+"/updateReferenceDatas",dto).then(function(result){$scope.isRunningReferenceDataAction=!1,repository.growl(translationService.translate("web-referenceType-referenceData-reorderAndSave-success","Referansedata har blitt oppdatert"),"success")},function(error){$scope.isRunningReferenceDataAction=!1,getReferenceDatas(),"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")}))}}};$scope.onReferenceDataDisabledChanged=function(referenceData){referenceData.isDisabled?referenceData.DisabledFromDate=(new Date).toISOString():referenceData.DisabledFromDate=null},$scope.treeOptions={accept:function(sourceNodeScope,destNodeScope,destIndex){return $scope.model.IsHierarchy?!$scope.isRunningReferenceDataAction&&!$scope.isSaving:"uiTree"===destNodeScope.$parent.$type&&!$scope.isRunningReferenceDataAction&&!$scope.isSaving},dropped:function(event){if(!event.dest.nodesScope.$parent.nodropEnabled){var draggedDown=event.source.index>event.dest.index,startIndex=draggedDown?event.dest.index:event.source.index,endIndex=draggedDown?event.source.index:event.dest.index;if(startIndex!==endIndex||$scope.model.IsHierarchy&&event.dest.nodesScope!==event.source.nodesScope){if($scope.model.IsHierarchy){var parentModel=event.dest.nodesScope.$parent.$modelValue,currentModel=event.source.nodeScope.$modelValue;parentModel&&parentModel.Guid?currentModel.GuidParent=parentModel.Guid:currentModel.GuidParent=null}setTimeout(function(){reorderAndSave(startIndex,endIndex)},0)}}}}}angular.module("Plania").controller("ReferenceTypeController",["$scope","Repository","$stateParams","$timeout","TranslationService","$interval",controller])}(),function(){function controller($scope,$modalInstance,params,translationService){$scope.fieldRule=params.fieldRule,$scope.hasAccess=$scope.$root.userInfo.isSystemAdministrator,$scope.ok=function(){$modalInstance.close({rule:$scope.fieldRule,reset:!1})},$scope.reset=function(){$scope.fieldRule.OverriddenValidityRules=-1,$modalInstance.close({rule:$scope.fieldRule,reset:!0})},$scope.close=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("RegisteredFieldEditModalController",["$scope","$modalInstance","params","TranslationService",controller])}(),function(){function controller($scope,repository,translationService,$modal,registeredFieldService){$scope.filter={};var allFieldRules,createPrefixWithTranslation=function(prefix){return{guidPrefix:prefix,translatedValue:translationService.translate("web-enum-prefix-"+prefix,prefix)}},filterUnknownPrefix=function(prefix){return!_.isString(prefix)};repository.getSingleWithNoParameter(repository.apiData.entityTypeInfo.url).then(function(result){result&&($scope.entityTypeGroups=_.map(result,function(entityTypeGroup){return entityTypeGroup.prefixes=_.map(_.reject(entityTypeGroup.Prefixes,filterUnknownPrefix),createPrefixWithTranslation),delete entityTypeGroup.Prefixes,entityTypeGroup}))}),$scope.formatFieldName=function(fieldName){return fieldName.replace("Guid","")},$scope.editFieldRule=function(fieldRule){$modal.open({templateUrl:"app/registeredFields/registeredFieldEditModal.html",controller:"RegisteredFieldEditModalController",size:"md",resolve:{params:function(){return{fieldRule:fieldRule}}}}).result.then(function(result){result.reset?repository.deleteSingle(repository.apiData.registeredField.url,result.rule.Guid).then(function(result){registeredFieldService.getRegisteredField($scope.selectedPrefix,!0).then(function(result){allFieldRules=result,filterFieldRules(),repository.growl("Tilbakestillt","success")})}):repository.updateSingle(repository.apiData.registeredField.url,result.rule).then(function(result){repository.growl("Suksess","success")},repository.showError)})};var filterFieldRules=function(){_.each(allFieldRules,function(property){property.webTranslationSystemName="web-"+property.EntityType+"-",property.DomainFieldName.toLowerCase().startsWith("guid")?property.webTranslationSystemName+=property.DomainFieldName.substr(4):property.webTranslationSystemName+=property.DomainFieldName}),$scope.fieldRules=_.filter(allFieldRules,function(property){var show=!0,systemNameSearch=property.webTranslationSystemName;return show&&$scope.filter.searchString&&(show=property.DomainFieldName.toLowerCase().indexOf($scope.filter.searchString.toLowerCase())>-1||translationService.translate(systemNameSearch,null,null).toLowerCase().indexOf($scope.filter.searchString.toLowerCase())>-1),show&&$scope.filter.Mandatory&&(show=property.Mandatory),show&&$scope.filter.Unique&&(show=property.Unique),show&&$scope.filter.NotEditableInListView&&(show=property.NotEditableInListView),show&&$scope.filter.Hidden&&(show=property.Hidden),show&&$scope.filter.Private&&(show=property.Private),show&&$scope.filter.History&&(show=property.History),show&&$scope.filter.AvailableInListView&&(show=property.AvailableInListView),show&&$scope.filter.ExternallyHidden&&(show=property.ExternallyHidden),show})};$scope.setSelectedPrefix=function(prefix){registeredFieldService.getRegisteredField(prefix,!0).then(function(result){$scope.selectedPrefix=prefix,$scope.selectedPrefixHeader=translationService.translate("web-enum-prefix-"+prefix,prefix),allFieldRules=result,filterFieldRules()})},$scope.getModuleIcon=function(entityTypeGroupName){return repository.moduleService.getModuleIcon(entityTypeGroupName)},$scope.$watch("filter",function(newValue,oldValue){newValue!==oldValue&&filterFieldRules()},!0)}angular.module("Plania").controller("RegisteredFieldsController",["$scope","Repository","TranslationService","$modal","RegisteredFieldService",controller])}(),function(){angular.module("Plania").controller("PrintReportController",["$scope","$stateParams","$localStorage",function($scope,$stateParams,$localStorage){var reportParams=$stateParams.reportParams?$stateParams.reportParams:$localStorage.reportParams;$scope.reportName=$stateParams.reportName,$scope.reportParams=JSON.parse(reportParams),$scope.printReport=!0,$scope.reportParams&&$scope.reportParams.DisableAutomaticPrint&&($scope.printReport=!1),delete $localStorage.reportParams}])}();!function(){function controller($scope,repository){}angular.module("Plania").controller("SsrsController",["$scope","Repository",controller])}(),function(){function controller($scope,repository){var menuParams={};$scope.navigation.params.menuGuid&&(menuParams=repository.getMenuParameters($scope.navigation.params.menuGuid)),$scope.reportName=menuParams.reportName}angular.module("Plania").controller("TelerikController",["$scope","Repository",controller])}(),function(){function controller($scope,repository,$modalInstance,translationService){$scope.onFileSelect=function(file){file.length>0&&($scope.file=file[0])},$scope.dragOverClass=function($event){var items=$event.dataTransfer.items,hasFile=!1;if(items){for(var i=0;i=file.total?"success":"info"})}},$scope.downloadReportFromPlania=function(){repository.updateSingle(repository.apiData.reportMetadata.url,{Guid:"UpdateFromPlania"}).then(function(result){$modalInstance.close("Oppdatert"),$scope.isUploading=!1},function(error){repository.showError(error),$scope.isUploading=!1})},$scope.ok=function(){$modalInstance.close()},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("UpdateReportController",["$scope","Repository","$modalInstance","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,authService,$modal,$filter,translationService,enumService,$localStorage,constants,$timeout,$rootScope){$scope.update="request.edit"===$scope.navigation.current.name,$scope.model={Guid:$stateParams.guid},$scope.activateAutocomplete=!1,$scope.isDocumentsCollapsed=!0,$scope.reloadDocumentTable=!1,$scope.forceReloadDocumentTable=!1,$scope.reloadAlarmLogTable=!1,$scope.isWorkOrderCollapsed=!0,$scope.isDynamicPropertiesCollapsed=!1,$scope.reload=!1,$scope.entityCommentSearch={searchString:"",focus:!1},$scope.viewMode=!!$scope.update,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.counts={documentTotalCount:0},$scope.documents=[],$scope.alarmLogs=[],$scope.validCharacters="^(?!.*<[a-zA-ZæøåÆØÅ]+).*";var updateAccess=function(){if($scope.update){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!authService.hasEditAccess(repository.commonService.prefix.Request,checkOtherDo)||!$scope.userInfo.isSystemAdministrator&&$scope.model.IsTemplate,$scope.restrictDelete=!authService.hasDeleteAccess(repository.commonService.prefix.Request,checkOtherDo)||!$scope.userInfo.isSystemAdministrator&&$scope.model.IsTemplate}else $scope.restrictEdit=!authService.hasCreateAccess(repository.commonService.prefix.Request)||!$scope.userInfo.isSystemAdministrator&&$scope.model.IsTemplate};updateAccess();var requestColumns=["Building.Id","Building.Description","Building.Estate.Guid","Building.Estate.Id","Building.Estate.Description","Equipment.Id","Equipment.Description","Drawing.Id","Drawing.Description","Area.Id","Area.Description","Department.Id","Department.Description","ResourceGroup.Id","ResourceGroup.Description","Cause.Id","Priority.Description","ActivityCategory.Description","ActivityCategory.UseInWorkOrder","Customer.Id","Customer.Description","Person.FirstName","Person.LastName","ResponsiblePerson.FirstName","ResponsiblePerson.LastName","Priority.HasDeadline"],workOrderColumns=["Building.Id","Building.Description","ResponsiblePerson.FirstName","ResponsiblePerson.LastName"],setProperties=function(){if($scope.model.Building&&($scope.building=$scope.getEntityCaption($scope.model.Building)),$scope.model.Drawing&&($scope.drawing=$scope.getEntityCaption($scope.model.Drawing)),$scope.model.Equipment&&($scope.equipment=$scope.getEntityCaption($scope.model.Equipment)),$scope.model.Area&&($scope.area=$scope.getEntityCaption($scope.model.Area)),$scope.model.Department&&($scope.department=$scope.getEntityCaption($scope.model.Department)),$scope.model.ResourceGroup&&($scope.resourceGroup=$scope.getEntityCaption($scope.model.ResourceGroup)),$scope.model.Cause&&($scope.cause=$scope.model.Cause.Id),$scope.model.Priority&&($scope.priority=$scope.model.Priority.Description),$scope.model.Customer&&($scope.customer=$scope.getEntityCaption($scope.model.Customer)),$scope.model.Person){var personFirstName=$scope.model.Person.FirstName?$scope.model.Person.FirstName+" ":"" ;$scope.person=personFirstName+($scope.model.Person.LastName||"")}if($scope.model.ResponsiblePerson){var responsiblePersonFirstName=$scope.model.ResponsiblePerson.FirstName?$scope.model.ResponsiblePerson.FirstName+" ":"";$scope.responsiblePerson=responsiblePersonFirstName+($scope.model.ResponsiblePerson.LastName||"")}},getWorkOrder=function(){$scope.enableWebNavigation=$rootScope.userInfo.enableWebNavigation,repository.getSingle(repository.apiData.workOrder.url,$scope.model.GuidWorkOrder,JSON.stringify(workOrderColumns)).then(function(result){$scope.model.WorkOrder=result.Data,setWorkOrderProperties()})},setWorkOrderProperties=function(){$scope.model.WorkOrder.StartDate&&($scope.model.WorkOrderStartDate=$filter("date")(new Date($scope.model.WorkOrder.StartDate),"dd.mm.yyyy")),$scope.model.WorkOrder.DueDate&&($scope.model.WorkOrderDueDate=$filter("date")(new Date($scope.model.WorkOrder.DueDate),"dd.mm.yyyy")),$scope.model.WorkOrder.EndDate&&($scope.model.WorkOrderEndDate=$filter("date")(new Date($scope.model.WorkOrder.EndDate),"dd.mm.yyyy")),$scope.model.WorkOrder.ResponsiblePerson&&($scope.model.WorkOrderResponsible=$scope.model.WorkOrder.ResponsiblePerson.FirstName+" "+$scope.model.WorkOrder.ResponsiblePerson.LastName)},webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);if($scope.update)repository.getMainModel(repository.apiData.request.url,$stateParams.guid,JSON.stringify(requestColumns)).then(function(response){var responseData=response.Data;$scope.model=responseData,updateAccess(),setProperties(),$scope.model.GuidWorkOrder&&$scope.hasReadAccess("WorkOrder")&&getWorkOrder(),$scope.reloadDocumentTable=!0,$scope.reload=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250),responseData.Priority&&($scope.restrictDueDate=!!responseData.Priority.HasDeadline)},function(error){repository.growl(error,"danger")});else{var getCategoryPrefill=function(guid){var guidCategory=guid||$scope.model.GuidActivityCategory;guidCategory&&repository.getSingle(repository.apiData.activityCategory.url,guidCategory).then(function(result){$scope.model.DynamicProperty=result.Data.DynamicProperty},function(error){repository.growl(error,"danger")})},userData=repository.authService.getUserData();if(userData.guidDepartment&&($scope.model.GuidDepartment=userData.guidDepartment,$scope.model.Department={Guid:userData.guidDepartment,Name:userData.userDepartment,Caption:userData.userDepartment},$scope.department=$scope.model.Department.Caption),repository.commonService.getFilterData().selectedBuilding.Guid&&($scope.model.GuidBuilding=repository.commonService.getFilterData().selectedBuilding.Guid,$scope.building=repository.commonService.getFilterData().selectedBuilding.Name),$stateParams.showPersistantData){var persistentData=repository.persistedData.getPersistedData("request.create");persistentData&&($scope.model=persistentData.model||{},delete $scope.model.Guid,delete $scope.model.Status,delete $scope.model.Id,delete $scope.model.GuidRequest,$scope.model.GuidWorkOrder=persistentData.guidWorkOrder,$scope.building=persistentData.building,$scope.area=persistentData.area,$scope.equipment=persistentData.equipment,$scope.resourceGroup=persistentData.resourceGroup,$scope.responsiblePerson=persistentData.responsiblePerson,$scope.department=persistentData.department,$scope.activityCategory=persistentData.activityCategory,$scope.cause=persistentData.cause,$scope.priority=persistentData.priority,$scope.customer=persistentData.customer)}userData.guidPerson?$scope.model.ContactPerson=userData.personFirstName+" "+userData.personLastName:$scope.model.ContactPerson=userData.realName,$scope.model.EmailAddress=userData.email,$scope.model.Telephone=userData.phone,$scope.model.RegisteredDate=new Date,$scope.model.Status=constants.requestStatus.new,$scope.activateAutocomplete=!0,webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value&&null!==prefill.Value)switch(prefill.Property){case"Building":$scope.building=prefill.Value.Label,$scope.model.GuidBuilding=prefill.Value.Guid;break;case"Equipment":$scope.equipment=prefill.Value.Label,$scope.model.GuidEquipment=prefill.Value.Guid;break;case"Drawing":$scope.drawing=prefill.Value.Label,$scope.model.GuidDrawing=prefill.Value.Guid;break;case"Area":$scope.area=prefill.Value.Label,$scope.model.GuidArea=prefill.Value.Guid;break;case"ResourceGroup":$scope.resourceGroup=prefill.Value.Label,$scope.model.GuidResourceGroup=prefill.Value.Guid;break;case"Priority":$scope.priority=prefill.Value.Label,$scope.model.GuidPriority=prefill.Value.Guid;break;case"ActivityCategory":$scope.model.ActivityCategory={Description:prefill.Value.Label,Guid:prefill.Value.Guid},$scope.model.GuidActivityCategory=prefill.Value.Guid;break;case"Customer":$scope.customer=prefill.Value.Label,$scope.model.GuidCause=prefill.Value.Guid;break;case"Cause":$scope.cause=prefill.Value.Label,$scope.model.GuidCause=prefill.Value.Guid;break;case"ResponsiblePerson":case"Person1":$scope.responsiblePerson=prefill.Value.Label,$scope.model.GuidResponsiblePerson=prefill.Value.Guid;break;case"Person":$scope.person=prefill.Value.Label,$scope.model.GuidPerson=prefill.Value.Guid;break;case"Department":$scope.department=prefill.Value.Label,$scope.model.GuidDepartment=prefill.Value.Guid}else if("@CurrentBuilding"===prefill.Value){var building=repository.commonService.getFilterData().selectedBuilding;building.Guid&&($scope.building=building.Name,$scope.model.GuidBuilding=building.Guid)}else"@LoggedInPerson"===prefill.Value?($scope.responsiblePerson=repository.authService.getUserData().personFirstName+" "+repository.authService.getUserData().personLastName,$scope.model.GuidResponsiblePerson=repository.authService.getUserData().guidPerson):"@UserCustomer"===prefill.Value?$scope.model.GuidCustomer=repository.authService.getUserData().guidCustomer:$scope.model[prefill.Property]=prefill.Value}),getCategoryPrefill()}$scope.createRequest=function(destination){$scope.model.RegisteredDate&&($scope.model.RegisteredDate=new Date($scope.model.RegisteredDate).toISOString()),$scope.model.StartDate&&($scope.model.StartDate=new Date($scope.model.StartDate).toISOString()),$scope.model.DueDate&&($scope.model.DueDate=new Date($scope.model.DueDate).toISOString());var success=function(result){repository.growl($scope.update?"Meldingen ble lagret":"Meldingen ble opprettet","success");var guid=$scope.update?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.update?repository.updateSingle(repository.apiData.request.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.request.url,$scope.model).then(success).catch(error)},$scope.canChangeDataOwner=$localStorage.userData.canChangeRequestStatus&&$scope.hasEditAccess("Request"),$scope.changeDataOwner=function(){return $scope.model.GuidEquipment?void swal("Feil!",translationService.translate("web-swal-request-change-data-owner-has-equipment","Kan ikke skifte klient siden meldingen har tilknyttet anlegg!"),"error"):$scope.model.GuidWorkOrder?void swal("Feil!",translationService.translate("web-swal-request-change-data-owner-has-workorder","Kan ikke skifte klient siden meldingen har tilknyttet arbeidsordre!"),"error"):void swal({title:translationService.translate("web-swal-request-change-dataOwner","Bekreft skifting av klient"),text:translationService.translate("web-swal-request-change-dataOwner-approve-message","Er du sikker på at du vil skifte klient for denne meldingen?"),type:"info",showCancelButton:!0,confirmButtonColor:"#2196f3",confirmButtonText:translationService.translate("web-swal-request-change-dataOwner-confirm","Ja, Skift klient!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0,showLoaderOnConfirm:!0},function(){$modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"lg",resolve:{modalParams:function(){return{title:translationService.translate("web-request-changeDataOwner","Skift klient"),url:repository.apiData.dataOwner.url,sorting:{},filter:{},columns:[{title:translationService.translate("web-dataOwner-id"),property:"Id"},{title:translationService.translate("web-dataOwner-description"),property:"Description"}]}}}}).result.then(function(dataOwner){repository.runAction(repository.apiData.request.url+$scope.model.Guid+"/changeDataOwner/"+dataOwner.Guid).then(function(){repository.growl(translationService.translate("web-request-dataOwnerchanged","Klienten er endret"),"success"),$scope.goBack("request.edit",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})},function(error){repository.showError(error)})})},function(error){swal(translationService.translate("web-error","Feil"),error,"error")})},$scope.onActivityCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidActivityCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidActivityCategory=category.Guid},$scope.calendars={registeredDate:!1,dueDate:!1},$scope.open=function($event,calendar){$scope.calendars[calendar]=!$scope.calendars[calendar],$event.preventDefault(),$event.stopPropagation()},$scope.sendEmail=function(){var onNewDocument=($scope.documents.concat($scope.model.Images),function(){$scope.forceReloadDocumentTable=!1,$timeout(function(){$scope.forceReloadDocumentTable=!0},250)}),onNewImage=function(){repository.getMainModel(repository.apiData.request.url,$stateParams.guid).then(function(response){$scope.model.Images=response.Data.Images})};$modal.open({templateUrl:"app/common/views/emailModal.html",controller:"EmailModalController",size:"lg",resolve:{params:function(){return{entity:"Request",model:$scope.model,prefillSubjectWithCaption:!0,onNewDocument:onNewDocument,onNewImage:onNewImage}}}}).result.then(function(){$scope.reloadAlarmLogTable=!0})},$scope.onPrioritySelect=function(priority){priority?($scope.model.GuidPriority=priority.Guid,priority.HasDeadline?($scope.model.DueDate=enumService.getTimeUnitDate(new Date,priority.DeadlinePeriodUnit,priority.DeadlinePeriodNumber),$scope.restrictDueDate=!0):$scope.restrictDueDate=!1):($scope.model.GuidPriority=null,$scope.restrictDueDate=!1)},$scope.removeRequest=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-request-message","Meldingen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-request-button-confirm","Ja, fjern meldingen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.request.url,$scope.model.Guid).then(function(){swal.close(),$scope.goBack("request.list",{menuGuid:$scope.navigation.params.menuGuid}),repository.growl(translationService.translate("web-request-growl-deleted","Meldingen har blitt fjernet"),"success")})})},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidEquipment="",$scope.equipment="",$scope.model.GuidArea="",$scope.area=""),$scope.model.GuidBuilding=building.Guid},$scope.onEquipmentSelect=function(equipment){if(!equipment)return void($scope.model.GuidEquipment="");$scope.model.GuidEquipment=equipment.Guid,$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=equipment.GuidBuilding,$scope.building=equipment.Building.Caption),equipment.GuidArea&&($scope.model.GuidArea=equipment.GuidArea,$scope.area=equipment.Area.Caption)},$scope.onAreaSelect=function(area){if(!area)return $scope.model.GuidArea="",void($scope.area="");$scope.model.GuidArea=area.Guid,$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=area.GuidBuilding,$scope.building=area.Building.Id+" - "+area.Building.Description)},$scope.autoCompleteFilter=function(filterName){switch(filterName){case"equipment":return{GuidBuilding:$scope.model.GuidBuilding,IsMaintainable:1,PropertyFilter:[{Property:"IsTemplate",Operator:"=",Value:!1}]};case"area":return{GuidBuilding:$scope.model.GuidBuilding,GuidDrawing:$scope.model.GuidDrawing};case"drawing":return{GuidBuilding:$scope.model.GuidBuilding};case"person":return{};case"responsiblePerson":return{GuidBuildingResponsible:$scope.model.GuidBuilding};case"department":return{};case"priority":return{PropertyFilter:[{Property:"EntityType",Operator:"<>",Value:"Condition"}]};case"cause":return{};case"resourceGroup":return{PropertyFilter:[{Property:"DoesMaintenanceTasks",Operator:"=",Value:"true"}]};case"activityCategory":return{PropertyFilter:[{Property:"UseInRequest",Operator:"=",Value:"true"},{Property:"IsAbstract",Operator:"=",Value:"0"}]}}},$scope.accessToCreateWorkOrder=repository.authService.hasCreateAccess(repository.commonService.prefix.WorkOrder),$scope.accessToReadWorkOrder=repository.authService.hasReadAccess(repository.commonService.prefix.WorkOrder),$scope.createWorkOrder=function(){var reference=$scope.model.ContactPerson;$scope.model.Telephone&&(reference=reference+" - "+$scope.model.Telephone);var defaultText=$scope.model.ExplanatoryText;$scope.model.Location&&(defaultText=$scope.model.Location+" - "+defaultText);var workorder={model:angular.copy($scope.model),guidEstate:$scope.model.Building.Estate?$scope.model.Building.Estate.Guid:null,estate:$scope.model.Building.Estate?$scope.getEntityCaption($scope.model.Building.Estate):null,guidBuilding:$scope.model.GuidBuilding,building:$scope.building,guidArea:$scope.model.GuidArea,area:$scope.area,guidEquipment:$scope.model.GuidEquipment,equipment:$scope.equipment,guidRequest:$scope.model.Guid,resourceGroup:$scope.resourceGroup,responsiblePerson:$scope.responsiblePerson,department:$scope.department,cause:$scope.model.Cause?$scope.model.Cause.Id:null,priority:$scope.priority,defaultDescription:$scope.model.Description,defaultText:defaultText,defaultReference:reference,guidCustomer:$scope.model.GuidCustomer};if($scope.model.ActivityCategory&&!0===$scope.model.ActivityCategory.UseInWorkOrder){for(var countCombo=1;countCombo<=40;countCombo++){var fieldCombo="Combo"+String(countCombo).padStart(2,"0");$scope.model[fieldCombo]&&(workorder[fieldCombo]=$scope.model[fieldCombo])}for(var countDate=1;countDate<=30;countDate++){var fieldDate="Date"+String(countDate).padStart(2,"0");$scope.model[fieldDate]&&(workorder[fieldDate]=$scope.model[fieldDate])}for(var countText=1;countText<=30;countText++){var fieldText="Text"+String(countText).padStart(2,"0");$scope.model[fieldText]&&(workorder[fieldText]=$scope.model[fieldText])}for(var countNumber=1;countNumber<=10;countNumber++){var fieldNumber="Number"+String(countNumber).padStart(2,"0");$scope.model[fieldNumber]&&(workorder[fieldNumber]=$scope.model[fieldNumber])}}else workorder.model.GuidActivityCategory="";repository.persistedData.setPersistedData("workOrder.create",workorder),$scope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})},$scope.addExistingWorkOrder=function(){$modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"lg",resolve:{modalParams:function(){var propertyFilter=[{Property:"GuidRequest",Operator:"=",Value:""},{Property:"stage",Operator:"<>",Value:"2"}];return $scope.model.GuidBuilding&&propertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:$scope.model.GuidBuilding,allowToggle:!0,filterValue:$scope.building,isDisabled:!1}),$scope.model.GuidEquipment&&propertyFilter.push({Property:"GuidEquipment",Operator:"=",Value:$scope.model.GuidEquipment,allowToggle:!0,filterValue:$scope.equipment,isDisabled:!1}),$scope.model.GuidArea&&propertyFilter.push({Property:"GuidArea",Operator:"=",Value:$scope.model.GuidArea,allowToggle:!0,filterValue:$scope.area,isDisabled:!1}),{title:translationService.translate("web-request-addExistingWorkOrder","Legg til eksisterende arbeidsordre"),url:repository.apiData.workOrder.url,sorting:{},filter:{PropertyFilter:propertyFilter},columns:[{title:translationService.translate("web-workorder-id"),property:"Id"},{title:translationService.translate("web-workorder-type"),property:"Type"},{title:translationService.translate("web-building-id"),property:"Building.Id"},{title:translationService.translate("web-building-description"),property:"Building.Description"},{title:translationService.translate("web-equipment-description"),property:"Equipment.Description"},{title:translationService.translate("web-workorder-description"),property:"Description"},{title:translationService.translate("web-workorder-startdate"),property:"StartDate",PropertyType:"date"},{title:translationService.translate("web-workorder-duedate"),property:"DueDate",PropertyType:"date"},{title:translationService.translate("web-workorder-enddate"),property:"EndDate",PropertyType:"date"}]}}}}).result.then(function(item){$scope.model.GuidWorkOrder=item.Guid,$scope.createRequest("request.edit")},function(msg){})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("RequestController",["$scope","Repository","$stateParams","authService","$modal","$filter","TranslationService","EnumService","$localStorage","Constants","$timeout","$rootScope",controller])}(),function(){function controller($scope,repository,params,modalInstance,translationService){var columns=["Description","CreationDate","Status"],filter={};params.guidArea&&(filter.FilterModel={Condition:"and",Rules:[{Condition:"or",Rules:[{Property:"Status",Operator:"=",Value:"0"},{Property:"Status",Operator:"=",Value:"1"}]},{Property:"WorkOrder.EndDate",Operator:"=",Value:""},{Property:"GuidArea",Operator:"=",Value:params.guidArea}]}),$scope.canNavigate=function(){return repository.authService.hasReadAccess(repository.commonService.prefix.Request)},$scope.goToRequest=function(request){$scope.navigation.go("request.edit",{guid:request.Guid}),$scope.ok()},repository.GetPaginated(repository.apiData.request.url,0,100,{CreationDate:"desc"},filter,null,JSON.stringify(columns)).then(function(result){$scope.requests=result.List}),$scope.ok=function(){modalInstance.close()},$scope.cancel=function(){modalInstance.dismiss("cancel")}}angular.module("Plania").controller("RequestModalController",["$scope","Repository","params","$modalInstance","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,ngTableParams,$modal,listService){$scope.isUpdate="resourceGroup.edit"===$scope.navigation.current.name;var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.ResourceGroup,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ResourceGroup,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.ResourceGroup),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ResourceGroup)};$scope.isUpdate&&repository.getSingle(repository.apiData.resourceGroup.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess()},function(error){repository.growl(error,"danger")}),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-resourceGroup-success","Ressursgruppe har blitt oppdatert."):translationService.translate("create-resourceGroup-success","Ressursgruppen har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.resourceGroup.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.resourceGroup.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-resourceGroup-message","Ressursgruppen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-resourceGroup-button-confirm","Ja, fjern Ressursgruppen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.resourceGroup.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-resourceGroup-success","Ressursgruppen ble fjernet!"),result,"success"),$scope.goBack("resourceGroup.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("ResourceGroupController",["$scope","Repository","$stateParams","TranslationService","ngTableParams","$modal","ListService",controller])}(),function(){function controller($scope,$modalInstance,translationService){$scope.scheduledJobTypes=[{icon:"square-sliders",colour:"gray",title:translationService.translate("web-scheduledJob-type-MedicalClassificationExport","Rom klassifisering"),description:translationService.translate("web-scheduledJob-type-MedicalClassificationExport-description","Eksport av romklassifikasjon - testmiljø"),model:{Description:"Eksport av romklassifikasjon - testmiljø",Type:"MedicalClassificationExport",Params:{Url:"https://apitest.klassifikasjonssystemet.no",Version:"3.1.4"}}},{icon:"download",colour:"blue",title:translationService.translate("web-scheduledJob-type-ftpConnector","Overfør fil fra SFTP katalog"),description:translationService.translate("web-scheduledJob-type-ftpConnector-description","Import/eksport av data med SFTP"),model:{Description:"Import eller eksport av data ved hjelp av SFTP server",Type:"FtpConnector",Params:{Port:22,JobId:-1}}},{icon:"folder",colour:"cyan",title:translationService.translate("web-scheduledJob-type-fileConnector","Overfør fil fra server"),description:translationService.translate("web-scheduledJob-type-fileConnector-description","Import eller eksport fra lokal mappe eller nettverksdisk"),model:{Description:"Overfør fil fra lokal disk eller nettverk",Type:"FileConnector",Params:{JobId:-1,DeleteSourceFile:!1}}}],$scope.save=function(jobType){$modalInstance.close(jobType.model)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CreateScheduledJobModalController",["$scope","$modalInstance","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,ngTableParams,$modal,translationService,authService,listService,$interval,$localStorage){$scope.isUpdate="scheduledJob.edit"===$scope.navigation.current.name,$scope.viewMode=!!$scope.isUpdate,$scope.model={Guid:$stateParams.guid},$scope.originalModel=angular.copy($scope.model),$scope.activateAutocomplete=!1,$scope.viewModel={},$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var systemJobNames=["UpdateWorkOrderSums","UpdateProjectSums","UpdatePlaniaEconomyFields","UpdateGeneralOptionsCache","UpdateCustomerExpectedAnonymizationDates","UpdateCleaningTasks","UpdateAccessDomainCache","TwoFactorTokenMaintenance","SendUsageReportToPlania","SendSettingInformationToPlania","SendLicenseToPlania","RemoveOverdueExitCleaningTask","RemoveExpiredRefreshTokens","RemoveExpiredJobExecution","FtpConnectorRegistration","FileConnectorRegistration","DeleteUnusedHousingCustomers","BimsyncPoller","AnonymizeHousingCustomers","AggregateCleaningCompletions"],updateAccess=function(){if($scope.isUpdate){var checkOtherDo=!1;if($scope.restrictEdit=!authService.hasEditAccess(repository.commonService.prefix.ScheduledJob,checkOtherDo),$scope.restrictDelete=!authService.hasDeleteAccess(repository.commonService.prefix.ScheduledJob,checkOtherDo),$scope.model&&$scope.model.Type){var isAllowedDeletion=!1;"FtpConnector"!==$scope.model.Type&&"AzureADSync"!==$scope.model.Type&&"MedicalClassificationExport"!==$scope.model.Type&&"FileConnector"!==$scope.model.Type||(isAllowedDeletion=!0),$scope.restrictDelete=!isAllowedDeletion}}else $scope.restrictEdit=!authService.hasCreateAccess(repository.commonService.prefix.ScheduledJob)},getFromServer=function(){repository.getSingle(repository.apiData.scheduledJob.url,$stateParams.guid).then(function(response){$scope.model=response.Data,$scope.model&&($scope.model.Params=JSON.parse($scope.model.Parameters),$scope.integrationDataJobIds&&($scope.selectedJobId=_.find($scope.integrationDataJobIds,{Id:$scope.model.Params.JobId}))),updateAccess(),$scope.isSystemJob=systemJobNames.includes($scope.model.Id),$scope.reload=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250),$scope.originalModel=angular.copy($scope.model)},function(error){repository.growl(error,"danger")})},initNew=function(){updateAccess(),$stateParams.scheduledJobModel?$scope.model=$stateParams.scheduledJobModel:(repository.growl(translationService.translate("web-scheduledJob-create-missingModel","Du må velge type bakgrunnsjobb for å kunne opprette ny")),$scope.navigation.go("scheduledJob.list",{menuGuid:$scope.navigation.params.menuGuid}))};$stateParams.guid?getFromServer():(initNew(),$scope.originalModel=angular.copy($scope.model)),repository.getWithUrlParameter(repository.apiData.integrationDataJobId.url).then(function(response){$scope.integrationDataJobIds=response.Data,$scope.model.Params&&($scope.selectedJobId=_.find($scope.integrationDataJobIds,{Id:$scope.model.Params.JobId}))},function(error){repository.growl(error,"danger")}),$scope.setSelectedJobId=function(jobId){$scope.model.Params.JobId=jobId.Id,$scope.selectedJobId=jobId},$scope.update=function(destination){var success=function(result){repository.growl(translationService.translate("web-swal-scheduledJob-savedOk","Bakgrunnsjobben er lagret"),"success"),$scope.goBack(destination,{guid:result.Guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){repository.growl(error,"danger")},modelToSave=angular.copy($scope.model);modelToSave.Parameters=JSON.stringify(modelToSave.Params),delete modelToSave.Params,$scope.isUpdate?repository.updateSingle(repository.apiData.scheduledJob.url,modelToSave).then(success).catch(error):repository.createSingle(repository.apiData.scheduledJob.url,modelToSave).then(success).catch(error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-scheduledJob-message","Bakgrunnsjobben vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-scheduledJob-button-confirm","Ja, slett bakgrunnsjobben!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.scheduledJob.url,$scope.model.Guid).then(function(result){swal("Suksess!",translationService.translate("web-swal-scheduledJob-success","Bakgrunnsjobben ble fjernet!"),"success"),repository.growl("Bakgrunnsjobben har blitt fjernet","success"),$scope.goBack("scheduledJob.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.runJob=function(){if(!$scope.isSavingRunJob){var requestBody={GuidScheduledJob:$scope.model.Guid};$scope.isSavingRunJob=!0,repository.createSingle(repository.apiData.scheduledJobStart.url,requestBody).then(function(result){$scope.executionTable.reload(),repository.growl(translationService.translate("web-swal-scheduledJobExecution-savedOk","Kjøring av bakgrunnsjobben er startet"),"success"),$scope.isSavingRunJob=!1}).catch(function(error){$scope.isSavingRunJob=!1,repository.growl(error,"danger")})}},$scope.executionColumns=[{Position:1,Title:translationService.translate("web-scheduledJobExecution-jobId","Jobb ID"),Property:"JobId",PropertyType:"string"},{Position:2,Title:translationService.translate("web-scheduledJobExecution-creationDate","Opprettet"),Property:"CreationDate",PropertyType:"date"},{Position:3,Title:translationService.translate("web-scheduledJobExecution-updatedDate","Oppdatert"),Property:"UpdatedDate",PropertyType:"date"},{Position:4,Title:translationService.translate("web-scheduledJobExecution-status","Status"),Property:"Status",PropertyType:"string"},{Position:5,Title:translationService.translate("web-scheduledJobExecution-logOutput","Logg"),Property:"LogOutput",PropertyType:"string"},{Position:6,Title:translationService.translate("web-scheduledJobExecution-userCreatedBy-realName","Startet av"),Property:"UserCreatedBy.RealName",PropertyType:"string"}],$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"userGroup":return filter.FilterModel={Condition:"and",Rules:[{Property:"IsUserGroup",Operator:"=",Value:!0}]},filter}return filter},$scope.executionTable=new ngTableParams({page:1,count:10,sorting:{CreationDate:"desc"},filter:{PropertyFilter:[{Property:"GuidScheduledJob",Operator:"=",value:$scope.model.Guid}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=_.map($scope.executionColumns,"Property");repository.GetPaginated(repository.apiData.scheduledJobExecution.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.executionTable.settings().total=result.TotalCount,$scope.executionTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.goToExecutionEdit=function(execution){$scope.navigation.go("scheduledJobExecution.edit",{guid:execution.Guid},{reload:!0})};var reloadTableInterval=$interval(function(){$scope.isUpdate&&$scope.executionTable.reload()},1e4);$scope.$on("$destroy",function(){angular.isDefined(reloadTableInterval)&&$interval.cancel(reloadTableInterval)}),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.hstep=1,$scope.mstep=5,$scope.synchronizePersonWithLdap=$localStorage.generalOptions.SynchronizePersonWithLdap,$scope.azureSyncDropdownOptions={ldapGuid:["Id"],username:["UserPrincipalName","OnPremisesSamAccountName","OnPremisesUserPrincipalName","MailNickname","Mail","OtherMails"],realName:["DisplayName"],userEmail:["Mail","OtherMails"],phoneNumber:["BusinessPhones","MobilePhone"],ldapDn:["OnPremisesDistinguishedName"],firstName:["GivenName"],lastName:["Surname"],personEmail:["Mail","OtherMails"],telephoneWork:["BusinessPhones","MobilePhone"],cellphone:["BusinessPhones","MobilePhone"],uniquePlaniaFields:["Username","Email","RealName","PhoneNumber"],uniqueAzureFields:["UserPrincipalName","OnPremisesSamAccountName","OnPremisesUserPrincipalName","MailNickname","Mail","OtherMails","DisplayName","BusinessPhones","MobilePhone"]}} angular.module("Plania").controller("ScheduledJobController",["$scope","Repository","$stateParams","ngTableParams","$modal","TranslationService","authService","ListService","$interval","$localStorage",controller])}(),function(){function controller($scope,repository,$stateParams){$scope.isUpdate="scheduledJob.edit"===$scope.navigation.current.name,$scope.viewMode=!!$scope.isUpdate,repository.getSingle(repository.apiData.scheduledJobExecution.url,$stateParams.guid).then(function(response){$scope.model=response.Data},function(error){repository.growl(error,"danger")})}angular.module("Plania").controller("ScheduledJobExecutionController",["$scope","Repository","$stateParams",controller])}(),function(){function SignalR(config,$rootScope){var factory={isInitialized:!1};return factory.connection=$.hubConnection(config.baseUrl+"signalr"),factory.proxy=factory.connection.createHubProxy("planiaHub"),factory.on=function(eventName,callback){factory.proxy.on(eventName,function(result){$rootScope.$apply(function(){callback&&callback(result)})})},factory.off=function(eventName){factory.proxy.off(eventName)},factory.invoke=function(methodName,callback){factory.proxy.invoke(methodName).done(function(result){$rootScope.$apply(function(){callback&&callback(result)})})},factory.setQs=function(parameters){factory.connection.qs=parameters},factory.start=function(success,fail,params){if(!factory.isInitialized)return params&&(factory.connection.qs=params),factory.connection.start().done(function(){factory.isInitialized=!0,success&&success()}).fail(function(){factory.isInitialized=!1,fail&&fail()})},factory.stop=function(){factory.isInitialized=!1,factory.connection.stop()},factory}angular.module("Plania").factory("SignalR",["config","$rootScope",SignalR])}(),function(){function SignalRconfig(authService,config,$httpParamSerializer,generalOptionsService,translationService,$rootScope,$localStorage,$state,signalR){var factory={};return signalR.on("reloadPage",function(){$state.reload()}),signalR.on("refreshGeneralOptions",function(){generalOptionsService.refreshGeneralOptions()}),signalR.on("refreshTranslations",function(msg){if(msg){var data=JSON.parse(msg);translationService.setLanguageEntry(data.Locale+data.SystemName.toLowerCase(),data.TranslatedValue)}else translationService.getTranslations()}),factory.setEditPageListener=function(to,toParams,from,fromParams){$localStorage.generalOptions.NotifyObjectUpdated&&($rootScope.editPageHasBeenUpdatedMessage=null,from.name.includes(".edit")&&signalR.off("updatedPage"+fromParams.guid),to.name.includes(".edit")&&signalR.on("updatedPage"+toParams.guid,function(msg){var data=JSON.parse(msg);$rootScope.editPageHasBeenUpdatedMessage=data}))},signalR.connection.disconnected(function(){authService.getUserData().isAuthenticated&&setTimeout(function(){authService.getUserData().isAuthenticated&&authService.refreshAuthentication().then(function(result){"invalid"!==result&&(signalR.setQs({guidUser:authService.getUserData().guidUser,fingerprint:config.fingerprint}),signalR.connection.start())})},5e3)}),factory}angular.module("Plania").factory("SignalRconfig",["authService","config","$httpParamSerializer","GeneralOptionsService","TranslationService","$rootScope","$localStorage","$state","SignalR",SignalRconfig])}(),function(){function controller($scope,repository,constants,translationService,$localStorage,ngTableParams){function initSmsConfiguration(){$scope.model={},$scope.smsConfiguration={},repository.getSingleWithNoParameter(repository.apiData.smsProvider.url).then(function(result){$scope.smsConfiguration=result},function(error){"Ingen data funnet"===error?$scope.newConfiguration=!0:repository.growl(error,"danger")})}function isValid(){var valid=!0;return $scope.smsConfiguration.SenderId.length>$scope.maxSenderLength&&(valid=!1,repository.growl(translationService.translate("web-smsprovider-sendertoolong","Lengde på avsender navn kan ikke være lenger enn")+" "+$scope.maxSenderLength,"danger")),valid}$scope.maxRecommendedSmsLength=64,$scope.maxSenderLength=11,initSmsConfiguration(),$scope.setDefaultConfiguration=function(){$scope.newConfiguration=!1;var defaultConfig=constants.defaultSmsConfiguration;$scope.smsConfiguration.ServicePlanId=defaultConfig.ServicePlanId,$scope.smsConfiguration.AccessToken=defaultConfig.AccessToken,$scope.smsConfiguration.SenderId=defaultConfig.SenderId,$scope.smsConfiguration.Url=defaultConfig.Url,$scope.smsConfiguration.TemplateText=defaultConfig.TemplateText},$scope.save=function(){$scope.newConfiguration=!1,$scope.model=$scope.smsConfiguration,isValid()&&repository.updateSingle(repository.apiData.smsProvider.url,$scope.model).then(function(result){repository.growl("Lagring fullført","success")},function(error){repository.growl(error,"danger")})},$scope.delete=function(){if($localStorage.generalOptions.TwoFactorAuthenticationOption>0)return void swal(translationService.translate("web-smsprovider-cannotdisable","Kan ikke slette konfigurasjon når tofaktor er påskrudd, vennligst skru den av i kundeprofilen først."),"","error");swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-smsprovider-deletemessage","Konfigurasjonen slettes permanent!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-smsprovider-deletemessage-confirm","Ja, fjern konfigurasjon"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.smsProvider.url,$scope.model.Provider).then(function(result){repository.growl("Sletting fullført","success"),initSmsConfiguration()},function(error){repository.growl(error,"danger")})})},$scope.hasReadAccess("TwoFactorToken")&&($scope.smsTable=new ngTableParams({page:1,count:50,sorting:{CreationDate:"desc"}},{total:0,filterDelay:10,counts:[50,100,200],getData:function($defer,params){var columns=["PhoneNumber","CreationDate","Status","User.Username","DeviceRemembered"];repository.GetPaginated(repository.apiData.twoFactorToken.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.smsTable.settings().total=result.TotalCount,$scope.smsTable.settings().filterDelay=500,$defer.resolve(result.List)})}})),$scope.smsTableGetStatusColor=function(status){switch(status){case"New":return"text-info";case"Used":return"text-success";case"NotUsed":return"text-warning";case"Failed":return"text-danger"}return null}}angular.module("Plania").controller("SmsProviderController",["$scope","Repository","Constants","TranslationService","$localStorage","ngTableParams",controller])}(),function(){function controller($scope,repository,$modalInstance,$localStorage,registeredFieldService,translationService,$q){$scope.sparePart={},$scope.component={},$scope.componentSupplier={},$scope.generalOptions=$localStorage.generalOptions;var mandatoryComponentFields=[];registeredFieldService.getRegisteredField(repository.commonService.prefix.Component).then(function(result){var mandatoryFields=_.filter(result,function(o){return("Id"!==o.DomainFieldName||!$scope.generalOptions.UseComponentCounter)&&o.Mandatory}),mappedLabels=_.map(mandatoryFields,function(o){return{FieldName:o.DomainFieldName,translatedValue:translationService.translate("web-component-"+o.DomainFieldName.replace("Guid","")).replace(":","")}});mandatoryComponentFields=mappedLabels});var mandatoryComponentXSupplierFields=[];registeredFieldService.getRegisteredField(repository.commonService.prefix.ComponentXSupplier).then(function(result){var mandatoryFields=_.filter(result,function(o){if("GuidComponent"===o.DomainFieldName)return!1}),mappedLabels=_.map(mandatoryFields,function(o){return{FieldName:o.DomainFieldName,translatedValue:translationService.translate("web-componentXSupplier-"+o.DomainFieldName.replace("Guid","")).replace(":","")}});mandatoryComponentXSupplierFields=mappedLabels});var mandatorySparePartFields=[];registeredFieldService.getRegisteredField(repository.commonService.prefix.SparePart).then(function(result){var mandatoryFields=_.filter(result,function(o){return"GuidComponent"!==o.DomainFieldName&&("GuidComponentXSupplier"!==o.DomainFieldName&&o.Mandatory)}),mappedLabels=_.map(mandatoryFields,function(o){return{FieldName:o.DomainFieldName,translatedValue:translationService.translate("web-sparePart-"+o.DomainFieldName.replace("Guid","")).replace(":","")}});mandatorySparePartFields=mappedLabels});var createComponent=function(){var deferred=$q.defer();return $scope.component.Guid?$.Deferred().resolve().promise():(repository.createSingle(repository.apiData.component.url,$scope.component).then(function(result){$scope.component.Guid=result.Guid,$scope.sparePart.GuidComponent=result.Guid,$scope.componentSupplier.GuidComponent=result.Guid,deferred.resolve()},function(error){repository.showError(error),deferred.reject()}),deferred.promise)},createComponentXSupplier=function(){var deferred=$q.defer();return $scope.componentSupplier.Guid?$.Deferred().resolve().promise():($scope.componentSupplier.Price&&($scope.componentSupplier.Price=$scope.componentSupplier.Price.replace(",",".")),repository.createSingle(repository.apiData.componentSupplier.url,$scope.componentSupplier).then(function(result){$scope.componentSupplier.Guid=result.Guid,$scope.sparePart.GuidComponentXSupplier=result.Guid,deferred.resolve()},function(error){repository.showError(error),deferred.reject()}),deferred.promise)},createSparePart=function(){repository.createSingle(repository.apiData.sparePart.url,$scope.sparePart).then(function(result){repository.growl("Reservedel har blitt opprettet","success"),repository.commonService.setLastRegisterGuid("sparePart.edit",result.Guid),$modalInstance.close(result)},function(error){repository.showError(error)})},validateMandatoryFields=function(){for(var i=0;i
    Vil du deaktivere reservedelen?",type:"error",html:!0,showCancelButton:!0,confirmButtonText:"Deaktiver",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.IsDeactivated=!0,$scope.update("sparePart.list"))})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("SparePartsController",["$scope","Repository","$stateParams","TranslationService","ngTableParams","$modal","ListService",controller])}(),function(){function controller($scope,params,repository,$modalInstance,$localStorage){$scope.model={GuidSparePart:params.GuidSparePart,WithdrawalDate:(new Date).toISOString()},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidEquipment="",$scope.model.Equipment=null),$scope.model.GuidBuilding=building.Guid},$scope.onEquipmentSelect=function(equipment){if(!equipment)return void($scope.model.GuidEquipment="");$scope.model.GuidEquipment=equipment.Guid,$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=equipment.GuidBuilding,$scope.model.Building=equipment.Building)},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"building":return filter;case"equipment":return filter={GuidBuilding:$scope.model.GuidBuilding},filter.PropertyFilter=[{Property:"IsTemplate",Operator:"=",Value:!1}],filter}},$scope.save=function(){$modalInstance.close($scope.model)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("SparePartObjectWithdrawalModalController",["$scope","params","Repository","$modalInstance","$localStorage",controller])}(),function(){function controller($scope,params,$modalInstance){$scope.countingItem=params.countingItem,$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CountingItemCommentModalController",["$scope","params","$modalInstance",controller])}(),function(){function controller($scope,repository,params,$modalInstance){$scope.model={},$scope.notUniqueName=!1,params.sparePartCountingList&&($scope.model.Guid=params.sparePartCountingList.Guid,$scope.model.Id=params.sparePartCountingList.Id),$scope.model=params.sparePartCountingList?params.sparePartCountingList:{},!params.sparePartCountingList&¶ms.sparePartCounting&&($scope.model.GuidSparePartCounting=params.sparePartCounting.Guid);var success=function(result){repository.growl($scope.model.Guid?"Varetellingsliste oppdatert":"Varetellingsliste opprettet","success"),params.sparePartCounting?$modalInstance.close(result.Guid):$modalInstance.close($scope.model)},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.update=function(){if(!params.sparePartCountingList&&_.find(params.listNames,function(o){return o===$scope.model.Id}))return void($scope.notUniqueName=!0);$scope.model.Guid?repository.updateSingle(repository.apiData.sparePartCountingList.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.sparePartCountingList.url,$scope.model).then(success,error)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CreateSparePartCountingListModalController",["$scope","Repository","params","$modalInstance",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,$modal,$timeout,$q){$scope.isUpdate="sparePartCounting.edit"===$scope.navigation.current.name,$scope.model={},$scope.viewMode=!!$scope.isUpdate,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.search={},$scope.selectedDataType="SparePartCountingItem",$scope.sortingProperty="SparePart.Location",$scope.sortingDirection="desc",$scope.sorting={},$scope.sorting[$scope.sortingProperty]=$scope.sortingDirection,$scope.countingItemCount=25,$scope.sparePartCountingLists=[];var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.SparePartCounting,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.SparePartCounting,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.SparePartCounting),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.SparePartCounting)};$scope.getGraphColor=function(list,type){var progress=$scope.getPercentCompleted(list);return 100===progress?"color"===type?"#4CAF50":"c-green":progress<20?"color"===type?"#F44336":"c-gray":"color"===type?"#00bcd4":"c-gray"},$scope.setSelectedCountingList=function(list){$scope.selectedCountingList=list,$scope.loadCountingListItems(),$scope.loadCountingListUsers()},$scope.setSelectedDataType=function(type){$scope.selectedDataType=type};var getCountingItemComments=function(){var commentFilter={PropertyFilter:[{Property:"SparePartCountingList.GuidSparePartCounting",Operator:"=",Value:$stateParams.guid},{Property:"Comment",Operator:"<>",Value:""}]};repository.GetPaginated(repository.apiData.sparePartCountingItem.url,0,50,{},commentFilter,"",JSON.stringify(["SparePart.Component.GuidImage","SparePart.Component.Id","SparePart.Component.Description","CountedDate","Comment"])).then(function(result){$scope.commentCount=result.TotalCount,$scope.commentItems=result.List})};if($scope.sortingProperties=[{value:"SparePart.Location",label:"Plassering",type:"string"},{value:"SparePart.Component.Id",label:"ID",type:"string"},{value:"QuantityDeviation",label:"Avvik",type:"number"},{value:"CountedDate",label:"Tidspunkt",type:"date"}],$scope.setSorting=function(item){$scope.sortingProperty===item.value?($scope.sortingDirection="desc"===$scope.sortingDirection?"asc":"desc",$scope.sorting[$scope.sortingProperty]=$scope.sortingDirection):($scope.sorting={},$scope.sortingProperty=item.value,$scope.sortingDirection="desc",$scope.sorting[$scope.sortingProperty]=$scope.sortingDirection),$scope.loadCountingListItems()},$scope.isUpdate){repository.getSingle(repository.apiData.sparePartCounting.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess()},function(error){repository.growl(error,"danger")});var params={page:1,count:25,sorting:{CreationDate:"asc"},filter:{PropertyFilter:[{Property:"GuidSparePartCounting",operator:"=",value:$stateParams.guid}]}};repository.GetPaginated(repository.apiData.sparePartCountingList.url,params.page-1,params.count,params.sorting,params.filter).then(function(result){$scope.sparePartCountingLists=result.List,$scope.sparePartCountingLists.length>0&&$scope.setSelectedCountingList($scope.sparePartCountingLists[0])},function(error){repository.growl(error,"danger")}),getCountingItemComments()}$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-sparepartcounting-success","Varetellingen har blitt oppdatert."):translationService.translate("create-sparePartcounting-success","Varetellingen har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.sparePartCounting.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.sparePartCounting.url,$scope.model).then(success,error)},$scope.completeCounting=function(){swal({title:translationService.translate("web-swal-sparePartcounting-complete-title","Fullfør varetellingen?"),text:translationService.translate("web-swal-sparePartcounting-complete-message","Varetellingen vil bli merket som ferdig, og kan ikke lenger endres!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#4caf50",confirmButtonText:translationService.translate("web-swal-sparePartcounting-complete-button-confirm","Ja, fullfør Varetellingen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.model.EndDate=(new Date).toISOString(),repository.updateSingle(repository.apiData.sparePartCounting.url,$scope.model).then(function(result){swal(translationService.translate("web-swal-sparePartcounting-complete-success","Varetellingen ble fullført!"),null,"success")},function(error){$scope.model.EndDate=""})})},$scope.reopenCounting=function(){var oldEndDate=$scope.model.EndDate;$scope.model.EndDate=null,repository.updateSingle(repository.apiData.sparePartCounting.url,$scope.model).then(function(result){$scope.model=result},function(error){$scope.model.EndDate=oldEndDate})},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-sparePartcounting-message","Varetellingen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-sparePartcounting-button-confirm","Ja, fjern Varetellingen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.sparePartCounting.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-sparePartcounting-success","Varetellingen ble fjernet!"),result,"success"),$scope.goBack("sparePartCounting.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.copy=function(){repository.createSingle(repository.apiData.sparePartCounting.url,{CopyCounting:!0,CopyFromGuid:$stateParams.guid}).then(function(result){$scope.goBack("sparePartCounting.edit",{guid:result.Guid})},function(error){repository.showError(error)})},$scope.hideSearch=function(){$scope.search={},$scope.search.listviewSearchStat=!1,$scope.searchChanged()};var searchTimeOutPromise;$scope.searchChanged=function(){$timeout.cancel(searchTimeOutPromise),searchTimeOutPromise=$timeout(function(){$scope.loadCountingListItems(),$scope.loadCountingListUsers()},500)},$scope.reloadSparePartCounting=function(sparePartCounting){sparePartCounting&&sparePartCounting.Guid&&repository.getSingle(repository.apiData.sparePartCounting.url,sparePartCounting.Guid).then(function(response){sparePartCounting=angular.merge(sparePartCounting,response.Data)},function(error){repository.growl(error,"danger")})},$scope.reloadList=function(list){list&&list.Guid&&repository.getSingle(repository.apiData.sparePartCountingList.url,list.Guid).then(function(response){list=angular.merge(list,response.Data)},function(error){repository.growl(error,"danger")})},$scope.addCountingList=function(){$modal.open({templateUrl:"app/sparePartCounting/views/createSparePartCountingListModal.html",controller:"CreateSparePartCountingListModalController",resolve:{params:function(){return{sparePartCounting:$scope.model,listNames:_.map($scope.sparePartCountingLists,"Id")}}}}).result.then(function(guid){repository.getSingle(repository.apiData.sparePartCountingList.url,guid).then(function(response){$scope.sparePartCountingLists.push(response.Data),$scope.setSelectedCountingList($scope.sparePartCountingLists[$scope.sparePartCountingLists.length-1])},function(error){repository.growl(error,"danger")})},function(){})},$scope.editCountingList=function(countingList){$modal.open({templateUrl:"app/sparePartCounting/views/createSparePartCountingListModal.html",controller:"CreateSparePartCountingListModalController",resolve:{params:function(){return{sparePartCountingList:countingList}}}}).result.then(function(newCountingList){countingList=newCountingList},function(){})},$scope.deleteCountingList=function(guid){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-sparePartCountingList-message","Tellelisten vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-sparePartCountingList-button-confirm","Ja, fjern tellelisten!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.sparePartCountingList.url,guid).then(function(result){swal(translationService.translate("web-swal-sparePartCountingList-success","Tellelisten ble fjernet!"),result,"success"),$scope.selectedCountingList.Guid===guid&&($scope.selectedCountingList=null);for(var i=0;i<$scope.sparePartCountingLists.length;i++)if($scope.sparePartCountingLists[i].Guid===guid){$scope.sparePartCountingLists.splice(i,1);break}})})},$scope.showMoreCountingItems=function(){$scope.countingItemCount+=25,$scope.loadCountingListItems()},$scope.loadCountingListItems=function(){var params={columns:["SparePart.Component.GuidImage","SparePart.Component.Id","SparePart.Component.Description","SparePart.Location","PhysicalQuantity","RecordQuantity","QuantityDeviation","CountedDate"],page:1,count:$scope.countingItemCount,sorting:$scope.sorting,filter:{PropertyFilter:[{Property:"GuidSparePartCountingList",operator:"=",value:$scope.selectedCountingList.Guid}],searchString:$scope.search.searchString}};repository.GetPaginated(repository.apiData.sparePartCountingItem.url,params.page-1,params.count,params.sorting,params.filter,null,JSON.stringify(params.columns)).then(function(result){$scope.selectedCountingList.SparePartCountingItems=result.List,$scope.canLoadMoreCountingItems=result.TotalCount>$scope.countingItemCount},function(error){repository.growl(error,"danger")})},$scope.loadCountingListUsers=function(){var params={columns:["User.Guid","User.RealName","User.Email","User.GuidImage","User.PhoneNumber"],page:1,count:25,sorting:{"User.RealName":"asc"},filter:{PropertyFilter:[{ Property:"GuidSparePartCountingList",operator:"=",value:$scope.selectedCountingList.Guid}],searchString:$scope.search.searchString}};repository.GetPaginated(repository.apiData.userXSparePartCountingList.url,params.page-1,params.count,params.sorting,params.filter,null,JSON.stringify(params.columns)).then(function(result){$scope.selectedCountingList.UserXSparePartCountings=result.List,$scope.userCount=result.TotalCount},function(error){repository.growl(error,"danger")})},$scope.addCountingListItems=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:"xl",resolve:{modalParams:function(){return{title:translationService.translate("web-sparePartCounting-addCountingListItems-title","Legg til varetelling poster"),columns:[{Title:translationService.translate("web-component-id"),Property:"Component.Id"},{Title:translationService.translate("web-component-description"),Property:"Component.Description"},{Title:translationService.translate("web-sparePart-location"),Property:"Location"},{Title:translationService.translate("web-sparePart-inventory"),Property:"Inventory"},{Title:translationService.translate("web-supplier-description"),Property:"ComponentXSupplier.Supplier.Description"},{Title:translationService.translate("web-componentXSupplier-PartNumber"),Property:"ComponentXSupplier.PartNumber"}],url:repository.apiData.sparePart.url,sorting:{"Component.Id":"asc"},filter:{filterActiveCounting:!0}}}}}).result.then(function(selectedGuids){var sparePartCountingItems=[];selectedGuids.forEach(function(guid){_.find($scope.selectedCountingList.SparePartCountingItems,function(obj){return obj.GuidSparePart===guid})||sparePartCountingItems.push({GuidSparePart:guid,GuidSparePartCountingList:$scope.selectedCountingList.Guid})}),repository.createMultiple(repository.apiData.sparePartCountingItem.url,sparePartCountingItems,"Prefix="+repository.apiData.sparePartCountingItem.prefix).then(function(result){repository.growl(translationService.translate("web-sparePartCounting-addCountingListItems-create-success","Varetelling postene har blitt lagt til"),"success"),$scope.reloadList($scope.selectedCountingList),$scope.reloadSparePartCounting($scope.model),$scope.loadCountingListItems()})},function(error){})},$scope.addCountingListUsers=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Legg til brukere",columns:[{Title:translationService.translate("web-user-username"),Property:"Username",PropertyType:"string"},{Title:translationService.translate("web-user-realname"),Property:"RealName",PropertyType:"string"}],url:repository.apiData.user.url,sorting:{Username:"asc"},alreadySavedGuids:function(){var selectedGuids=[];return $scope.selectedCountingList.UserXSparePartCountings.forEach(function(userXSparePartCounting){selectedGuids.push(userXSparePartCounting.User.Guid)}),selectedGuids}(),filter:{}}}}}).result.then(function(selectedGuids){var userXSparePartCountingList=[];selectedGuids.forEach(function(guid){_.find($scope.selectedCountingList.UserXSparePartCountings,function(obj){return obj.GuidUser===guid})||userXSparePartCountingList.push({GuidUser:guid,GuidSparePartCountingList:$scope.selectedCountingList.Guid})}),repository.createMultiple(repository.apiData.userXSparePartCountingList.url,userXSparePartCountingList,"Prefix="+repository.apiData.userXSparePartCountingList.prefix).then(function(result){repository.growl(translationService.translate("web-sparePartCounting-addCountingListUsers-create-success","Bruker har blitt lagt til"),"success"),$scope.loadCountingListUsers()})},function(error){})},$scope.deleteCountingListItem=function(guid){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-sparePartCountingItem-message","Reservedelen vil bli fjernet fra tellelisten!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-sparePartCountingItem-button-confirm","Ja, fjern reservedelen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.sparePartCountingItem.url,guid).then(function(result){$scope.loadCountingListItems(),swal(translationService.translate("web-swal-sparePartCountingItem-success","Reservedelen ble fjernet ble fjernet fra tellelisten!"),result,"success")})})},$scope.deleteCountingListUser=function(userXSparePartCounting){repository.deleteSingle(repository.apiData.userXSparePartCountingList.url,userXSparePartCounting.Guid).then(function(result){$scope.loadCountingListUsers()})},$scope.addCountingListContent=function(){"User"===$scope.selectedDataType?$scope.addCountingListUsers():"SparePartCountingItem"===$scope.selectedDataType&&$scope.addCountingListItems()},$scope.getPercent=function(number,total){return total?parseInt(number/total*100):0},$scope.getPercentCompleted=function(list){return list&&list.TotalQuantity?$scope.getPercent(list.TotalCountedQuantity,list.TotalQuantity):0},$scope.openUserInfoModal=function(userXSparePartCounting){$modal.open({templateUrl:"app/common/views/userInformationModal.html",controller:"UserInformationModalController",size:"sm",resolve:{params:function(){return{user:userXSparePartCounting.User}}}})},$scope.showCountingItemComment=function(countingItem){$modal.open({templateUrl:"app/common/views/messageModal.html",controller:"MessageModalController",size:"sm",resolve:{content:function(){return{header:"Kommentar",timestamp:countingItem.SparePart.Component.Id+" - "+countingItem.SparePart.Component.Description,message:countingItem.Comment}}}})},$scope.openSparePartInfoModal=function(sparePart){$modal.open({templateUrl:"app/sparePart/views/sparePartInformationModal.html",controller:"SparePartController",size:"sm",resolve:{params:function(){return{sparePart:sparePart}}}})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("SparePartCountingController",["$scope","Repository","$stateParams","TranslationService","$modal","$timeout","$q",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,ngTableParams,translationService,listService){$scope.isUpdate="sparePartWithdrawal.edit"===$scope.navigation.current.name;var columns=["SparePart.ComponentXSupplier.PartNumber","SparePart.Component.Id","SparePart.Component.Description","SparePart.Component.Unit","SparePart.Inventory","WorkOrderXSparePart.WorkOrder.Id","Building.Id","Building.Description","Equipment.Id","Equipment.Description","UserCreatedBy.RealName"];$scope.isUpdate?repository.getSingle(repository.apiData.sparePartWithdrawal.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.fieldRules=response.FieldRules,$scope.reload=!0},function(error){repository.growl(error,"danger")}):repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix.Condition).then(function(result){$scope.fieldRules=result,$scope.reload=!0}),$scope.updateWithdrawal=function(destination){$scope.isUpdate||($scope.model.GuidDataOwner=repository.commonService.getFilterData().selectedDataOwner.Guid);var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-sparePartWithdrawal-success","Uttak ble oppdatert."):translationService.translate("create-withdrawal-success","Uttak ble opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.sparePartWithdrawal.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.sparePartWithdrawal.url,$scope.model).then(success).catch(error)},$scope.removeWithdrawal=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-withdrawal-message","Uttak vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-withdrawal-button-confirm","Ja, fjern uttaket!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.sparePartWithdrawal.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-withdrawal-success","Uttaket ble fjernet!"),result,"success"),repository.growl("Uttaket har blitt fjernet","success"),$scope.goBack("sparePartWithdrawal.list",{menuGuid:$scope.navigation.params.menuGuid})})})}}angular.module("Plania").controller("SparePartWithdrawalController",["$scope","Repository","$stateParams","$modal","ngTableParams","TranslationService","ListService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService){$scope.isUpdate="standardText.edit"===$scope.navigation.current.name,$scope.model={};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.StandardText,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.StandardText,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.StandardText),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.StandardText)};$scope.isUpdate&&repository.getSingle(repository.apiData.standardText.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateAccess()},function(error){repository.growl(error,"danger")}),$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-standardText-success","StandardText har blitt oppdatert."):translationService.translate("create-standardText-success","StandardText har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingle(repository.apiData.standardText.url,$scope.model).then(success,error):repository.createSingle(repository.apiData.standardText.url,$scope.model).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-costcenter-message","StandardText vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-standardText-button-confirm","Ja, fjern StandardText"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.standardText.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-standardText-success","StandardText ble fjernet!"),result,"success"),$scope.goBack("standardText.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("StandardTextController",["$scope","Repository","$stateParams","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,ngTableParams,$modal,authService,translationService,$localStorage){$scope.update="supplier.edit"===$scope.navigation.current.name,$scope.isUpdate=$scope.update,$scope.isPersonCollapsed=!0,$scope.restrictEdit=!authService.hasEditAccess("supplier"),$scope.restrictDelete=!authService.hasDeleteAccess("supplier"),$scope.model={Guid:$stateParams.guid},$scope.modelDto={},$scope.reload=!1,$scope.activateAutocomplete=!1,$scope.generalOptions=$localStorage.generalOptions,$scope.viewMode=!!$scope.update,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var updateAccess=function(){if($scope.update){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!authService.hasEditAccess(repository.commonService.prefix.Supplier,checkOtherDo),$scope.restrictDelete=!authService.hasDeleteAccess(repository.commonService.prefix.Supplier,checkOtherDo)}else $scope.restrictEdit=!authService.hasCreateAccess(repository.commonService.prefix.Supplier)};updateAccess(),$scope.search={text:"",focus:!1,hasSearched:!1},$scope.steps=[],function(){var stepIndex=0,steps=[];$scope.generalOptions.UseBronnoysundRegister&&steps.push({stepIndex:++stepIndex,name:"searchBroenoysund",title:translationService.translate("web-supplier-section-title-searchBroenoysund","Søk")}),steps.push({stepIndex:++stepIndex,name:"basicInfo",title:translationService.translate("web-supplier-section-title-basicInformation","Basisinformasjon")}),$scope.steps=steps}(),$scope.currentStep=$scope.steps[0],$scope.goToNextStep=function(){var stepIndex=_.findIndex($scope.steps,{name:$scope.currentStep.name});if(stepIndex>=0&&stepIndex<$scope.steps.length){var nextStep=$scope.steps[++stepIndex];nextStep&&("searchBroenoysund"===nextStep.name&&($scope.searchResults=[],$scope.search.text="",$scope.search.hasSearched=!1,$timeout(function(){$scope.search.focus=!0},500)),$scope.currentStep=nextStep)}},$scope.goToPreviousStep=function(){var stepIndex=_.findIndex($scope.steps,{name:$scope.currentStep.name});if(stepIndex>0){var prevStep=$scope.steps[--stepIndex];prevStep&&($scope.currentStep=prevStep)}},$scope.orgNumberRegex=/^[0-9]{9}$/;var isOrganizationNumber=function(orgNumber){return $scope.orgNumberRegex.test(orgNumber)};if($scope.searchCustomerRegister=function(){var searchString=$scope.search.text,searchName=!0;try{searchName=!isOrganizationNumber(searchString)}catch(ex){searchName=!0}var queryParameters="";queryParameters=searchName?"name="+searchString:"organizationNumber="+searchString,repository.getWithUrlParameter(repository.apiData.customer.endpoint.searchPublicRegister,queryParameters).then(function(result){result&&($scope.searchResults=result.List,$scope.searchResultTotalCount=result.TotalCount,$scope.search.hasSearched=!0)},function(error){repository.growl(error,"danger")})},$scope.selectSupplier=function(supplier){$scope.model.Description=supplier.navn,$scope.model.OrganizationNr=supplier.organisasjonsnummer,supplier.forretningsadresse&&($scope.model.Address1=supplier.forretningsadresse.adresse[0],$scope.model.PostalCode=supplier.forretningsadresse.postnummer,$scope.model.PostalArea=supplier.forretningsadresse.poststed,$scope.model.Country=supplier.forretningsadresse.land),$scope.goToNextStep()},$scope.update){var columns=["SupplierLineOfBusiness.Id"];repository.getMainModel(repository.apiData.supplier.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){var supplier=response.Data;$scope.model=supplier,updateAccess(),$scope.reload=!0,$scope.model.SupplierLineOfBusiness&&($scope.modelDto.supplierLineOfBusiness=$scope.getEntityCaption($scope.model.SupplierLineOfBusiness)),$scope.contactTable.filter().GuidSupplier=$scope.model.Guid,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})}else{$scope.activateAutocomplete=!0;var webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value)switch(prefill.Property){case"SupplierLineOfBusiness":$scope.model.SupplierLineOfBusiness.Id=prefill.Value.Label,$scope.model.GuidSupplierLineOfBusiness=prefill.Value.Guid}else $scope.model[prefill.Property]=prefill.Value})}$scope.contactTable=new ngTableParams({page:1,count:10,sorting:{LastName:"asc",FirstName:"asc"},filter:{PropertyFilter:[{Property:"GuidSupplier",Operator:"=",Value:$stateParams.guid}]}},{total:0,filterDelay:10,counts:[],getData:function($defer,params){authService.hasReadAccess("ContactPerson")&¶ms.filter().GuidSupplier&&repository.GetPaginated(repository.apiData.contactPerson.url,params.page()-1,params.count(),params.sorting(),params.filter()).then(function(result){$scope.contactTable.settings().total=result.TotalCount,$scope.contactTable.settings().filterDelay=500,result.totalCount>10&¶ms.counts([10,20,50]),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.updateSupplier=function(destination){var success=function(result){repository.growl($scope.update?"Leverandør har blitt oppdatert":"Leverandør har blitt lagret","success");var guid=$scope.update?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.update?repository.updateSingle(repository.apiData.supplier.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.supplier.url,$scope.model).then(success).catch(error)},$scope.addContactPerson=function(){$modal.open({templateUrl:"app/contactPerson/contactPerson.html",controller:"ContactPersonController",resolve:{params:function(){return{guidSupplier:$scope.model.Guid}}}}).result.then(function(){$scope.contactTable.reload(),$scope.isPersonCollapsed=!1},function(){$scope.isPersonCollapsed=!1})},$scope.updateContactPerson=function(guid){$modal.open({templateUrl:"app/contactPerson/contactPerson.html",controller:"ContactPersonController",resolve:{params:function(){return{guid:guid}}}}).result.then(function(){$scope.contactTable.reload(),$scope.isPersonCollapsed=!1},function(){$scope.isPersonCollapsed=!1})},$scope.openUrl=function(){var url=$scope.model.WebAddress;url&&0!==url.indexOf("http")&&(url="https://"+url),window.open(url,"_blank")},$scope.openMail=function(){window.location.href="mailto:"+$scope.model.Email},$scope.removePerson=function(person){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-supplier-contactperson-message","Kontaktpersonen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-supplier-contactperson-button-confirm","Ja, fjern kontaktpersonen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.contactPerson.url,person.Guid).then(function(result){swal(translationService.translate("web-swal-supplier-contactperson-success","Kontaktpersonen ble fjernet!"),result,"success"),$scope.contactTable.reload()})})},$scope.removeSupplier=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-supplier-message","Leverandøren vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-supplier-button-confirm","Ja, fjern leverandøren!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.supplier.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-supplier-success","Leverandøren ble fjernet!"),result,"success"),$scope.goBack("supplier.list",{menuGuid:$scope.navigation.params.menuGuid})},function(error){swal({title:"Kunne ikke slette leverandøren!",text:error.Message+"

    Vil du deaktivere leverandøren?",type:"error",html:!0,showCancelButton:!0,confirmButtonText:"Deaktiver",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.IsDeactivated=!0,$scope.model.Id="#"+$scope.model.Id,$scope.updateSupplier("supplier.list"))})})})},$scope.onPostCodeSelect=function(postalInfo){postalInfo?($scope.model.GuidPost=postalInfo.Guid,$scope.model.PostalCode=postalInfo.ZipCode,$scope.model.PostalArea=postalInfo.PostalArea,$scope.postalInfo=postalInfo):($scope.model.PostalCode="",$scope.model.GuidPost="",$scope.model.PostalArea="")},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("SupplierController",["$scope","Repository","$stateParams","ngTableParams","$modal","authService","TranslationService","$localStorage",controller])}(),function(){function controller($scope,repository,translationService,params,$modalInstance){$scope.model=angular.copy(params.languageXWebText),$scope.systemName=params.systemName,$scope.model.TranslatedHelpText?$scope.HelpTextHtml=$scope.model.TranslatedHelpText:$scope.HelpTextHtml=$scope.model.DefaultTranslatedHelpText,$scope.save=function(){$scope.model.TranslatedHelpText=$scope.HelpTextHtml,repository.updateSingle(repository.apiData.translate.url,$scope.model).then(function(result){repository.growl("Hjelpetekst oppdatert","success"),translationService.setHelpTextEntry(($scope.model.Language.Locale+params.systemName).toLowerCase(),!(!$scope.model.TranslatedHelpText&&!$scope.model.DefaultTranslatedHelpText)),$modalInstance.close(result)},function(error){repository.growl(error,"danger")})},$scope.setEmpty=function(){$scope.HelpTextHtml=""},$scope.tinymceOptions={language:"nb_NO",branding:!1,plugins:["autolink link autoresize textcolor"],menubar:"edit insert format",toolbar:"undo redo | styleselect fontselect fontsizeselect | bold italic forecolor backcolor | alignleft aligncenter alignright lineheightselect | bullist numlist outdent indent ",image_advtab:!1,relative_urls:!1,convert_urls:!1,remove_script_host:!1,paste_data_images:!1,autoresize_min_height:400,autoresize_max_height:600,forced_root_block:!1,lineheight_formats:"14pt 16pt 18pt 20pt 22pt 24pt 26pt 36pt",inline_styles:!0,font_formats:"Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Calibri=calibri;Comic Sans MS=comic sans ms,sans-serif;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;"},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("EditHelpTextModalController",["$scope","Repository","TranslationService","params","$modalInstance",controller])}(),function(){function controller($scope,params,$modalInstance,translationService,$sce){$scope.model={translatedLabel:params.translatedLabel},translationService.getHelpText(params.systemName).then(function(result){$scope.model.helpText=$sce.trustAsHtml(result)}),$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("HelpTextModalController",["$scope","params","$modalInstance","TranslationService","$sce",controller])}(),function(){function controller($scope,repository,ngTableParams,$modal){$scope.invalidateLanguageCache=function(){repository.deleteSingle(repository.apiData.translate.url,"cache").then(function(){repository.growl("Cache har blitt invalidert","success")})},$scope.translationTable=new ngTableParams({page:1,count:20,filter:{}},{total:0,counts:[20,50,100],getData:function($defer,params){repository.GetPaginated(repository.apiData.translate.url,params.page()-1,params.count(),params.sorting(),params.filter()).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List),result.List.length>0&&($scope.tableHeaders=_.map(result.List[0].LanguageXWebTexts,function(o){return o.Language.Country}))},function(error){repository.growl(error,"danger")})}}),$scope.openTranslationModal=function(webText){$modal.open({templateUrl:"app/translation/views/translationModal.html",controller:"TranslationModalController",size:"lg",resolve:{params:function(){return{webText:webText}}}}).result.then(function(result){$scope.preSelected=webText,$scope.translationTable.reload()})}}angular.module("Plania").controller("TranslationListController",["$scope","Repository","ngTableParams","$modal",controller])}(),function(){function controller($scope,repository,params,$modalInstance,translationService,$q,$modal){function setHelpTextFromResult(model,result){model.HasHelpText=result.HasHelpText,model.DefaultTranslatedHelpText=result.DefaultTranslatedHelpText,model.TranslatedHelpText=result.TranslatedHelpText}var helpTextWasUpdated=!1;!params.webText&¶ms.systemName?repository.getSingle(repository.apiData.translate.url,params.systemName).then(function(result){$scope.model=angular.copy(result),$scope.original=angular.copy($scope.model.LanguageXWebTexts.sort(function(a,b){return a.Language.IndexPosition-b.Language.IndexPosition}))},repository.showError):($scope.model=angular.copy(params.webText),$scope.original=angular.copy($scope.model.LanguageXWebTexts));var updateTranslation=function(translation){var deferred=$q.defer();return repository.updateSingle(repository.apiData.translate.url,translation).then(function(result){deferred.resolve(result)},function(error){deferred.reject(error)}),deferred.promise};$scope.editHelpText=function(translation){var originalTranslation=_.find($scope.original,{Guid:translation.Guid});$modal.open({templateUrl:"app/translation/views/editHelpTextModal.html",controller:"EditHelpTextModalController",size:"lg",resolve:{params:function(){return{systemName:params.systemName,languageXWebText:originalTranslation}}}}).result.then(function(result){helpTextWasUpdated=!0;var idx=_.findIndex($scope.model.LanguageXWebTexts,{Guid:result.Guid});-1!==idx&&(setHelpTextFromResult($scope.model.LanguageXWebTexts[idx],result),setHelpTextFromResult($scope.original[idx],result))})},$scope.save=function(){for(var promises=[],i=0;i<$scope.model.LanguageXWebTexts.length;i++)$scope.model.LanguageXWebTexts[i].TranslatedValue!==$scope.original[i].TranslatedValue&&promises.push(updateTranslation($scope.model.LanguageXWebTexts[i]));promises.length>0?$q.all(promises).then(function(){repository.growl("Oversettelse oppdatert","success"),params.webText=$scope.model,$modalInstance.close({model:$scope.model,translationUpdated:!0})}).catch(function(error){repository.growl(error,"danger")}):helpTextWasUpdated?$modalInstance.close({model:$scope.model,helpTextUpdated:helpTextWasUpdated}):$modalInstance.close("nothing to update")},$scope.cancel=function(){helpTextWasUpdated?$modalInstance.close({model:$scope.model,helpTextUpdated:helpTextWasUpdated}):$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("TranslationModalController",["$scope","Repository","params","$modalInstance","TranslationService","$q","$modal",controller])}(),function(){function controller($scope,repository,params,$modalInstance,constants,$rootScope,commonService){$scope.model={},$scope.model.GuidUser=params.guidUser,$scope.model.IsDefaultDataOwner=!!params.isFirst;var isKaLocalAdmin=$scope.customization.isCustomer("KA")&&$rootScope.userInfo.guidUserGroup===constants.ka.guidLocalAdminUserGroup;isKaLocalAdmin&&($scope.model.GuidLinkedDataOwner=commonService.getFilterData().selectedDataOwner.Guid,$scope.model.LinkedDataOwner={Guid:commonService.getFilterData().selectedDataOwner.Guid,Description:commonService.getFilterData().selectedDataOwner.Description},$scope.dataOwnerSelectionLocked=!0),$scope.save=function(){$modalInstance.close()},$scope.saveAction=function(){delete angular.copy($scope.model).User,repository.createSingle(repository.apiData.userProfile.url,$scope.model).then(function(result){repository.growl("Brukerprofil oppdatert","success"),$modalInstance.close($scope.model)}).catch(function(error){var message="";error.indexOf("invalid_license_defined_users")>=0&&(message="Antall brukere er flere enn lisensert. Fortsett vil sende melding om lisensendring til Plania"),error.indexOf("invalid_license_simple_users")>=0&&(message="Antall brukere er flere enn lisensert. Fortsett vil sende melding om lisensendring til Plania"),""!==message?swal({title:"Bekreft utvidelse av lisens",text:message,type:"warning",showCancelButton:!0,confirmButtonText:"Ja, utvid lisens",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm?($scope.model.ConfirmIncreaseInLicense=!0,$scope.saveAction()):(repository.growl("Endringene ble avbrutt!","success"),$modalInstance.close("ok"))}):swal({title:"Feil ved lagring",text:error,type:"warning",closeOnConfirm:!0,closeOnCancel:!0})})},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.autoCompleteFilter=function(filterName){switch(filterName){case"dataOwner":return{ExcludeUserDataOwners:$scope.model.GuidUser};case"entityPermissionProfile":return isKaLocalAdmin?{FilterModel:{Condition:"and",Rules:[{Property:"Guid",Operator:"in",Value:[constants.ka.guidStandardEntityPermissionProfile,constants.ka.guidExternalOperatorEntityPermissionProfile]}]}}:{}}}}angular.module("Plania").controller("CreateUserDataOwnerController",["$scope","Repository","params","$modalInstance","Constants","$rootScope","CommonService",controller])}(),function(){function controller($scope,repository,params,$modalInstance,constants,$rootScope){$scope.isDocumentsCollapsed=!0,$scope.activateAutocomplete=!1;var isKaLocalAdmin=$scope.customization.isCustomer("KA")&&$rootScope.userInfo.guidUserGroup===constants.ka.guidLocalAdminUserGroup;isKaLocalAdmin&&($scope.dataOwnerSelectionLocked=!0),repository.getSingle(repository.apiData.userProfile.url,params.guidUserProfile).then(function(result){$scope.model=result.Data,$scope.isUpdateProfile=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}),$scope.save=function(){$modalInstance.close()},$scope.saveAction=function(){var sendModel=angular.copy($scope.model);delete sendModel.User,repository.updateSingle(repository.apiData.userProfile.url,sendModel).then(function(result){repository.growl("Brukerprofil oppdatert","success"),$modalInstance.close($scope.model)},function(error){var message="";error.indexOf("invalid_license_defined_users")>=0&&(message="Antall brukere er flere enn lisensert. Fortsett vil sende melding om lisensendring til Plania"),error.indexOf("invalid_license_simple_users")>=0&&(message="Antall brukere er flere enn lisensert. Fortsett vil sende melding om lisensendring til Plania"),""!==message?swal({title:"Bekreft utvidelse av lisens",text:message,type:"warning",showCancelButton:!0,confirmButtonText:"Ja, utvid lisens",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm?($scope.model.ConfirmIncreaseInLicense=!0,$scope.saveAction()):(repository.growl("Endringene ble avbrutt!","success"),$modalInstance.close("ok"))}):swal({title:"Feil ved lagring",text:error,type:"warning",closeOnConfirm:!0, closeOnCancel:!0})})},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.autoCompleteFilter=function(filterName){switch(filterName){case"entityPermissionProfile":return isKaLocalAdmin?{FilterModel:{Condition:"and",Rules:[{Property:"Guid",Operator:"in",Value:[constants.ka.guidStandardEntityPermissionProfile,constants.ka.guidExternalOperatorEntityPermissionProfile]}]}}:{}}}}angular.module("Plania").controller("EditUserDataOwnerController",["$scope","Repository","params","$modalInstance","Constants","$rootScope",controller])}(),function(){function controller($scope,translationService,repository,$modal,$stateParams,ngTableParams,$localStorage,$rootScope,listService,constants){function setTwoFactorStatus(){$scope.twoFactor={},$localStorage.generalOptions.TwoFactorAuthenticationOption<=0?($scope.twoFactor.isEnabled=!1,$scope.twoFactor.canChange=!1,$scope.twoFactor.statusText=translationService.translate("web-user-twofactor-disabled","Tofaktor er avskrudd fra system")):2===$localStorage.generalOptions.TwoFactorAuthenticationOption?($scope.twoFactor.isEnabled=!0,$scope.twoFactor.canChange=!1,$scope.twoFactor.statusText=translationService.translate("web-user-twofactor-enabled","Tofaktor er påskrudd fra system")):$scope.model.UserGroup&&$scope.model.UserGroup.IsTwoFactorAuthenticationEnabled?($scope.twoFactor.isEnabled=!0,$scope.twoFactor.canChange=!1,$scope.twoFactor.statusText=translationService.translate("web-user-twofactor-usergroup-enabled","Tofaktor er påskrudd fra brukergruppe")):($scope.twoFactor.isEnabled=$scope.model.IsTwoFactorAuthenticationEnabled,$scope.twoFactor.canChange=!0)}$scope.update="user.edit"===$scope.navigation.current.name,$scope.languages=[],$scope.model={Guid:$stateParams.guid},$scope.passwordExpirationDate=!1,$scope.restrictEdit=!1,$scope.activateAutocomplete=!$scope.update,$scope.viewMode=!!$scope.update,$scope.hasReadAccess=$rootScope.hasReadAccess,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.getPropertyValue=function(entity,field){return listService.GetPropertyValue(entity,field)},$scope.open=function($event){$scope.passwordExpirationDate=!$scope.passwordExpirationDate,$event.preventDefault(),$event.stopPropagation()};var updateAccess=function(){$scope.update?($scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.User,!1),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.User,!1),$scope.userInfo.isUserAdministrator||($scope.restrictEdit=$scope.restrictEdit||$scope.model.Guid!==$scope.userInfo.guidUser,$scope.restrictDelete=$scope.restrictEdit||$scope.model.Guid!==$scope.userInfo.guidUser)):($scope.restrictEdit=!$scope.userInfo.isUserAdministrator||!repository.authService.hasCreateAccess(repository.commonService.prefix.User),$scope.restrictDelete=!$scope.userInfo.isUserAdministrator||!repository.authService.hasDeleteAccess(repository.commonService.prefix.User)),$scope.hasProjectManagementModule=$scope.hasModule("ProjectManagement")};updateAccess(),setTwoFactorStatus(),$scope.access={Desktop:!1,Web:!1,Mobile:!1,ReadOnlyWeb:!1};var setUserAccess=function(access){access.indexOf("Desktop")>=0&&($scope.access.Desktop=!0),access.indexOf("Web")>=0&&($scope.access.Web=!0),access.indexOf("Mobil")>=0&&($scope.access.Mobile=!0),access.indexOf("ReadOnlyWeb")>=0&&($scope.access.ReadOnlyWeb=!0)},GetUserAccess=function(){var access=0;return $scope.access.Desktop&&(access|=1),$scope.access.Web&&(access|=2),$scope.access.Mobile&&(access|=4),$scope.access.ReadOnlyWeb&&(access|=8),access};repository.GetPaginated(repository.apiData.webMenu.url,0,1e3,{Name:"asc"},{},"",JSON.stringify(["Name"])).then(function(result){var availableMenus=[];availableMenus.push({text:"Ingen",guid:null}),result.List.length>0&&result.List.forEach(function(webMenu){webMenu.IsBuildingDependent||availableMenus.push({text:webMenu.Name,guid:webMenu.Guid})}),$scope.availableStartPages=availableMenus,$scope.model.GuidWebMenu&&($scope.selectedStartMenu=_.filter($scope.availableStartPages,{guid:$scope.model.GuidWebMenu})[0]||$scope.availableStartPages[0])});var getSingle=function(){var columns=["Person.FirstName","Person.LastName","Person.Email","Person.TelephoneWork","ResourceGroup.Id","Department.Id","Department.Description","Account.Id","Account.Description","Supplier.Description","DefaultBuildingSelection.Description","Customer.Id","Customer.Description","MobileMenuProfile.Id","MobileMenuProfile.Description"];repository.getSingle(repository.apiData.user.url,$stateParams.guid,JSON.stringify(columns)).then(function(result){$scope.model=result.Data,$scope.model.UserGroup||($scope.model.UserGroup={IsStartPageForced:!1}),updateAccess(),setUserAccess($scope.model.AccessType),setTwoFactorStatus(),repository.GetPaginated(repository.apiData.language.url,0,100,{},{}).then(function(result){$scope.languages=[],result.List.forEach(function(row){$scope.languages.push(row)}),$scope.model.GuidLanguage=$scope.model.GuidLanguage?$scope.model.GuidLanguage:$scope.languages[0].Guid,$scope.selectedLanguage=_.filter($scope.languages,{Guid:$scope.model.GuidLanguage})[0]}),$scope.availableStartPages&&($scope.selectedStartMenu=_.filter($scope.availableStartPages,{guid:$scope.model.GuidWebMenu})[0]||$scope.availableStartPages[0]),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})};$scope.update?getSingle():($scope.model.UserGroup={IsStartPageForced:!1},repository.GetPaginated(repository.apiData.language.url,0,100,{},{}).then(function(result){result.List.forEach(function(row){$scope.languages.push(row)});var language=_.filter($scope.languages,{Country:"Norway"})[0]||$scope.languages[0];$scope.model.GuidLanguage=language.Guid})),$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"userGroup":return filter.FilterModel={Condition:"and",Rules:[{Property:"IsUserGroup",Operator:"=",Value:!0}]},$scope.customization.isCustomer("KA")&&$rootScope.userInfo.guidUserGroup===constants.ka.guidLocalAdminUserGroup&&filter.FilterModel.Rules.push({Property:"Guid",Operator:"in",Value:[constants.ka.guidFdvUserGroup,constants.ka.guidInventoryUserGroup]}),filter}return filter},$scope.GuidChangeLanguage=function(selectedLanguage){$scope.model.GuidLanguage=selectedLanguage.Guid,$scope.selectedLanguage=_.filter($scope.languages,{Guid:selectedLanguage.Guid})[0]},$scope.changeStartPage=function(selected){selected&&($scope.model.GuidWebMenu=selected.guid)},$scope.deleteUser=function(destination,user){$scope.isDeletingUser=!0,swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-user-message","Bruker vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-user-button-confirm","Ja, fjern brukeren!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.user.url,user.Guid).then(function(result){window.onkeydown=null,window.onfocus=null,repository.growl(translationService.translate("delete-user-success-message"," %Username% ble slettet fra systemet",user),"success"),$scope.goBack(destination,{menuGuid:$scope.navigation.params.menuGuid}),swal.close()},function(error){swal({title:translationService.translate("web-user-delete-fail","Kunne ikke slette %Username%",user),text:error.Message+"

    "+translationService.translate("web-user-deactivate-question","Vil du deaktivere %Username%",user),type:"error",html:!0,showCancelButton:!0,confirmButtonText:"Deaktiver",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm&&($scope.model.IsDeactivated=!0,$scope.updateUser("user.list"))})})})},$scope.onUserGroupSelect=function(ug){ug||($scope.model.GuidUserGroup="",$scope.model.UserGroup.IsStartPageForced=!1),$scope.model.UserGroup&&$scope.model.UserGroup.IsStartPageForced&&repository.GetPaginated(repository.apiData.webMenu.url,0,1e3,{Id:"asc"},{},"",JSON.stringify(["Name"])).then(function(result){var availableMenus=[];availableMenus.push({text:"Ingen",guid:null}),result.List.length>0&&result.List.forEach(function(webMenu){webMenu.IsBuildingDependent||availableMenus.push({text:webMenu.Name,guid:webMenu.Guid})}),$scope.availableStartPages=availableMenus,$scope.model.UserGroup.GuidWebMenu&&($scope.selectedStartMenu=_.filter($scope.availableStartPages,{guid:$scope.model.UserGroup.GuidWebMenu})[0]||$scope.availableStartPages[0],$scope.model.GuidWebMenu=$scope.model.UserGroup.GuidWebMenu)}),$scope.update||($scope.model.GuidPerson||($scope.model.GuidPerson=ug.guidPerson),$scope.model.GuidResourceGroup=ug.GuidResourceGroup,$scope.model.ResourceGroup=ug.ResourceGroup,$scope.model.GuidAccount=ug.GuidAccount,$scope.model.Account=ug.Account,$scope.model.GuidDepartment=ug.GuidDepartment,$scope.model.Department=ug.Department,$scope.model.GuidCustomer=ug.GuidCustomer,$scope.model.Customer=ug.Customer,$scope.model.GuidDefaultBuildingSelection=ug.GuidDefaultBuildingSelection,$scope.model.DefaultBuildingSelection=ug.DefaultBuildingSelection,$scope.model.Procuration=ug.Procuration,$scope.model.CanPrintPurchaseOrder=ug.CanPrintPurchaseOrder),$scope.model.GuidDefaultDataOwner=ug.GuidDefaultDataOwner,$scope.model.GuidMobileMenuProfile=ug.GuidMobileMenuProfile,$scope.model.MobileMenuProfile=ug.MobileMenuProfile,$scope.model.AccessType=ug.AccessType,setUserAccess($scope.model.AccessType),setTwoFactorStatus(),$scope.model.IsUserAdministrator=ug.IsUserAdministrator,$scope.model.IsSystemAdministrator=ug.IsSystemAdministrator,$scope.model.CanRunNewPeriod=ug.CanRunNewPeriod,$scope.model.CanRunNewEnergyPeriod=ug.CanRunNewEnergyPeriod,$scope.model.CanChangeDataOwner=ug.CanChangeDataOwner,$scope.model.CanOverridePermissions=ug.CanOverridePermissions,$scope.model.CanRunSystemFunction=ug.CanRunSystemFunction,$scope.model.IsBookingAdministrator=ug.IsBookingAdministrator,$scope.model.IsExternalUser=ug.IsExternalUser,$scope.model.CanChangeDataAcquisitionStatus=ug.CanChangeDataAcquisitionStatus,$scope.model.CanChangeRequestStatus=ug.CanChangeRequestStatus,$scope.model.CanSeeWebMainMenu=ug.CanSeeWebMainMenu,$scope.model.CanExportToExcel=ug.CanExportToExcel,$scope.model.SqlCustomerFilter=ug.SqlCustomerFilter,$scope.model.GuidUserGroup=ug.Guid,$scope.model.UserGroup=ug},$scope.onPersonSelect=function(person){if(!person)return void($scope.model.GuidPerson="");person.Email&&($scope.model.Email=person.Email),person.TelephoneWork&&($scope.model.PhoneNumber=person.TelephoneWork),!$scope.model.CellPhone&&person.Cellphone&&($scope.model.CellPhone=person.Cellphone),$scope.model.RealName=person.FirstName+" "+person.LastName,$scope.model.GuidPerson=person.Guid},$scope.updateUser=function(destination){if(!$scope.userForm.newEmail.$valid)return void repository.growl(translationService.translate("web-user-validation-email-invalidFormat","Epostformat er ugyldig"),"danger");if(!$scope.model.IsPasswordPermanent&&!$scope.model.PasswordLastDayDate)return void repository.growl(translationService.translate("user-label-passwordExpirationDate")+" er obligatorisk","danger");$scope.model.AccessType=GetUserAccess(),$scope.update||($scope.model.GuidDefaultDataOwner=repository.commonService.getFilterData().selectedDataOwner.Guid);var success=function(result){repository.growl($scope.update?translationService.translate("update-user-success","Brukeren har blitt oppdatert."):translationService.translate("create-user-success","Brukeren har blitt registrert."),"success");var guid=$scope.update?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){var message="";error.indexOf("invalid_license_defined_users")>=0&&(message="Antall brukere er flere enn lisensert. Fortsett vil sende melding om lisensendring til Plania"),error.indexOf("invalid_license_simple_users")>=0&&(message="Antall brukere er flere enn lisensert. Fortsett vil sende melding om lisensendring til Plania"),""!==message?swal({title:"Bekreft utvidelse av lisens",text:message,type:"warning",showCancelButton:!0,confirmButtonText:"Ja, utvid lisens",cancelButtonText:"Avbryt",closeOnConfirm:!0,closeOnCancel:!0},function(isConfirm){window.onkeydown=null,window.onfocus=null,isConfirm?($scope.model.ConfirmIncreaseInLicense=!0,$scope.updateUser(destination)):repository.growl("Endringene ble avbrutt!","danger")}):repository.growl(error,"danger")};$scope.model.PasswordLastDayDate&&($scope.model.PasswordLastDayDate=new Date($scope.model.PasswordLastDayDate).toISOString()),$scope.update?repository.updateSingle(repository.apiData.user.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.user.url,$scope.model).then(success).catch(error)},$scope.userProfileInfo=new function(){var me=this;this.data=[],this.totalCount=0,this.search={},this.columns=[{Position:1,Title:translationService.translate("user-clientTable-dataOwnerName","Klient"),Property:"LinkedDataOwner.Description",PropertyType:"string"},{Position:2,Title:translationService.translate("user-clientTable-userProfileName","Profil"),Property:"EntityPermissionProfile.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("user-clientTable-userProfileDescription","Profilbeskrivelse"),Property:"EntityPermissionProfile.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("user-clientTable-updatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}],this.defaultDataOwner={hasError:!1,status:"",caption:""},this.getData=function(){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("IsDefaultDataOwner");var filter={FilterModel:{Property:"GuidUser",Operator:"=",Value:$scope.model.Guid}};repository.GetPaginated(repository.apiData.userProfile.url,0,-1,null,filter,null,JSON.stringify(columns)).then(function(result){me.data=result.List,me.totalCount=result.TotalCount,me.table.reload();var defaultDataOwner=_.filter($scope.userProfileInfo.data,{IsDefaultDataOwner:!0})[0];if(defaultDataOwner)if(defaultDataOwner.GuidEntityPermissionProfile){var caption="";defaultDataOwner.LinkedDataOwner.Description&&(caption+=defaultDataOwner.LinkedDataOwner.Description),defaultDataOwner.EntityPermissionProfile.Id&&(caption&&(caption+=" - "),caption+=defaultDataOwner.EntityPermissionProfile.Id),me.defaultDataOwner={profile:defaultDataOwner,hasError:!1,status:"ok",caption:caption}}else me.defaultDataOwner={hasError:!0,status:"missingEntityPermission"};else me.data.length?me.defaultDataOwner={hasError:!0,status:"missingUserProfiles"}:me.defaultDataOwner={hasError:!0,status:"missingDefaultDataOwner"}},function(error){repository.showError(error)})};var getValue=function(entity,property){var value=entity;return property.split(".").forEach(function(prop){null!==value&&void 0!==value&&(value=value[prop])}),value},getFilteredData=function(filter){var data=me.data;if(void 0===filter.searchString)return data;var filterText=filter.searchString.toLowerCase();return data=data.filter(function(item){if(void 0===filterText||null===filterText||""===filterText.trim())return!0;var state=!1;return me.columns.forEach(function(column){(""+getValue(item,column.Property)).toLowerCase().includes(filterText)&&(state=!0)}),state})};this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:20,filter:{searchParams:""},sorting:{"LinkedDataOwner.Description":"asc"}},{total:0,filterDelay:10,counts:[20,50,100,200],getData:function($defer,params){var data=getFilteredData(params.filter()),sortingKey=Object.keys(params.sorting())[0];if(sortingKey){data=_.sortBy(data,sortingKey);"desc"===params.sorting()[sortingKey].toLowerCase()&&(data=data.reverse())}me.table.settings().total=data.length,me.table.settings().filterDelay=500,data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$defer.resolve(data)}}))},this.add=function(){me.canAdd()&&$modal.open({templateUrl:"app/user/views/editUserDataOwner.html",controller:"CreateUserDataOwnerController",resolve:{params:function(){return{guidUser:$scope.model.Guid,isFirst:me.data.length<1}}}}).result.then(function(userProfile){userProfile&&userProfile.IsDefaultDataOwner&&($scope.model.GuidDefaultDataOwner=userProfile.GuidLinkedDataOwner),me.getData()})},this.update=function(entity){me.canEdit(entity)&&($scope.restrictEdit||$scope.model.GuidUserGroup&&$scope.model.UserGroup&&!$scope.model.UserGroup.CanOverrideUserProfiles||$modal.open({templateUrl:"app/user/views/editUserDataOwner.html",controller:"EditUserDataOwnerController",resolve:{params:function(){return{guidUserProfile:entity.Guid}}}}).result.then(function(userProfile){userProfile&&userProfile.IsDefaultDataOwner&&($scope.model.GuidDefaultDataOwner=userProfile.GuidLinkedDataOwner),me.getData()}))},this.remove=function(entity){me.canDelete(entity)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-user-dataOwner-message","Klienten vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-user-dataOwner-button-confirm","Ja, fjern klienten!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.userProfile.url,entity.Guid).then(function(result){swal.close(),repository.growl(translationService.translate("user-removeDataOwner-Success","Klient ble fjernet fra Bruker."),"success"),me.getData()})})},this.contextMenuOptions=function(item){var options=[];return me.canEdit(item)&&options.push({html:' '+translationService.translate("web-user-userProfile-edit","Rediger klienttilgang")+"",click:function(){me.update(item)}}),$scope.hasReadAccess("DataOwner")&&options.push({html:' '+translationService.translate("web-user-viewDataOwner","Gå til klient")+"",isHref:!0}),$scope.hasReadAccess("EntityPermissionProfile")&&options.push({html:' '+translationService.translate("web-user-viewEntityPermissionProfile","Gå til rettighetsprofil")+"",isHref:!0}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-user-dataOwner-delete","Slett klient")+"",click:function(){me.remove(item)},hasTopDivider:!0}),options},this.canAdd=function(){return!($scope.restrictEdit||$scope.model.GuidUserGroup&&$scope.model.UserGroup&&!$scope.model.UserGroup.CanOverrideUserProfiles)},this.canEdit=function(entity){return entity&&!$scope.restrictEdit&&(!$scope.model.GuidUserGroup||!$scope.model.UserGroup||!!$scope.model.UserGroup.CanOverrideUserProfiles)},this.canDelete=function(entity){return entity&&!$scope.restrictEdit&&(!$scope.model.GuidUserGroup||!$scope.model.UserGroup||!!$scope.model.UserGroup.CanOverrideUserProfiles)},$scope.update&&(me.initTable(),me.getData())},$scope.$on("$stateChangeStart",function(event,toState,toParams,fromState,fromParams){if("user.edit"!==toState.name&&$scope.update&&!$scope.isDeletingUser)if(0===$scope.userProfileInfo.data.length)event.preventDefault(),swal(translationService.translate("user-edit-no-dataowner-title","Ingen klienter valgt"),translationService.translate("user-edit-no-dataowner","Klient og brukerprofil må velges dersom brukeren skal kunne benyttes"),"error"),$scope.userProfileInfo.add();else if(0===_.filter($scope.userProfileInfo.data,{IsDefaultDataOwner:!0}).length)event.preventDefault(),swal(translationService.translate("user-edit-no-default-dataowner-title","Ingen Standard klient valgt"),translationService.translate("user-edit-no-default-dataowner","Det må velges en standard klient dersom brukeren skal kunne benyttes"),"error"),$scope.userProfileInfo.add();else if(0===_.filter($scope.userProfileInfo.data,function(profile){return profile.GuidEntityPermissionProfile&&profile.IsDefaultDataOwner}).length){event.preventDefault(),swal(translationService.translate("user-edit-no-entityPermission-title","Ingen Profil valgt"),translationService.translate("user-edit-no-entityPermission","Standard klient må ha en profil valgt"),"error");var defaultProfile=_.find($scope.userProfileInfo.data,function(profile){return profile.IsDefaultDataOwner});defaultProfile?$scope.userProfileInfo.update(defaultProfile):$scope.userProfileInfo.add()}}),$scope.uploadImage=function(images){if(!(images.length<1)){$modal.open({templateUrl:"app/common/views/imageUploadModal.html",controller:"ImageUploadModalController",size:"lg",resolve:{params:function(){return{image:images[0],targetSize:300,areaType:"square"}}}}).result.then(function(croppedImage){function handleFileUpload(file){var reader=new FileReader;reader.onload=function(e){var newFile={ImageSrc:e.target.result.substr(e.target.result.indexOf("base64,")+"base64,".length),Name:file.name,GuidUser:$scope.model.Guid};files.push(newFile),onLoadEndHandler()},reader.readAsDataURL(file)}function onLoadEndHandler(image){repository.createMultiple(repository.apiData.image.url,files).then(function(imageResult){var newGuidImage=imageResult[0].Guid,changeUserImageDto={GuidImage:newGuidImage,GuidUser:$scope.model.Guid};repository.createSingle(repository.apiData.user.urlChangeImage,changeUserImageDto).then(function(result){$scope.model.GuidImage=newGuidImage,$scope.model.Guid===$rootScope.userInfo.guidUser&&($rootScope.userInfo.guidImage=newGuidImage,$localStorage.userData.guidImage=newGuidImage),repository.growl("Bilde oppdatert","success")},function(error){repository.growl(error,"danger")})},function(error){repository.growl(error,"danger")})}var files=[];handleFileUpload(croppedImage)})}},$scope.changePassword=function(){$modal.open({templateUrl:"app/common/modal/views/changePasswordModal.html",controller:"ChangePasswordModalController",size:"sm",resolve:{params:function(){return{user:$scope.model}}}}).result.then(function(newPassword){newPassword&&($scope.model.Password=newPassword,$scope.updateUser("user.edit"))})},$scope.externalLoginProviderTable=new ngTableParams({page:1,count:-1,filter:{}},{total:0,filterDelay:10,counts:!1,getData:function($defer,params){repository.GetPaginated(repository.apiData.externalLoginProvider.url+"user/"+$scope.model.Guid,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify([])).then(function(result){$scope.externalLoginProviderTable.settings().total=result.length,$scope.externalLoginProviderTable.settings().filterDelay=500,$defer.resolve(result)},function(error){repository.growl(error,"danger")})}}),$scope.userXExternalLoginContextMenuOptions=function(item){var options=[];return 0===item.UserXExternalLogins.length&&$scope.userInfo.guidUser===$scope.model.Guid&&options.push({html:' '+translationService.translate("web-userXExternalLogin-contextMenuOption-add","Legg til")+"",click:function(){swal({title:translationService.translate("web-swal-userXExternalLogin-areyousure","Registrering av ekstern innlogging"),text:translationService.translate("web-swal-userXExternalLogin-add-message","Du vil nå navigeres til ekstern innlogging. Ved fullført innlogging vil brukeren din i Plania knyttes opp mot den eksterne innloggingen"),type:"info",showCancelButton:!0,confirmButtonColor:"#337ab7",confirmButtonText:translationService.translate("web-swal-userXExternalLogin-add-button-confirm","Fortsett"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.authService.authenticateLoginProviderWhileLoggedIn(item)})}}),item.UserXExternalLogins.length>0&&options.push({html:' '+translationService.translate("web-userXExternalLogin-contextMenuOption-delete","Slett")+"",click:function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-userXExternalLogin-delete-message","Ekstern innlogging vil bli fjernet og bruker må knytte til ekstern innlogging på ny"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-userXExternalLogin-delete-button-confirm","Fjern ekstern innlogging"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null;var userXExternalLogin=_.find(item.UserXExternalLogins,function(login){return login.GuidUser===$scope.model.Guid});userXExternalLogin&&repository.deleteSingle(repository.apiData.userXExternalLogin.url,userXExternalLogin.Guid).then(function(result){swal.close(),repository.growl(translationService.translate("web-swal-userXExternalLogin-delete-successToaster","Ekstern innlogging fjernet"),"success"),$scope.externalLoginProviderTable.reload()})})}}),options}}angular.module("Plania").controller("UserController",["$scope","TranslationService","Repository","$modal","$stateParams","ngTableParams","$localStorage","$rootScope","ListService","Constants",controller])}(),function(){function controller($scope,$modal,repository,translationService){$scope.webProfiles=[],$scope.isChanging=!1,$scope.treeOptions={dropped:function(event){if(!event.dest.nodesScope.$parent.nodropEnabled){var draggedDown=event.source.index>event.dest.index,startIndex=draggedDown?event.dest.index:event.source.index,endIndex=draggedDown?event.source.index:event.dest.index;startIndex!==endIndex&&setTimeout(function(){reorderAndSave(startIndex,endIndex)},0)}}};var getWebProfiles=function(){repository.GetPaginated(repository.apiData.userXWebProfile.url,0,-1,{IndexPosition:"asc"},{PropertyFilter:[{Property:"GuidUser",operator:"=",value:$scope.user.Guid}]}).then(function(profileResult){profileResult&&($scope.webProfiles=profileResult.List),$scope.isChanging=!1},function(error){$scope.isChanging=!1,repository.growl(error,"danger")})};getWebProfiles(),$scope.$watch("user.Guid",function(newValue,oldValue){newValue!==oldValue&&getWebProfiles()});var hasDuplicateIndexPositions=function(){for(var indexPositions=[],i=0;i<$scope.webProfiles.length;i++){var indexPosition=$scope.webProfiles[i].IndexPosition;if(indexPositions.includes(indexPosition))return!0;indexPositions.push(indexPosition)}return!1},reorderAndSave=function(startIndex,endIndex){if(0!==$scope.webProfiles.length&&((void 0===startIndex||startIndex>=$scope.webProfiles.length)&&(startIndex=0),(void 0===endIndex||endIndex<=startIndex)&&(endIndex=$scope.webProfiles.length-1),hasDuplicateIndexPositions()&&(startIndex=0,endIndex=$scope.webProfiles.length-1),!(endIndex<=startIndex))){for(var changeList=[],i=startIndex;i<=endIndex;i++){var webProfile=$scope.webProfiles[i];webProfile.IndexPosition=i,changeList.push({Guid:webProfile.Guid,IndexPosition:webProfile.IndexPosition})}$scope.isChanging=!0,repository.patch(repository.apiData.userXWebProfile.url,null,changeList).then(function(response){var success=_.every(response,function(response){return response.IsSuccess});$scope.isChanging=!1,success?repository.growl(translationService.translate("web-userXWebProfile-reorderAndSave-success","Webprofiler har blitt oppdatert"),"success"):repository.growl(translationService.translate("web-userXWebProfile-reorderAndSave-failed","En eller flere webprofiler ble ikke oppdatert"),"danger")},function(error){$scope.isChanging=!1,repository.showError(error)})}},getHighestIndexPosition=function(){if(0===$scope.webProfiles.length)return 0;var maxWebProfile=_.max($scope.webProfiles,function(webProfile){return webProfile.IndexPosition});return maxWebProfile?maxWebProfile.IndexPosition:0};$scope.addWebProfile=function(){if(!$scope.isChanging){var alreadySavedGuids=_.map($scope.webProfiles,"GuidWebProfile");$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Velg webprofil",columns:[{Title:translationService.translate("web-webProfile-id"),Property:"Id"},{Title:translationService.translate("web-webProfile-description"),Property:"Description"}],useObjects:!1,url:repository.apiData.webProfile.url,sorting:{Id:"asc"},filter:{},alreadySavedGuids:alreadySavedGuids}}}}).result.then(function(selectedEntities){var toSave=_.difference(selectedEntities,alreadySavedGuids),i=getHighestIndexPosition(),userXWebProfiles=_.map(toSave,function(entity){return{GuidUser:$scope.user.Guid,GuidWebProfile:entity,IndexPosition:i++}});$scope.isChanging=!0,repository.createMultiple(repository.apiData.userXWebProfile.url,userXWebProfiles).then(function(result){repository.growl("Webprofiler har blitt lagt til","success"),getWebProfiles()},function(error){$scope.isChanging=!1,repository.growl(error,"danger")})})}},$scope.removeWebProfile=function(profile){$scope.isChanging||swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-user-webProfile-message","profilen vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-user-webprofile-button-confirm","Ja, fjern profilen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.isChanging=!0,repository.deleteSingle(repository.apiData.userXWebProfile.url,profile.Guid).then(function(result){$scope.isChanging=!1,repository.growl(translationService.translate("user-profile-removed-message","Profilen har blitt fjernet"),"success"),_.remove($scope.webProfiles,function(webProfile){return webProfile.Guid===profile.Guid}),reorderAndSave(),swal.close()},function(error){$scope.isChanging=!1,repository.growl(error,"danger")})})}}angular.module("Plania").directive("userxwebprofile",function(){return{restrict:"E",scope:{user:"=user",reload:"=reload",guid:"=guid",restrictEdit:"=restrictEdit"},controller:["$scope","$modal","Repository","TranslationService",controller],templateUrl:"app/userXWebProfile/views/userXWebProfileDirective.html"}})}(),function(){function controller($scope,translationService,repository,$modal,$stateParams,ngTableParams,listService,$localStorage){function setTwoFactorStatus(){$scope.twoFactor={},$localStorage.generalOptions.TwoFactorAuthenticationOption<=0?($scope.twoFactor.isEnabled=!1,$scope.twoFactor.canChange=!1,$scope.twoFactor.statusText=translationService.translate("web-usergroup-twofactor-disabled","Tofaktor er avskrudd fra system")):2===$localStorage.generalOptions.TwoFactorAuthenticationOption?($scope.twoFactor.isEnabled=!0,$scope.twoFactor.canChange=!1,$scope.twoFactor.statusText=translationService.translate("web-usergroup-twofactor-enabled","Tofaktor er påskrudd fra system")):$scope.twoFactor.canChange=!0}$scope.update="usergroup.edit"===$scope.navigation.current.name,$scope.model={ Guid:$stateParams.guid},$scope.activateAutocomplete=!$scope.update,$scope.webProfiles=[],$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)},$scope.userColumns=[{Position:1,Title:translationService.translate("web-userGroup-RealName","Navn"),Property:"RealName",PropertyType:"string"},{Position:2,Title:translationService.translate("web-userGroup-UserName","Brukernavn"),Property:"Username",PropertyType:"string"}];var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.User,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.User,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.User),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.User);$scope.hasProjectManagementModule=$scope.hasModule("ProjectManagement")};updateAccess(),setTwoFactorStatus(),$scope.AddUsers=function(){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Velg brukere",columns:[{Title:translationService.translate("web-user-username"),Property:"Username"},{Title:translationService.translate("web-user-realName"),Property:"RealName"}],useObjects:!1,url:repository.apiData.user.url,sorting:{Username:"asc"},filter:{},alreadySavedGuids:_.map($scope.userTable.data,"Guid")}}}}).result.then(function(selectedEntities){var editedRows=[];selectedEntities.forEach(function(guid){editedRows.push({Guid:guid,GuidUserGroup:$scope.model.Guid})}),repository.patch(repository.apiData.user.url,null,editedRows).then(function(response){if(_.every(response,function(response){return response.IsSuccess}))repository.growl(translationService.translate("web-userGroup-addUser-success","Brukere har blitt lagt til brukergruppen"),"success");else{repository.growl(translationService.translate("web-userGroup-addUser-failed","En eller flere brukere ble ikke lagt til i brukergruppen"),"danger");var errorMessages=_.pluck(response,"ErrorMessage").join(", ");swal({title:"Feil ved lagring",text:errorMessages,type:"warning",closeOnConfirm:!0,closeOnCancel:!0})}$scope.userTable.reload()},function(error){repository.showError(error)})})},$scope.removeUser=function(user){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-usergroup-user-message","Brukeren vil bli fjernet fra gruppen!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-usergroup-user-button-confirm","Ja, fjern brukeren!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.patch(repository.apiData.user.url,user.Guid,{GuidUserGroup:null}).then(function(response){repository.growl(translationService.translate("web-swal-usergroup-user-success","Brukeren ble fjernet!"),"success"),$scope.userTable.reload(),swal.close()},function(error){repository.showError(error)})})},$scope.userTable=new ngTableParams({page:1,count:10,sorting:{RealName:"asc"},filter:{PropertyFilter:[{Property:"GuidUserGroup",Operator:"=",value:$scope.model.Guid},{Property:"IsUserGroup",Operator:"=",value:0}]}},{total:0,counts:[10,20,50],filterDelay:10,paginationMaxBlocks:6,getData:function($defer,params){var columns=[];$scope.userColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.user.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.userTable.settings().total=result.TotalCount,$scope.userTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.access={Desktop:!1,Web:!1,Mobile:!1,ReadOnlyWeb:!1};var setUserAccess=function(access){access.indexOf("Desktop")>=0&&($scope.access.Desktop=!0),access.indexOf("Web")>=0&&($scope.access.Web=!0),access.indexOf("Mobil")>=0&&($scope.access.Mobile=!0),access.indexOf("ReadOnlyWeb")>=0&&($scope.access.ReadOnlyWeb=!0)},GetUserAccess=function(){var access=0;return $scope.access.Desktop&&(access|=1),$scope.access.Web&&(access|=2),$scope.access.Mobile&&(access|=4),$scope.access.ReadOnlyWeb&&(access|=8),access};repository.GetPaginated(repository.apiData.webMenu.url,0,1e3,{Name:"asc"},{},"",JSON.stringify(["Name"])).then(function(result){var availableMenus=[];availableMenus.push({text:"Ingen",guid:null}),result.List.length>0&&result.List.forEach(function(webMenu){webMenu.IsBuildingDependent||availableMenus.push({text:webMenu.Name,guid:webMenu.Guid})}),$scope.availableStartPages=availableMenus,$scope.model.GuidWebmenu&&($scope.selectedStartMenu=_.filter($scope.availableStartPages,{guid:$scope.model.GuidWebMenu})[0]||availableMenus[0])}),$scope.update?repository.getSingle(repository.apiData.user.url,$stateParams.guid).then(function(result){$scope.model=result.Data,$scope.reload=!0,updateAccess(),setUserAccess($scope.model.AccessType),$scope.availableStartPages&&($scope.selectedStartMenu=_.filter($scope.availableStartPages,{guid:$scope.model.GuidWebMenu})[0]||$scope.availableStartPages[0]),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}):$scope.model.IsUserGroup=!0,$scope.GuidChangeLanguage=function(selectedLanguage){$scope.model.GuidLanguage=selectedLanguage.Guid},$scope.changeStartPage=function(selected){$scope.model.GuidWebMenu=selected.guid},$scope.deleteUserGroup=function(destination,userGroup){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-usergroup-message","Brukergruppen vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-usergroup-button-confirm","Ja, fjern brukergruppen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.user.url,userGroup.Guid).then(function(result){repository.growl(translationService.translate("delete-usergroup-success-message","brukergruppen ble slettet fra systemet"),"success"),swal.close(),$scope.goBack(destination,{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.updateUserGroup=function(destination){$scope.model.AccessType=GetUserAccess();var success=function(result){repository.growl($scope.update?"Brukergruppe har blitt oppdatert":translationService.translate("create-userGroup-success","Brukergruppen har blitt registrert."),"success");var guid=$scope.update?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})},error=function(error){repository.growl(error,"danger")};$scope.update?repository.updateSingle(repository.apiData.user.url,$scope.model).then(success).catch(error):repository.createSingle(repository.apiData.user.url,$scope.model).then(success).catch(error)},$scope.userProfileInfo=new function(){var me=this;this.data=[],this.totalCount=0,this.search={},this.columns=[{Position:1,Title:translationService.translate("user-clientTable-dataOwnerName","Klient"),Property:"LinkedDataOwner.Description",PropertyType:"string"},{Position:2,Title:translationService.translate("user-clientTable-userProfileName","Profil"),Property:"EntityPermissionProfile.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("user-clientTable-userProfileDescription","Profilbeskrivelse"),Property:"EntityPermissionProfile.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("user-clientTable-updatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}],this.defaultDataOwner={profile:null,hasError:!1,title:"",message:""},this.getData=function(){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("IsDefaultDataOwner");var filter={FilterModel:{Property:"GuidUser",Operator:"=",Value:$scope.model.Guid}};repository.GetPaginated(repository.apiData.userProfile.url,0,-1,null,filter,null,JSON.stringify(columns)).then(function(result){me.data=result.List,me.totalCount=result.TotalCount,me.table.reload();var defaultDataOwner=_.filter($scope.userProfileInfo.data,{IsDefaultDataOwner:!0})[0];if(defaultDataOwner)if(defaultDataOwner.GuidEntityPermissionProfile){var caption="";defaultDataOwner.LinkedDataOwner.Description&&(caption+=defaultDataOwner.LinkedDataOwner.Description),defaultDataOwner.EntityPermissionProfile.Id&&(caption&&(caption+=" - "),caption+=defaultDataOwner.EntityPermissionProfile.Id),me.defaultDataOwner={profile:defaultDataOwner,hasError:!1,status:"ok",caption:caption}}else me.defaultDataOwner={hasError:!0,status:"missingEntityPermission"};else me.data.length?me.defaultDataOwner={hasError:!0,status:"missingUserProfiles"}:me.defaultDataOwner={hasError:!0,status:"missingDefaultDataOwner"}},function(error){repository.showError(error)})};var getValue=function(entity,property){var value=entity;return property.split(".").forEach(function(prop){null!==value&&void 0!==value&&(value=value[prop])}),value},getFilteredData=function(filter){var data=me.data;if(void 0===filter.searchString)return data;var filterText=filter.searchString.toLowerCase();return data=data.filter(function(item){if(void 0===filterText||null===filterText||""===filterText.trim())return!0;var state=!1;return me.columns.forEach(function(column){(""+getValue(item,column.Property)).toLowerCase().includes(filterText)&&(state=!0)}),state})};this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:20,filter:{searchParams:""},sorting:{"LinkedDataOwner.Description":"asc"}},{total:0,filterDelay:10,counts:[20,50,100,200],getData:function($defer,params){var data=getFilteredData(params.filter()),sortingKey=Object.keys(params.sorting())[0];if(sortingKey){data=_.sortBy(data,sortingKey);"desc"===params.sorting()[sortingKey].toLowerCase()&&(data=data.reverse())}me.table.settings().total=data.length,me.table.settings().filterDelay=500,data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$defer.resolve(data)}}))},this.add=function(){me.canAdd()&&$modal.open({templateUrl:"app/user/views/editUserDataOwner.html",controller:"CreateUserDataOwnerController",resolve:{params:function(){return{guidUser:$scope.model.Guid,isFirst:me.data.length<1}}}}).result.then(function(userProfile){userProfile&&userProfile.IsDefaultDataOwner&&($scope.model.GuidDefaultDataOwner=userProfile.GuidLinkedDataOwner),me.getData()})},this.update=function(entity){me.canEdit(entity)&&($scope.restrictEdit||$scope.model.GuidUserGroup||$modal.open({templateUrl:"app/user/views/editUserDataOwner.html",controller:"EditUserDataOwnerController",resolve:{params:function(){return{guidUserProfile:entity.Guid}}}}).result.then(function(userProfile){userProfile&&userProfile.IsDefaultDataOwner&&($scope.model.GuidDefaultDataOwner=userProfile.GuidLinkedDataOwner),me.getData()}))},this.remove=function(entity){me.canDelete(entity)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-usergroup-dataOwner-message","Klienten vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-usergroup-dataOwner-button-confirm","Ja, fjern klienten!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.userProfile.url,entity.Guid).then(function(result){swal.close(),repository.growl(translationService.translate("usergroup-removeDataOwner-Success","Klient ble fjernet fra brukergruppen."),"success"),me.getData()})})},this.contextMenuOptions=function(item){var options=[];return me.canEdit(item)&&options.push({html:' '+translationService.translate("web-user-userProfile-edit","Rediger klienttilgang")+"",click:function(){me.update(item)}}),$scope.hasReadAccess("DataOwner")&&options.push({html:' '+translationService.translate("web-user-viewDataOwner","Gå til klient")+"",isHref:!0}),$scope.hasReadAccess("EntityPermissionProfile")&&options.push({html:' '+translationService.translate("web-user-viewEntityPermissionProfile","Gå til rettighetsprofil")+"",isHref:!0}),me.canDelete(item)&&options.push({html:' '+translationService.translate("web-user-dataOwner-delete","Slett klient")+"",click:function(){me.remove(item)},hasTopDivider:!0}),options},this.canAdd=function(){return!$scope.restrictEdit&&!$scope.model.GuidUserGroup},this.canEdit=function(entity){return entity&&!$scope.restrictEdit&&!$scope.model.GuidUserGroup},this.canDelete=function(entity){return entity&&!$scope.restrictEdit&&!$scope.model.GuidUserGroup},$scope.update&&(me.initTable(),me.getData())},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("UserGroupController",["$scope","TranslationService","Repository","$modal","$stateParams","ngTableParams","ListService","$localStorage",controller])}(),function(){function controller($scope,$modalInstance,parentParams,repository,ngTableParams,$filter,documentService){$scope.activateAutocomplete=!1,$scope.documentsTable=new ngTableParams({page:1,count:10,sorting:{id:"asc"},filter:{isBuildingDependent:!1}},{total:0,counts:[10,25,50],paginationMaxBlocks:5,getData:function($defer,params){repository.GetPaginated(repository.apiData.videoXEntity.url,params.page()-1,params.count(),params.sorting(),params.filter()).then(function(result){params.total(result.TotalCount);var sortedResult=params.sorting()?$filter("orderBy")(result.List,params.orderBy()):result.List;$defer.resolve(sortedResult),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})}});var selectedDocuments=[];$scope.saveDocument=function(){var documentXEntities=[];selectedDocuments.forEach(function(guid){documentXEntities.push({Guid:guid,GuidCleaningTask:parentParams.guidCleaningTask,Entity:-1})}),repository.createMultiple(repository.apiData.videoXEntity.url,documentXEntities).then(function(result){repository.growl("Dokumentene har blitt lagt til","success"),$modalInstance.close("OK")})},$scope.addDocument=function(guid){if(_.contains(selectedDocuments,guid))for(var i=0;i=file.total?"success":"info")})},$scope.ok=function(result){$modalInstance.close(result)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CreateVideoXEntityController",["$scope","Repository","$modalInstance","params",controller])}(),function(){function controller($scope,repository,params,authService,$modalInstance){$scope.update=!0,$scope.restrictEdit=!authService.hasEditAccess("Video"),repository.getSingle(repository.apiData.video.url,params.guid).then(function(response){$scope.model=response.Data},function(error){repository.growl(error.Data?error.Data.message:error.Message,"danger")}),$scope.save=function(){repository.updateSingle(repository.apiData.video.url,$scope.model).then(function(){repository.growl("Videoen ble lagret","success"),$modalInstance.close("Ok")},function(error){repository.growl(error.Data?error.Data.message:error.Message,"danger")})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("EditVideoXEntityController",["$scope","Repository","params","authService","$modalInstance",controller])}(),function(){function controller($scope,$modalInstance,params,repository,config){$scope.videoSrc=config.baseUrlApi+"videodata/"+params.guidVideoBinary,$scope.video=params.video,$scope.loadMediaElement=function(){var player=new MediaElementPlayer("#videoPlayer",{});player.pause(),player.setSrc($scope.videoSrc),player.features=[],player.load(),player.play()},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("VideoPlayerModalController",["$scope","$modalInstance","params","Repository","config",controller])}(),function(){function controller($scope,translationService,repository,$modal,$stateParams,ngTableParams,listService,$localStorage){$scope.model={Guid:$stateParams.guid},$scope.isUpdate=!0,$scope.columnView={raw:!1},$scope.toggleRawColumn=function(){$scope.columnView.raw=!$scope.columnView.raw};var updateAccess=function(){if($scope.isUpdate){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.WebListView,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.WebListView,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.WebListView),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.WebListView)};updateAccess(),repository.getSingle(repository.apiData.webListView.url,$stateParams.guid,JSON.stringify(["User.RealName","User.Username","UserUpdatedBy.RealName","UserUpdatedBy.Username"])).then(function(result){if($scope.model=result.Data,$scope.model.Sorting)try{$scope.model.Sorting=JSON.parse($scope.model.Sorting)}catch(ex){}$scope.model.Columns&&$scope.model.Columns.forEach(function(col){if(col.Filter)try{col.Filter=JSON.parse(col.Filter)}catch(ex){}}),$scope.reload=!0,updateAccess(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}),$scope.getOperatorName=function(operator){var name="Ukjent funksjon";switch(operator){case"=":name=translationService.translate("web-filterOperatorSelect-operator-equal","=");break;case"<>":name=translationService.translate("web-filterOperatorSelect-operator-notEqual","<>");break;case">":name=translationService.translate("web-filterOperatorSelect-operator-greaterThan",">");break;case"<":name=translationService.translate("web-filterOperatorSelect-operator-lessThan","<");break;case">=":name=translationService.translate("web-filterOperatorSelect-operator-greaterThanOrEqual",">=");break;case"<=":name=translationService.translate("web-filterOperatorSelect-operator-lessThanOrEqual","<=");break;case"&":name=translationService.translate("web-filterOperatorSelect-operator-bitwiseAnd","&");break;case"startswith":name=translationService.translate("web-filterOperatorSelect-operator-startswith","startswith");break;case"in":name=translationService.translate("web-filterOperatorSelect-operator-in","in");break;case"notin":name=translationService.translate("web-filterOperatorSelect-operator-notin","notin");break;case"contains":name=translationService.translate("web-filterOperatorSelect-operator-contains","contains")}return name},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("WebListViewController",["$scope","TranslationService","Repository","$modal","$stateParams","ngTableParams","ListService","$localStorage",controller])}(),function(){function controller($scope,$modalInstance,params,repository,ngTableParams){var filter={};params.excludeGuids&¶ms.excludeGuids.length>0?filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:params.excludeGuids.join(",")},{Property:"GuidUserGroup",operator:"=",value:""}]:filter.PropertyFilter=[{Property:"GuidUserGroup",operator:"=",value:""}],$scope.userTable=new ngTableParams({page:1,count:10,sorting:{RealName:"asc"},filter:filter},{total:0,paginationMaxBlocks:5,counts:[10,25,50],getData:function($defer,params){repository.GetPaginated(repository.apiData.user.url,params.page()-1,params.count(),params.sorting(),params.filter()).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}});var selectedUsers=[];$scope.saveUser=function(){repository.createMultiple(repository.apiData.userXWebProfile.url,selectedUsers).then(function(result){repository.growl("Brukeren har blitt lagt til profilen","success"),$modalInstance.close("OK")})},$scope.addUser=function(guid){if(_.contains(selectedUsers,guid))for(var i=0;ievent.dest.index,startIndex=draggedDown?event.dest.index:event.source.index,endIndex=draggedDown?event.source.index:event.dest.index;startIndex!==endIndex&&setTimeout(function(){reorderAndSave(startIndex,endIndex)},0)}}};var hasDuplicateIndexPositions=function(){var indexPositions=[];try{for(var i=0;i<$scope.menus.length;i++){var indexPosition=$scope.menus[i].IndexPosition;if(indexPositions.includes(indexPosition))return!0;indexPositions.push(indexPosition)}return!1}catch(error){return!1}},reorderAndSave=function(startIndex,endIndex){if(0!==$scope.menus.length&&((void 0===startIndex||startIndex>=$scope.menus.length)&&(startIndex=0),(void 0===endIndex||endIndex<=startIndex)&&(endIndex=$scope.menus.length-1),hasDuplicateIndexPositions()&&(startIndex=0,endIndex=$scope.menus.length-1),!(endIndex<=startIndex))){for(var changeList=[],i=startIndex;i<=endIndex;i++){var menu=$scope.menus[i];menu.IndexPosition=i,changeList.push({Guid:menu.Guid,IndexPosition:menu.IndexPosition})}$scope.isWebMenusChanging=!0,repository.patch(repository.apiData.webProfileWebMenu.url,null,changeList).then(function(response){var success=_.every(response,function(response){return response.IsSuccess});$scope.isWebMenusChanging=!1,success?repository.growl(translationService.translate("web-webProfile-reorderAndSave-success","Webmenyene har blitt oppdatert"),"success"):repository.growl(translationService.translate("web-webProfile-reorderAndSave-failed","En eller flere webmenyer ble ikke oppdatert"),"danger")},function(error){$scope.isWebMenusChanging=!1,repository.showError(error)})}},getHighestIndexPosition=function(){if(0===$scope.menus.length)return 0;var maxMenu=_.max($scope.menus,function(menu){return menu.IndexPosition});return maxMenu?maxMenu.IndexPosition:0};$scope.openIconModal=function(){$modal.open({templateUrl:"app/common/modal/views/selectIconModal.html",controller:"SelectIconModalController"}).result.then(function(selectedIcon){$scope.model.Icon=selectedIcon})},$scope.addMenu=function(){$scope.isWebMenusChanging||$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",resolve:{modalParams:function(){return{title:"Legg til web meny",url:repository.apiData.webMenu.url,sorting:{Name:"asc"},columns:[{Title:translationService.translate("web-webMenu-name"),Property:"Name",PropertyType:"string"},{Title:translationService.translate("web-webMenu-description"),Property:"Description",PropertyType:"string"}],useObjects:!1}}}}).result.then(function(menuGuids){var i=getHighestIndexPosition(),menus=_.map(menuGuids,function(menuGuid){return{GuidWebMenu:menuGuid,GuidWebProfile:$scope.model.Guid,IndexPosition:i++}});$scope.isWebMenusChanging=!0,repository.createMultiple(repository.apiData.webProfileWebMenu.url,menus).then(function(result){$scope.isWebMenusChanging=!1,repository.growl(translationService.translate("web-webProfile-addMenu-success","Webprofiler har blitt lagt til"),"success"),getMenus()},function(error){$scope.isWebMenusChanging=!1,repository.growl(error,"danger")})})},$scope.removeMenu=function(webProfileXWebMenu){$scope.isWebMenusChanging||swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-webprofile-webmenu-message","Menyen vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-webprofile-webmenu-button-confirm","Ja, fjern menyen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.isWebMenusChanging=!0,repository.deleteSingle(repository.apiData.webProfileWebMenu.url,webProfileXWebMenu.Guid).then(function(result){$scope.isWebMenusChanging=!1,swal(translationService.translate("web-swal-webprofile-webmenu-success","Menyen ble fjernet!"),result,"success"),_.remove($scope.menus,function(webProfile){return webProfile.Guid===webProfileXWebMenu.Guid}),reorderAndSave(),swal.close()},function(error){$scope.isWebMenusChanging=!1,repository.growl(error,"danger")})})},$scope.removeUser=function(user){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-webprofile-user-message","Brukeren vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-webprofile-user-button-confirm","Ja, fjern brukeren!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null, repository.deleteSingle(repository.apiData.userXWebProfile.url,user.Guid).then(function(result){swal(translationService.translate("web-swal-webprofile-user-success","Brukeren ble fjernet!"),result,"success"),repository.growl("Brukeren har blitt fjernet","success"),$scope.userTable.reload()})})},$scope.addUser=function(){var alreadySavedGuids=_.map($scope.userTable.data,"GuidUser");$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:"lg",resolve:{modalParams:function(){var propertyFilter=[{Property:"GuidUserGroup",Operator:"=",Value:""},{Property:"IsUserGroup",Operator:"=",Value:1,allowToggle:!0,filterValue:"Brukergruppe",isDisabled:!0}];return{title:"Velg bruker",columns:[{Title:translationService.translate("web-user-username"),Property:"Username"},{Title:translationService.translate("web-user-realName"),Property:"RealName"}],useObjects:!1,url:repository.apiData.user.url,sorting:{Username:"asc"},filter:{PropertyFilter:propertyFilter},alreadySavedGuids:alreadySavedGuids}}}}).result.then(function(selectedEntities){var toSave=_.difference(selectedEntities,alreadySavedGuids),userXWebProfiles=_.map(toSave,function(entity){return{GuidUser:entity,GuidWebProfile:$scope.model.Guid,IndexPosition:999}});repository.createMultiple(repository.apiData.userXWebProfile.url,userXWebProfiles).then(function(result){$scope.userTable.reload()},function(error){repository.growl(error,"danger")})})},$scope.removeWebProfile=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-webprofile-message","MenyProfilen vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-webprofile-button-confirm","Ja, fjern Menyprofilen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.webProfile.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-webprofile-success","MenyProfilen ble fjernet!"),result,"success"),repository.growl(translationService.translate("Web-profile-deleted-message","Web profilen har blitt slettet."),"success"),$scope.goBack("webProfile.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.$on($scope.events.newSelection,function(){updateAccess(),getMenus(),$scope.userTable&&$scope.userTable.reload&&$scope.userTable.reload()})}angular.module("Plania").controller("WebProfileController",["$scope","Repository","$stateParams","ngTableParams","$modal","TranslationService","IconService",listController])}(),function(){function controller($scope,$modalInstance,translationService,registeredFieldService,repository){if($scope.model.EndDate=$scope.model.EndDate?$scope.model.EndDate:new Date,$scope.workOrderXResourceGroup={},$scope.viewMode=!1,$scope.registeredTime={},$scope.userInfo.guidPerson&&$scope.hasReadAccess("WorkOrderXResourceGroup")){var kpiPropertyTotal={Prefix:"WorkOrderXResourceGroup",FromDate:new Date(0).toISOString(),ToDate:null,PropertyFilter:[{Property:"GuidWorkOrder",Value:$scope.model.Guid,Operator:"="},{Property:"GuidPerson",Value:$scope.userInfo.guidPerson,Operator:"="}],Properties:[{Property:"RealTime",Function:"sum"}]},kpiPropertyToday={Prefix:"WorkOrderXResourceGroup",FromDate:new Date(0).toISOString(),ToDate:null,PropertyFilter:[{Property:"GuidWorkOrder",Value:$scope.model.Guid,Operator:"="},{Property:"GuidPerson",Value:$scope.userInfo.guidPerson,Operator:"="},{Property:"RegisteredDate",Value:new Date((new Date).setHours(0,0,0,0)).toISOString(),Operator:"="}],Properties:[{Property:"RealTime",Function:"sum"}]};repository.createSingle(repository.apiData.kpi.url,kpiPropertyTotal).then(function(result){$scope.registeredTime.Total=result[0].Result[0].Value}),repository.createSingle(repository.apiData.kpi.url,kpiPropertyToday).then(function(result){$scope.registeredTime.Today=result[0].Result[0].Value})}var getGroupMandatoryDynamicProperties=function(group){var mandatoryProperties=[];return group.Items.forEach(function(item){item.Mandatory&&!$scope.model[item.PropertyName]&&mandatoryProperties.push(item),"Category"===item.Type&&item.Template.Groups.forEach(function(templateGroup){var groupProps=getGroupMandatoryDynamicProperties(templateGroup);mandatoryProperties=mandatoryProperties.concat(groupProps)})}),mandatoryProperties},getMandatoryDynamicProperties=function(){var mandatoryProperties=[];return $scope.model.DynamicProperty&&$scope.model.DynamicProperty.Groups.forEach(function(group){var groupProps=getGroupMandatoryDynamicProperties(group);mandatoryProperties=mandatoryProperties.concat(groupProps)}),mandatoryProperties};registeredFieldService.getRegisteredField(repository.commonService.prefix.WorkOrderXResourceGroup).then(function(result){$scope.workOrderXResourceGroupNoteIsMandatory=!1,$scope.workOrderXResourceGroupGuidHourTypeIsMandatory=!1,result.forEach(function(o){"Note"===o.DomainFieldName&&($scope.workOrderXResourceGroupNoteIsMandatory=o.Mandatory),"GuidHourType"===o.DomainFieldName&&($scope.workOrderXResourceGroupGuidHourTypeIsMandatory=o.Mandatory)})}),registeredFieldService.getRegisteredField(repository.commonService.prefix.WorkOrder).then(function(result){var mandatoryFields=_.filter(result,function(o){return"Id"!==o.DomainFieldName&&("RealTime"===o.DomainFieldName||"RealCost"===o.DomainFieldName||"EstimatedTime"===o.DomainFieldName||"EstimatedCost"===o.DomainFieldName?!($scope.resourceGroupInfo.table.total()>0)&&o.Mandatory:o.Mandatory&&!$scope.model[o.DomainFieldName])});$scope.mandatoryDynamicProperties=getMandatoryDynamicProperties();var mappedLabels=_.map(mandatoryFields,function(o){return{FieldName:o.DomainFieldName,translatedValue:translationService.translate("web-workorder-"+o.DomainFieldName.replace("Guid","")).replace(":","")}});mappedLabels.push.apply(mappedLabels,_.map($scope.mandatoryDynamicProperties,function(o){return{FieldName:o.PropertyName,translatedValue:o.LabelPropertyValue.replace(":","")}})),$scope.mandatoryProperties=mappedLabels}),$scope.isMandatory=function(property){return _.find($scope.mandatoryProperties,function(o){return o.FieldName===property})};var getSwalPopup=function(title,text,confirmText,cancelText,onConfirm){swal({title:title,text:text,type:"warning",showCancelButton:!!cancelText,confirmButtonColor:"#f44336",confirmButtonText:confirmText,cancelButtonText:cancelText,closeOnConfirm:!0,showLoaderOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,setTimeout(function(){onConfirm&&"function"==typeof onConfirm&&onConfirm()},100)})};$scope.saveAction=function(){if(!$scope.model.EndDate)return void getSwalPopup(translationService.translate("web-workOrderCompletionModal-swal-missingEndDate-title","Sluttdato er ikke satt."),translationService.translate("web-workOrderCompletionModal-swal-missingEndDate-text","Ønsker du å sette sluttdato til dagens dato? Sluttdato er påkrevd for fullføring."),translationService.translate("web-workOrderCompletionModal-swal-missingEndDate-confirm","Ja"),translationService.translate("web-workOrderCompletionModal-swal-missingEndDate-cancel","Nei"),function(){$scope.model.EndDate=new Date,$scope.saveAction()});if($scope.workOrderXResourceGroup.RealTime>0){if($scope.workOrderXResourceGroupNoteIsMandatory&&!$scope.workOrderXResourceGroup.Note)return void getSwalPopup(translationService.translate("web-workOrderCompletionModal-swal-missingWoXResourceNote-title","Mangler kommentar til timeføring."),translationService.translate("web-workOrderCompletionModal-swal-missingWoXResourceNote-text","Vennligst skriv en kommentar til timeføringen."),translationService.translate("web-workOrderCompletionModal-swal-missingWoXResourceNote-confirm","Ok"));if($scope.workOrderXResourceGroupGuidHourTypeIsMandatory&&!$scope.workOrderXResourceGroup.GuidHourType)return void getSwalPopup(translationService.translate("web-workOrderCompletionModal-swal-missingWoXResourceHourType-title","Mangler timetype til timeføring."),translationService.translate("web-workOrderCompletionModal-swal-missingWoXResourceHourType-text","Vennligst velg en timetype til timeføringen."),translationService.translate("web-workOrderCompletionModal-swal-missingWoXResourceHourType-confirm","Ok"))}$modalInstance.close($scope.workOrderXResourceGroup)},$scope.cancel=function(){$modalInstance.dismiss("canceled")},$scope.$watch("model.DynamicProperty",function(newValue,oldValue){newValue!==oldValue&&($scope.mandatoryDynamicProperties=getMandatoryDynamicProperties())})}angular.module("Plania").controller("CompleteWorkOrderModalController",["$scope","$modalInstance","TranslationService","RegisteredFieldService","Repository",controller])}(),function(){function controller($scope,params,repository,ngTableParams,$modalInstance,translationService,listService,$localStorage,$window,$rootScope,registeredFieldService,signalR,$timeout){$scope.initialListSetup=_.cloneDeep(params.SelectedListSetup),$scope.initialListSetup&&($scope.initialListSetup.inMemory=!0),$scope.allRowsSelected=!1,$scope.selectedEntities=[],$scope.isRunningAction=!1,$scope.currentTab="conditions",$scope.InspectedEntityLocation=$localStorage.generalOptions.InspectedEntityLocation,$scope.newWorkOrders=[],$scope.prefill={StartDate:(new Date).toISOString()},$scope.rules={creation:"oneToOne"},$scope.predictedAmountOfWorkOrders=0,$scope.reloadMainTable=!1,$scope.errorMessage=null,$scope.workOrderResponses=[],$scope.totalPredictedWorkOrders=0,$scope.createOneWoPerCondition=!1,$scope.totalFailedWorkOrders=0,$scope.createWorkOrderProgress={};var startSignalRListener=function(){var progressMethodName="createWorkOrdersWithoutValidationProgress";signalR.on(progressMethodName,function(progress){progress.Finished?$timeout(function(){$scope.createWorkOrderProgress=progress},1e3):$scope.createWorkOrderProgress=progress}),$scope.$on("$destroy",function(){signalR.off(progressMethodName)})},workOrderDescriptionMaxLength=50;registeredFieldService.getFieldRule(repository.commonService.prefix.WorkOrder,"Description").then(function(result){workOrderDescriptionMaxLength=result.MaxLength}),listService.getWebListViews($scope.initialListSetup,repository.apiData.condition.prefix,!1,null,{}).then(function(result){$scope.listOptions=result.listOptions,$scope.selectedListSetup=result.selectedListSetup,$scope.conditionTable||($scope.conditionTable=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{PropertyFilter:[{Property:"Status",Operator:"=",Value:0},{Property:"Type",Operator:"=",Value:1},{Property:"GuidCorrectiveWorkOrder",Operator:"=",Value:null}]}},{total:0,filterDelay:10,counts:[10,20,50],paginationMaxBlocks:8,getData:function($defer,params){var columns=[];$scope.selectedListSetup.Columns.forEach(function(col){columns.push(col.Property)}),columns.includes("Id")||columns.push("Id"),columns.includes("ActionComment")||columns.push("ActionComment"),repository.GetPaginated(repository.apiData.condition.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.conditionTable.settings().total=result.TotalCount,$scope.conditionTable.settings().filterDelay=500,params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))}),$scope.$watch("selectedListSetup",function(newValue,oldValue){oldValue!==newValue&&$scope.conditionTable&&($scope.conditionTable.$params.sorting=$scope.selectedListSetup.Sorting,$scope.selectedListSetup.GroupBy?$scope.conditionTable.settings().groupBy=function(obj){return!!$scope.selectedListSetup.GroupBy&&($scope.selectedListSetup.GroupBy.split(".").forEach(function(attr){obj=obj?obj[attr]:""}),obj)}:$scope.conditionTable.settings().groupBy=null,$scope.conditionTable.reload())}),$scope.getPropertyValue=function(entity,field){return listService.GetPropertyValue(entity,field)},$scope.addSelectedEntity=function(entity){if($scope.isItemSelected(entity)){for(var i=0;i<$scope.selectedEntities.length;i++)if($scope.selectedEntities[i].Guid===entity.Guid)return void $scope.selectedEntities.splice(i,1)}else $scope.selectedEntities.push(entity)},$scope.isItemSelected=function(entity){return _.find($scope.selectedEntities,function(e){return e.Guid===entity.Guid})},$scope.resultTable=new ngTableParams({page:1,count:10},{total:$scope.workOrderResponses.length,counts:[5,10,20],getData:function($defer,params){$scope.resultTable.settings().total=$scope.workOrderResponses.length;var paginated=$scope.workOrderResponses.slice((params.page()-1)*params.count(),params.page()*params.count());$defer.resolve(paginated)}}),$scope.getNewWorkOrders=function(){var newWorkOrders=[];if("oneWorkOrder"===$scope.rules.creation)return newWorkOrders.push({}),void($scope.newWorkOrders=newWorkOrders);var groupedConditions=_.groupBy($scope.selectedEntities,function(entity){return"oneToOne"===$scope.rules.creation?entity.Guid:"perBuilding"===$scope.rules.creation?entity.GuidBuilding:"perEstate"===$scope.rules.creation?entity.GuidEstate:null});Object.keys(groupedConditions).forEach(function(grpKey){var conditions=groupedConditions[grpKey],newWorkOrder={GuidEstate:null,GuidBuilding:null,GuidEquipment:null,GuidArea:null,Description:translationService.translate("correctiveAction-new-workOrder-defaultDescription","Gjennomføring av tiltak"),ExplanatoryText:"",ConditionGuids:[],GeneratedFrom:repository.commonService.prefix.Condition};conditions.forEach(function(condition){newWorkOrder.ConditionGuids.push(condition.Guid)}),"oneToOne"===$scope.rules.creation?(newWorkOrder.GuidBuilding=conditions[0].GuidBuilding,newWorkOrder.GuidEstate=conditions[0].GuidEstate,newWorkOrder.GuidEquipment=conditions[0].GuidEquipment,newWorkOrder.GuidArea=conditions[0].GuidArea,newWorkOrder.Description=conditions[0].ActionComment,newWorkOrder.ExplanatoryText=conditions[0].ActionComment):"perBuilding"===$scope.rules.creation?(newWorkOrder.GuidBuilding=grpKey,newWorkOrder.GuidEstate=conditions[0].GuidEstate):newWorkOrder.GuidEstate=grpKey,null!==newWorkOrder.Description&&void 0!==newWorkOrder.Description&&(newWorkOrder.Description=newWorkOrder.Description.substr(0,workOrderDescriptionMaxLength)),newWorkOrders.push(newWorkOrder)}),$scope.newWorkOrders=newWorkOrders},$scope.createWorkOrders=function(){if(!$scope.isRunningAction)if("oneWorkOrder"===$scope.rules.creation){var workOrder={fromCondition:!0,guidSelections:_.map($scope.selectedEntities,function(entity){return entity.Guid}),defaultDescription:translationService.translate("correctiveAction-new-workOrder-defaultDescription","Gjennomføring av tiltak"),defaultStartDate:$scope.prefill.StartDate};repository.persistedData.setPersistedData("workOrder.create",workOrder),$scope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})}else{$scope.getNewWorkOrders();var workOrders=[];$scope.newWorkOrders.forEach(function(wo){wo.StartDate=$scope.prefill.StartDate,workOrders.push(wo)}),$scope.isRunningAction=!0,$scope.reloadMainTable=!0,startSignalRListener(),$scope.currentTab="creationResults",repository.createSingle(repository.apiData.workOrder.endpoint.createWorkOrdersWithoutValidation,workOrders).then(function(result){$scope.isRunningAction=!1,$scope.selectedEntities=[],$scope.conditionTable.reload(),result.forEach(function(workOrder){workOrder.EntityCaption=workOrder.EntityId,workOrder.EntityDescription&&(workOrder.EntityId&&(workOrder.EntityCaption+=" - "),workOrder.EntityCaption+=workOrder.EntityDescription)}),$scope.workOrderResponses=result,$scope.resultTable.reload()},function(error){$scope.isRunningAction=!1,repository.growl(error,"danger")})}},$scope.$watchCollection("selectedEntities",function(newSelections,oldSelections){$scope.getNewWorkOrders()}),$scope.openWorkOrderInNewWindow=function(workOrder){workOrder.CreationDate&&$window.open($rootScope.navigation.href("workOrder.edit",{guid:workOrder.Guid}),"_blank")},$scope.contextMenuOptions=function(item){var options=[];return options.push({html:' '+translationService.translate("web-createWoFromConditionModal-viewWorkorder","Åpne arbeidsordre i ny tab/fane i nettleseren")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.openWorkOrderInNewWindow(item)}}),options},$scope.cancel=function(){$scope.isRunningAction?swal({title:translationService.translate("web-createWoFromConditionModal-swal-title","Vil du lukke dette vinduet?"),text:translationService.translate("web-createWoFromConditionModal-swal-text","Plania vil fortsette å opprette arbeidsordre fra tiltak, men du vil ikke kunne se potensielle feilmeldinger hvis du lukker dette vinduet."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-button-yes-continue","Ja, fortsett"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.reloadMainTable?$modalInstance.close():$modalInstance.dismiss("canceled")}):$scope.reloadMainTable?$modalInstance.close():$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CreateWoFromConditionModalController",["$scope","params","Repository","ngTableParams","$modalInstance","TranslationService","ListService","$localStorage","$window","$rootScope","RegisteredFieldService","SignalR","$timeout",controller])}(),function(){function controller($scope,ngTableParams,$modalInstance,params,repository,listService,translationService){$scope.model={Quantity:0},$scope.isUpdate=params.isUpdate,$scope.isWithdrawal=params.withdraw,$scope.restrictEdit=!1,$scope.restrictEditMessage="",$scope.isLoaded=!1,$scope.info={},$scope.tabs=[{heading:translationService.translate("web-sparepart-chooseSparePart","Velg reservedel"),step:1},{heading:translationService.translate("web-sparepart-setNumber","Sett antall"),step:2}],$scope.modelProperties={quantityToWithdraw:0},$scope.title=$scope.isUpdate?translationService.translate("web-sparepart-edit-title","Rediger reservedel"):translationService.translate("web-sparepart-new-title","Legg til ny reservedel"),$scope.step=$scope.isUpdate?2:1,$scope.setCurrentStep=function(step){$(".tab-content").css("overflow","hidden"),setTimeout(function(){$(".tab-content").css("overflow","visible")},500),$scope.step=step};var sparePartColumns=[{Title:translationService.translate("web-component-id","Id"),Property:"Component.Id"},{Title:translationService.translate("web-component-description","Beskrivelse"),Property:"Component.Description"},{Title:translationService.translate("web-componentXSupplier-partnumber","Delenummer"),Property:"ComponentXSupplier.PartNumber"},{Title:translationService.translate("web-componentXSupplier-Manufacturer","Fabrikat"),Property:"ComponentXSupplier.Manufacturer"},{Title:translationService.translate("web-componentXSupplier-inventory","Beholdning"),Property:"Inventory"},{Title:translationService.translate("web-componentXSupplier-Supplier","Leverandør"),Property:"ComponentXSupplier.Supplier.Description"},{Property:"ComponentXSupplier.Price",hidden:!0},{Property:"Component.Unit",hidden:!0},{Property:"Component.GuidImage",hidden:!0}];$scope.workOrder=params.workOrder;var getSparePartAttachments=function(guidComponent){repository.getWithUrlParameter(repository.apiData.workOrder.endpoint.getSparePartAttachments,"Guid="+$scope.workOrder.Guid+"&GuidComponent="+guidComponent).then(function(result){$scope.info.GuidComponentXEquipment=result.GuidComponentXEquipment,$scope.info.GuidComponentXArea=result.GuidComponentXArea})};if($scope.columns=_.filter(sparePartColumns,function(c){return!c.hidden}),$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.reloadSpareParts=function(){if($scope.isLoaded=!0,$scope.sparePartTable)return void $scope.sparePartTable.reload();$scope.sparePartTable=new ngTableParams({page:1,count:10,sorting:{},filter:{}},{total:0,counts:[10,50,100],paginationMaxBlocks:8,getData:function($defer,params){var columns=_.map(sparePartColumns,"Property"),filter=angular.copy(params.filter());"Equipment"===$scope.info.selectedFilterEntity&&(filter.GuidWorkOrderEquipment=$scope.workOrder.GuidEquipment),"Area"===$scope.info.selectedFilterEntity&&(filter.GuidWorkOrderArea=$scope.workOrder.GuidArea),repository.GetPaginated(repository.apiData.sparePart.url,params.page()-1,params.count(),params.sorting(),filter,null,JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})},$scope.isUpdate){var columns=["SparePart.ComponentXSupplier.PartNumber","SparePart.Inventory","SparePart.Component.Unit","SparePart.Component.GuidImage","SparePart.Component.Id","SparePart.Component.Description","SparePart.Component.Guid","WorkOrder.EndDate","WorkOrder.Stage","WorkOrder.Project.ClosedDate","WorkOrder.Equipment.Id","WorkOrder.Equipment.Description"];repository.getSingle(repository.apiData.workOrderSparePart.url,params.guid,JSON.stringify(columns)).then(function(result){$scope.model=result.Data,$scope.model.Inventory=result.Data.SparePart.Inventory,result.Data.SparePart.Component&&($scope.model.Unit=result.Data.SparePart.Component.Unit,$scope.model.GuidImage=result.Data.SparePart.Component.GuidImage,$scope.model.GuidComponent=result.Data.SparePart.Component.Guid,$scope.model.ComponentId=result.Data.SparePart.Component.Id,$scope.model.ComponentDescription=result.Data.SparePart.Component.Description,$scope.model.PartNumber=result.Data.SparePart.ComponentXSupplier.PartNumber),$scope.modelProperties&&(params.withdraw?($scope.modelProperties.quantityToWithdraw=$scope.model.Quantity-$scope.model.QuantityWithdrawn,$scope.maxValue=$scope.model.Inventory):($scope.modelProperties.quantityToWithdraw=$scope.model.QuantityWithdrawn,$scope.maxValue=$scope.model.QuantityWithdrawn)),$scope.isLoaded=!0,$scope.isUpdate&&!$scope.restrictEdit&&($scope.model.WorkOrder&&"History"===$scope.model.WorkOrder.Stage?($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-workOrderXSparePart-restrictEditMessage-woIsHistory","Redigering og sletting er ikke tilgjengelig når arbeidsordren som denne reservedelen er koblet til er hisorisk.")):$scope.model.WorkOrder&&$scope.model.WorkOrder.EndDate?($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-workOrderXSparePart-restrictEditMessage-woHasEndDate","Redigering og sletting er ikke tilgjengelig når arbeidsordren som denne reservedelen er koblet til er fullført.")):$scope.model.WorkOrder&&$scope.model.WorkOrder.Project&&"Project"===$scope.model.WorkOrder.Stage&&$scope.model.WorkOrder.Project.ClosedDate?($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-workOrderXSparePart-restrictEditMessage-projectIsCompleted","Redigering og sletting er ikke tilgjengelig når prosjektet via tilknyttet arbeidsordre er fullført.")):$scope.model.IsInvoiced&&($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-workOrderXSparePart-restrictEditMessage-isInvoiced","Redigering og sletting er ikke tilgjengelig fordi denne reservedelen er fakturert.")),getSparePartAttachments($scope.model.GuidComponent))})}else repository.getWithUrlParameter(repository.apiData.workOrder.endpoint.getDefaultSparePartEntity,"Guid="+$scope.workOrder.Guid).then(function(result){$scope.info={selectedFilterEntity:result.Data},$scope.reloadSpareParts()});$scope.chooseSparePart=function(item){$scope.itemExcluded(item.Guid)||($scope.model={GuidSparePart:item.Guid,Id:item.Component.Id,Description:item.Component.Description,Inventory:item.Inventory,Unit:item.Component.Unit,GuidImage:item.Component.GuidImage,GuidComponent:item.GuidComponent,Quantity:0},item.ComponentXSupplier&&($scope.model.PartNumber=item.ComponentXSupplier.PartNumber,$scope.model.Price=item.ComponentXSupplier.Price),getSparePartAttachments(item.GuidComponent),$scope.setCurrentStep(2))},$scope.itemExcluded=function(guid){return _.contains(params.excludeGuids,guid)},$scope.save=function(){delete $scope.model.Inventory,delete $scope.model.Unit,delete $scope.model.GuidUmage,void 0!==$scope.isWithdrawal&&($scope.isWithdrawal?$scope.model.QuantityWithdrawn=$scope.model.QuantityWithdrawn+$scope.modelProperties.quantityToWithdraw:$scope.model.QuantityWithdrawn=$scope.model.QuantityWithdrawn-$scope.modelProperties.quantityToWithdraw),$modalInstance.close($scope.model)},$scope.cancel=function(){$modalInstance.close()},$scope.addComponentToEquipment=function(){$scope.isSaving||(componentXEquipment={GuidComponent:$scope.model.GuidComponent,GuidEquipment:$scope.workOrder.GuidEquipment,Quantity:0},repository.createSingle(repository.apiData.componentEquipment.url,componentXEquipment).then(function(result){getSparePartAttachments(($scope.isUpdate,$scope.model.GuidComponent)),swal(translationService.translate("web-swal-component-add-equipment-success","Komponenten ble lagt til anlegget!"),"","success")},function(error){repository.growl(error,"danger")}))},$scope.addComponentToArea=function(){$scope.isSaving||(componentXArea={GuidComponent:$scope.model.GuidComponent,GuidArea:$scope.workOrder.GuidArea,Quantity:0},repository.createSingle(repository.apiData.componentArea.url,componentXArea).then(function(result){getSparePartAttachments(($scope.isUpdate,$scope.model.GuidComponent)),swal(translationService.translate("web-swal-component-add-area-success","Komponenten ble lagt til arealet!"),"","success")},function(error){repository.growl(error,"danger")}))},$scope.removeComponentFromArea=function(){$scope.isSaving||repository.deleteSingle(repository.apiData.componentArea.url,$scope.info.GuidComponentXArea).then(function(result){getSparePartAttachments(($scope.isUpdate,$scope.model.GuidComponent)),swal(translationService.translate("web-swal-component-remove-area-success","Komponenten ble fjernet fra arealet!"),"","success")})},$scope.removeComponentFromEquipment=function(){$scope.isSaving||repository.deleteSingle(repository.apiData.componentEquipment.url,$scope.info.GuidComponentXEquipment).then(function(result){getSparePartAttachments(($scope.isUpdate,$scope.model.GuidComponent)),swal(translationService.translate("web-swal-component-remove-equipment-success","Komponenten ble fjernet fra anlegget!"),"","success")})},$scope.manageEquipment=function(){$scope.info.GuidComponentXEquipment?$scope.removeComponentFromEquipment():$scope.addComponentToEquipment()},$scope.manageArea=function(){$scope.info.GuidComponentXArea?$scope.removeComponentFromArea():$scope.addComponentToArea()},$scope.$watch("info.selectedFilterEntity",function(newValue,oldValue){newValue!==oldValue&&newValue&&$scope.reloadSpareParts()})}angular.module("Plania").controller("CreateWorkOrderXSparePartController",["$scope","ngTableParams","$modalInstance","params","Repository","ListService","TranslationService",controller])}(),function(){angular.module("Plania").directive("workOrderEconomyInfo",function(){return{restrict:"E",scope:{workOrder:"=workOrder",reload:"=reload"},templateUrl:"app/workOrder/directives/workOrderEconomyInfo.html",controller:["$scope","$localStorage","RegisteredFieldService","Repository","TranslationService",function($scope,$localStorage,registeredFieldService,repository,translationService){function isLoadedFromServer(workOrder){return!!workOrder.GuidDataOwner}function init(){registeredFieldService.getRegisteredField(repository.commonService.prefix.WorkOrder).then(function(result){registeredFields=result,initEconomyTable()})}function isVisible(domainFieldName){if(!registeredFields)return!1;var fieldRule=_.find(registeredFields,{DomainFieldName:domainFieldName});return!(!fieldRule||fieldRule.Hidden||$localStorage.userData.isExternalUser&&fieldRule.ExternallyHidden)}function newRow(newRowSettings){var estimateVisible=isVisible(newRowSettings.propEstimated),realVisible=isVisible(newRowSettings.propReal),row={estimate:estimateVisible?$scope.workOrder[newRowSettings.propEstimated]:null,real:realVisible?$scope.workOrder[newRowSettings.propReal]:null,infoLabel:newRowSettings.infoLabel,systemName:"web-workorder-economyinfo-"+newRowSettings.translationKey,defaultTranslation:newRowSettings.defaultTranslation,highlight:newRowSettings.highlight,estimateColor:newRowSettings.estimateColor,realColor:newRowSettings.realColor};return row.estimate||row.real?(newRowSettings.subRows&&(row.subRows=_.compact(newRowSettings.subRows)),newRowSettings.showAllDecimals||(row.decimals=0),_.isNumber(row.real)&&_.isNumber(row.estimate)&&(row.estimateExceeded=row.real>row.estimate),row):null}function push(array,element){element&&array.push(element)}function initEconomyTable(){var rows=[];push(rows,newRow({defaultTranslation:"Tiltak",translationKey:"correctiveAction",propEstimated:"SumCorrectiveActionEstimatedAmount",infoLabel:!0})),push(rows,newRow({defaultTranslation:"Timer",translationKey:"time",propEstimated:"EstimatedTime",propReal:"RealTime",showAllDecimals:!0})),push(rows,newRow({defaultTranslation:"Interne kostnader",translationKey:"sumInternalCost",propEstimated:"SumInternalCostEstimatedAmount",propReal:"SumInternalCostRegisteredAmount",subRows:[newRow({defaultTranslation:"Timekostnader",translationKey:"sumResource",propEstimated:"SumResourceEstimatedAmount",propReal:"SumResourceRegisteredAmount"}),newRow({defaultTranslation:"Delkostnader",translationKey:"sumSparePart",propEstimated:"SumSparePartEstimatedAmount",propReal:"SumSparePartRegisteredAmount"}),newRow({defaultTranslation:"Anlegg",translationKey:"sumEquipment",propEstimated:"SumEquipmentEstimatedAmount",propReal:"SumEquipmentRegisteredAmount"})]})),push(rows,newRow({defaultTranslation:"Eksterne kostnader",translationKey:"sumExternalCost",propEstimated:"SumExternalCostEstimatedAmount",propReal:"SumExternalCostInvoiceAmount",subRows:[newRow({defaultTranslation:"Bestilt",translationKey:"sumExternalCostOrdered",propReal:"SumExternalCostOrderedAmount"}),newRow({defaultTranslation:"Disponert",translationKey:"restExternalCost",propReal:"RestExternalCostAllocatedAmount"}),newRow({defaultTranslation:"Anlegg",translationKey:"sumEquipment",propEstimated:"SumEquipmentEstimatedAmount",propReal:"SumEquipmentRegisteredAmount"})]})),push(rows,newRow({defaultTranslation:"Total Kostnader",translationKey:"total",propEstimated:"EstimatedCost",propReal:"RealCost",highlight:!0})),push(rows,newRow({defaultTranslation:"Total viderefaktureringssum",translationKey:"sumPaymentOrderSum",propReal:"SumPaymentOrderSum",highlight:!0,realColor:$scope.workOrder.SumPaymentOrderSum<$scope.workOrder.RealCost?"c-red":null})),$scope.vm={rows:rows,showContainer:_.some(rows,function(r){return r&&(r.real>0||r.estimate>0)})}}$scope.$watch("reload",function(newValue,oldValue){if(newValue!==oldValue)return isLoadedFromServer($scope.workOrder)?void($scope.reload&&!0===$scope.reload&&(init(),$scope.reload=!1)):void($scope.reload=!1)});var registeredFields=null;init()}]}})}(),function(){function controller($scope,repository,params,$modalInstance){if($scope.model=params.WorkOrderXArea,$scope.model.WorkOrderXAreaDto&&$scope.model.WorkOrderXAreaDto.AreaInfo.Id){var areaId=$scope.model.WorkOrderXAreaDto.AreaInfo.Id?$scope.model.WorkOrderXAreaDto.AreaInfo.Id+" - ":null;$scope.area=areaId+($scope.model.WorkOrderXAreaDto.AreaInfo.Description||"")+"\n"}$scope.building=params.buildingInfo,$scope.saveAction=function(){$scope.model.DeadlineDate&&($scope.model.DeadlineDate=new Date($scope.model.DeadlineDate).toISOString()),$scope.model.GuidDeviation&&($scope.model.Type=2),repository.updateSingle(repository.apiData.WorkOrderXArea.url,$scope.model).then(function(result){repository.growl("Avvik på rom er oppdatert","success"),$modalInstance.close("ok")})},$scope.cancel=function(){ $modalInstance.dismiss("canceled")}}angular.module("Plania").controller("EditWorkOrderXAreaController",["$scope","Repository","params","$modalInstance",controller])}(),function(){function controller($scope,$modalInstance,params,repository,registeredFieldService,workOrderService,translationService){$scope.isEdit=!!params.GuidWorkOrderXResourceGroup,$scope.isLoaded=!1,$scope.projectHourTypeCount=0,$scope.model={HourType:{}},$scope.restrictEdit=!1,$scope.restrictEditMessage="",$scope.activateAutocomplete=!1;var costPrHour=0,setCost=function(newEstimatedTime,newRealTime){if(newEstimatedTime||(newEstimatedTime=$scope.model.EstimatedTime),newRealTime||(newRealTime=$scope.model.RealTime),$scope.model.HourType&&"FixedAmount"===$scope.model.HourType.PriceType)costPrHour=$scope.model.HourType.Price;else if($scope.model.HourType&&"AddedAmount"===$scope.model.HourType.PriceType)costPrHour=$scope.model.ResourceGroup.CostPrHour+$scope.model.HourType.Price;else if($scope.model.HourType&&"AddedFactor"===$scope.model.HourType.PriceType){var cost=$scope.model.ResourceGroup.CostPrHour;costPrHour=cost+cost*$scope.model.HourType.Price/100}$scope.model.EstimatedCost=newEstimatedTime?costPrHour*newEstimatedTime:0,$scope.model.RealCost=newRealTime?costPrHour*newRealTime:0};$scope.onResourceGroupSelect=function(resourceGroup){if(!resourceGroup)return costPrHour=0,$scope.model.EstimatedCost=0,$scope.model.RealCost=0,$scope.model.GuidResourceGroup="",$scope.resourceGroup=null,void $scope.onPersonSelect(null);$scope.model.GuidResourceGroup=resourceGroup.Guid,$scope.model.ResourceGroup=resourceGroup,(resourceGroup.CostPrHour||0===resourceGroup.CostPrHour)&&(costPrHour=resourceGroup.CostPrHour,setCost())},$scope.onPersonSelect=function(person){if(!person)return $scope.model.GuidPerson="",$scope.model.GuidPersonResourceGroup=null,void($scope.person=null);$scope.model.GuidPerson=person.Guid,$scope.model.GuidPersonResourceGroup=person.GuidResourceGroup,$scope.model.Person=person,person.GuidResourceGroup&&$scope.onResourceGroupSelect({Guid:person.GuidResourceGroup,Caption:person.ResourceGroup.Caption,CostPrHour:person.ResourceGroup.CostPrHour})},$scope.onHourTypeSelect=function(hourType){hourType?($scope.model.GuidHourType=hourType.Guid,$scope.model.HourType=hourType):($scope.model.GuidHourType="",$scope.model.HourType.Caption=null),setCost()};var columns=["ResourceGroup.Id","ResourceGroup.Description","ResourceGroup.CostPrHour","Person.FirstName","Person.LastName","HourType.Id","HourType.Description","HourType.PriceType","HourType.Price","WorkOrder.Stage","WorkOrder.EndDate","WorkOrder.GuidProject","WorkOrder.Project.ClosedDate","UserUpdatedBy.RealName"];params.GuidWorkOrderXResourceGroup?repository.getSingle(repository.apiData.workOrderXResourceGroup.url,params.GuidWorkOrderXResourceGroup,JSON.stringify(columns)).then(function(result){$scope.model=result.Data,$scope.model.HourType||($scope.model.HourType={}),$scope.model.ResourceGroup&&(costPrHour=$scope.model.ResourceGroup.CostPrHour),setTimeout(function(){$scope.activateAutocomplete=!0},250),$scope.isLoaded=!0,$scope.isEdit&&!$scope.restrictEdit&&($scope.model.WorkOrder&&"History"===$scope.model.WorkOrder.Stage?($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-workOrderXResourceGroup-restrictEditMessage-woIsHistory","Redigering og sletting er ikke tilgjengelig når arbeidsordren som denne ressursen er koblet til er hisorisk.")):$scope.model.WorkOrder&&$scope.model.WorkOrder.EndDate?($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-workOrderXResourceGroup-restrictEditMessage-woHasEndDate","Redigering og sletting er ikke tilgjengelig når arbeidsordren som denne ressursen er koblet til er fullført.")):$scope.model.WorkOrder&&$scope.model.WorkOrder.Project&&"Project"===$scope.model.WorkOrder.Stage&&$scope.model.WorkOrder.Project.ClosedDate?($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-workOrderXResourceGroup-restrictEditMessage-projectIsCompleted","Redigering og sletting er ikke tilgjengelig når prosjektet via tilknyttet arbeidsordre er fullført.")):$scope.model.IsInvoiced&&($scope.restrictEdit=!0,$scope.restrictEditMessage=translationService.translate("web-workOrderXResourceGroup-restrictEditMessage-isInvoiced","Redigering og sletting er ikke tilgjengelig fordi denne ressursen er fakturert.")))},function(error){repository.growl(error,"danger")}):(params.GuidWorkOrder&&($scope.model.GuidWorkOrder=params.GuidWorkOrder),params.GuidProject&&($scope.model.WorkOrder={GuidProject:params.GuidProject}),params.ResourceGroup&&$scope.onResourceGroupSelect(params.ResourceGroup),$scope.model.RegisteredDate=new Date,$scope.activateAutocomplete=!0,$scope.isLoaded=!0),$scope.saveResource=function(){$scope.model.RegisteredDate="string"==typeof $scope.model.RegisteredDate?new Date($scope.model.RegisteredDate):$scope.model.RegisteredDate.toISOString();var sendModel=angular.copy($scope.model);delete sendModel.WorkOrder,delete sendModel.Person,delete sendModel.ResourceGroup;var hasActivatedWorkOrder=!1,errorCallback=function(error){error&&workOrderService.isWorkOrderStage0(error)?workOrderService.shouldActivateWorkOrder($scope.model.GuidWorkOrder,error).then(function(result){hasActivatedWorkOrder=!0,sendModel.Guid?updateResource():createResource()},function(error){error&&repository.growl(error,"danger")}):repository.growl(error.Message||error,"danger")},createResource=function(){return repository.createSingle(repository.apiData.workOrderXResourceGroup.url,sendModel).then(function(result){repository.growl("Ressurs har blitt knyttet til arbeidsordre","success"),$modalInstance.close({realCost:$scope.model.RealCost,estimatedCost:$scope.model.EstimatedCost,realTime:$scope.model.RealTime,estimatedTime:$scope.model.EstimatedTime}),hasActivatedWorkOrder&&$scope.goBack("workOrder.edit",{guid:$scope.model.GuidWorkOrder,menuGuid:null})},errorCallback)},updateResource=function(){repository.updateSingle(repository.apiData.workOrderXResourceGroup.url,sendModel).then(function(result){repository.growl("Ressurs oppdatert","success"),$modalInstance.close({realCost:$scope.model.RealCost,estimatedCost:$scope.model.EstimatedCost,realTime:$scope.model.RealTime,estimatedTime:$scope.model.EstimatedTime}),hasActivatedWorkOrder&&$scope.goBack("workOrder.edit",{guid:$scope.model.GuidWorkOrder,menuGuid:null})},errorCallback)};sendModel.Guid?updateResource():createResource()},$scope.cancel=function(){$modalInstance.dismiss("canceled")};$scope.autoCompleteFilter=function(filterName){switch(filterName){case"person":return{GuidResourceGroup:$scope.model.GuidResourceGroup,DoesMaintenanceTasks:!0,PropertyFilter:[{Property:"ResourceGroup.DoesMaintenanceTasks",Operator:"=",Value:"1"}]};case"resourceGroup":return{PropertyFilter:[{Property:"DoesMaintenanceTasks",Operator:"=",Value:"1"}]};case"hourType":var filter={PropertyFilter:[]};return $scope.model.WorkOrder&&$scope.model.WorkOrder.GuidProject?(filter.GuidProject=$scope.model.WorkOrder.GuidProject,filter.InResourceRegistration=!0):filter.PropertyFilter.push({Property:"GuidProject",Value:"",Operator:"="}),filter}},$scope.$watch("model.EstimatedTime",function(newValue,oldValue){newValue!==oldValue&&setCost()},!0),$scope.$watch("model.RealTime",function(newValue,oldValue){newValue!==oldValue&&setCost()},!0),$scope.$watch("model.GuidPersonResourceGroup",function(newValue,oldValue){$scope.disableResourceGroupSelection=!!newValue},!0)}angular.module("Plania").controller("WorkOrderXResourceGroupController",["$scope","$modalInstance","params","Repository","RegisteredFieldService","WorkOrderService","TranslationService",controller])}(),function(){function controller($scope,params,repository,ngTableParams,$modalInstance,translationService,listService,$filter,$window,$rootScope){$scope.initialListSetup=_.cloneDeep(params.SelectedListSetup),$scope.initialListSetup&&($scope.initialListSetup.inMemory=!0),$scope.allRowsSelected=!1,$scope.selectedGuids=[],$scope.firstLoadList=!1,$scope.isRunningAction=!1,$scope.currentTab="workOrders",$scope.dataOwnerActivityPeriodDate=null,$scope.reloadMainTable=!1,$scope.errorMessage=null,$scope.workOrderResponses=[],$scope.totalFailedWorkOrders=0;var guidDataOwner=repository.commonService.getFilterData().selectedDataOwner.Guid;guidDataOwner&&repository.getSingle(repository.apiData.dataOwner.url,guidDataOwner).then(function(response){$scope.dataOwnerActivityPeriodDate=$filter("date")(response.Data.ActivityPeriodDate,"dd.MM.yyyy")},function(error){repository.growl(error,"danger")}),listService.getWebListViews($scope.initialListSetup,repository.apiData.workOrder.prefix,!1,null,{}).then(function(result){$scope.workOrderListOptions=result.listOptions,$scope.workOrderListSetup=result.selectedListSetup,$scope.workOrderTable||($scope.workOrderTable=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{CanBeSentToHistory:!0}},{total:0,filterDelay:10,counts:[10,20,50],paginationMaxBlocks:8,getData:function($defer,params){var columns=[];$scope.workOrderListSetup.Columns.forEach(function(col){columns.push(col.Property)}),columns.includes("DataOwner.ActivityPeriodDate")||columns.push("DataOwner.ActivityPeriodDate"),repository.GetPaginated(repository.apiData.workOrder.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){$scope.workOrderTable.settings().total=result.TotalCount,$scope.workOrderTable.settings().filterDelay=500,$scope.firstLoadList=!0,params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))}),$scope.$watch("workOrderListSetup",function(newValue,oldValue){oldValue!==newValue&&$scope.workOrderTable&&($scope.workOrderTable.$params.sorting=$scope.workOrderListSetup.Sorting,$scope.workOrderListSetup.GroupBy?$scope.workOrderTable.settings().groupBy=function(obj){return!!$scope.workOrderListSetup.GroupBy&&($scope.workOrderListSetup.GroupBy.split(".").forEach(function(attr){obj=obj?obj[attr]:""}),obj)}:$scope.workOrderTable.settings().groupBy=null,$scope.workOrderTable.reload())}),$scope.getPropertyValue=function(entity,field){return listService.GetPropertyValue(entity,field)},$scope.addSelectedGuid=function(guid){if($scope.isItemSelected(guid)){for(var i=0;i<$scope.selectedGuids.length;i++)if($scope.selectedGuids[i]===guid)return void $scope.selectedGuids.splice(i,1)}else $scope.selectedGuids.push(guid)},$scope.isItemSelected=function(guid){return _.find($scope.selectedGuids,function(g){return g===guid})},$scope.sendToHistory=function(){0!==$scope.selectedGuids.length&&($scope.isRunningAction=!0,repository.runAction(repository.apiData.workOrder.endpoint.generateHistory,$scope.selectedGuids).then(function(result){if($scope.isRunningAction=!1,$scope.workOrderResponses=result,$scope.workOrderResponses.forEach(function(wo){0===wo.ErrorMessages.length&&$scope.selectedGuids.includes(wo.Guid)&&$scope.addSelectedGuid(wo.Guid)}),$scope.totalFailedWorkOrders=$scope.workOrderResponses.filter(function(wo){return wo.ErrorMessages.length>0}).length,$scope.errorMessage="",$scope.totalFailedWorkOrders>0?($scope.totalFailedWorkOrders===$scope.workOrderResponses.length||$scope.reloadMainTable||($scope.reloadMainTable=!0),$scope.errorMessage=translationService.translate("web-sendWorkOrderToHistoryModal-generateHistory-failed","En eller flere arbeidsordre ble ikke sendt til historikk. Sjekk listen for feil."),repository.growl($scope.errorMessage,"warning"),$scope.currentTab="errorMessages",$scope.workOrderTable&&$scope.workOrderTable.reload(),$scope.errorMessageTable&&$scope.errorMessageTable.reload()):(repository.growl(translationService.translate("web-sendWorkOrderToHistoryModal-generateHistory-success","Arbeidsordrene har blitt sendt til historikk."),"success"),$modalInstance.close()),result){$scope.errorDictionary={},$scope.totalErrorMessages=0;Object.keys(result).forEach(function(key){$scope.errorDictionary[key]={errorMessages:result[key],collapse:!1},$scope.totalErrorMessages+=result[key].length}),$scope.currentTab="errorMessages"}else $scope.totalErrorMessages=0,$scope.errorDictionary={},$modalInstance.dismiss()},function(error){$scope.isRunningAction=!1,repository.growl(error,"danger")}))},$scope.errorMessageTable=new ngTableParams({page:1,count:10},{total:$scope.workOrderResponses.length,counts:[5,10,20],getData:function($defer,params){$scope.errorMessageTable.settings().total=$scope.workOrderResponses.length,$defer.resolve($scope.workOrderResponses.filter(function(i){return 0!==i.ErrorMessages.length}).slice((params.page()-1)*params.count(),params.page()*params.count()))}}),$scope.contextMenuOptions=function(item){var options=[];return options.push({html:' '+translationService.translate("web-sendWorkOrderToHistoryModal-viewWorkorder","Åpne arbeidsordre i nytt vindu")+"",click:function($itemScope,$event,modelValue,text,$li){$window.open($rootScope.navigation.href("workOrder.edit",{guid:item.Guid}),"_blank")}}),options},$scope.cancel=function(){$scope.isRunningAction?swal({title:translationService.translate("web-sendWorkOrdersToHistoryModal-swal-title","Vil du lukke dette vinduet?"),text:translationService.translate("web-sendWOrkOrdersToHistoryModal-swal-text","Plania vil fortsette å sende valgte arbeidsordre til historikk, men du vil ikke kunne se potensielle feilmeldinger hvis du lukker dette vinduet."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-button-yes-continue","Ja, fortsett"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,$scope.reloadMainTable?$modalInstance.close():$modalInstance.dismiss("canceled")}):$scope.reloadMainTable?$modalInstance.close():$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("SendWorkOrderToHistoryModalController",["$scope","params","Repository","ngTableParams","$modalInstance","TranslationService","ListService","$filter","$window","$rootScope",controller])}(),function(){function controller($scope,repository,$q,$stateParams,$modal,$modalStack,ngTableParams,$rootScope,$window,translationService,$localStorage,listService,enumService,$timeout,registeredFieldService,workOrderService,signalR,areaService,customerService,colorService){$scope.isUpdate="workOrder.edit"===$scope.navigation.current.name||$stateParams.isModal,$scope.model={Guid:$stateParams.guid},$scope.activateAutocomplete=!1,$scope.modelDto={CompletionRate:0};var originalStartDate=null;$scope.isClosable=!0;var generatedFrom=repository.commonService.prefix.WorkOrder;$scope.isModal=$stateParams.isModal,$scope.isTextCollapsed=!0,$scope.isCommentCollapsed=!0,$scope.isDynamicPropertiesCollapsed=!1,$scope.isDocumentsCollapsed=$scope.isModal,$scope.reloadOperationalMessages=!1,$scope.isResourcesCollapsed=!0,$scope.showToolbar=!1,$scope.isAreaCollapsed=!0,$scope.reloads={deviations:!1,documents:!1,forceDocuments:!1,alarmLogs:!1,controlLists:!1,economyInfo:!1},$scope.generalOptions=$localStorage.generalOptions,$scope.enableWebNavigation=!1,$scope.counts={documentTotalCount:0},$scope.entityCommentSearch={searchString:"",focus:!1};var fieldLengths={Description:50};registeredFieldService.getRegisteredField(repository.commonService.prefix.WorkOrder).then(function(registeredFields){var isExternalUser=$localStorage.userData.isExternalUser,noteRule=_.filter(registeredFields,{DomainFieldName:"Note"})[0];$scope.isNoteHidden=!!noteRule&¬eRule.Hidden;var estimatedTimeRule=_.filter(registeredFields,{DomainFieldName:"EstimatedTime"})[0],realTimeRule=_.filter(registeredFields,{DomainFieldName:"RealTime"})[0],estimatedCostRule=_.filter(registeredFields,{DomainFieldName:"EstimatedCost"})[0],realCostRule=_.filter(registeredFields,{DomainFieldName:"RealCost"})[0];$scope.TimeAndCostVisibility={showEstimatedTime:!!estimatedTimeRule&&(!estimatedTimeRule.Hidden&&(!isExternalUser||!estimatedTimeRule.ExternallyHidden)),showRealTime:!!realTimeRule&&(!realTimeRule.Hidden&&(!isExternalUser||!realTimeRule.ExternallyHidden)),showEstimatedCost:!!estimatedCostRule&&(!estimatedCostRule.Hidden&&(!isExternalUser||!estimatedCostRule.ExternallyHidden)),showRealCost:!!realCostRule&&(!realCostRule.Hidden&&(!isExternalUser||!realCostRule.ExternallyHidden))};var descriptionRule=_.filter(registeredFields,{DomainFieldName:"Description"})[0];descriptionRule&&descriptionRule.MaxLength&&(fieldLengths.Description=descriptionRule.MaxLength)}),registeredFieldService.getRegisteredField(repository.commonService.prefix.WorkOrderXResourceGroup).then(function(registeredFields){var isExternalUser=$localStorage.userData.isExternalUser,estimatedTimeRule=_.filter(registeredFields,{DomainFieldName:"EstimatedTime"})[0],realTimeRule=_.filter(registeredFields,{DomainFieldName:"RealTime"})[0],estimatedCostRule=_.filter(registeredFields,{DomainFieldName:"EstimatedCost"})[0],realCostRule=_.filter(registeredFields,{DomainFieldName:"RealCost"})[0],noteRule=_.filter(registeredFields,{DomainFieldName:"Note"})[0];$scope.resourceGroupInfo.TimeAndCostVisibility={showEstimatedTime:!!estimatedTimeRule&&(!estimatedTimeRule.Hidden&&(!isExternalUser||!estimatedTimeRule.ExternallyHidden)),showRealTime:!!realTimeRule&&(!realTimeRule.Hidden&&(!isExternalUser||!realTimeRule.ExternallyHidden)),showEstimatedCost:!!estimatedCostRule&&(!estimatedCostRule.Hidden&&(!isExternalUser||!estimatedCostRule.ExternallyHidden)),showRealCost:!!realCostRule&&(!realCostRule.Hidden&&(!isExternalUser||!realCostRule.ExternallyHidden)),showNote:!!noteRule&&(!noteRule.Hidden&&(!isExternalUser||!noteRule.ExternallyHidden))},$scope.resourceGroupInfo.initTable()}),$scope.isDirtyEndDate=!1,$scope.showCompleteButton=$localStorage.generalOptions.WorkOrderShowCompleteButton,$scope.isEstateDisabled=!1,$scope.isBuildingDisabled=!1,$scope.isEquipmentDisabled=!1,$scope.restrictRedo=!0,$scope.isHistory=!1,$scope.editPurchaseOrder=$localStorage.generalOptions.UsePoInWo,$scope.viewMode=void 0!==$stateParams.viewMode?!!$stateParams.viewMode:!!$scope.isUpdate,$scope.extendWorkOrderType="Ukjent",$scope.documents=[],$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var getWorkOrderType=function(){switch($scope.model.Type){case"FV":return translationService.translate("web-WorkOrder-Type-FV","Forebyggende (FV)");case"PR":return translationService.translate("web-WorkOrder-Type-PR","Prosjekt (PR)");case"ME":return translationService.translate("web-WorkOrder-Type-ME","Melding (ME)");case"KO":return translationService.translate("web-WorkOrder-Type-KO","Korrektiv (KO)");case"AV":return translationService.translate("web-WorkOrder-Type-AV","Avvik (AV)");case"TT":return translationService.translate("web-WorkOrder-Type-TT","Tiltak (TT)");case"VL":return translationService.translate("web-WorkOrder-Type-VL","Vaktlogg (VL)");case"TK":return translationService.translate("web-WorkOrder-Type-TK","Tilstandskontroll (TK)");case"Alarm":return translationService.translate("web-WorkOrder-Type-ALARM","OPC-Alarm");default:return"Ukjent"}},updateAccess=function(){if($scope.isUpdate){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictClosedEdit=!$scope.hasEditAccess(repository.commonService.prefix.WorkOrder,void 0,checkOtherDo),"History"===$scope.model.Stage?($scope.restrictEdit=!0,$scope.restrictDelete=!0,$scope.restrictRedo=!0,$scope.isHistory=!0,$scope.allowCompletion=!1):"Project"===$scope.model.Stage&&$scope.model.Project&&$scope.model.Project.ClosedDate?($scope.restrictEdit=!0,$scope.restrictDelete=!0,$scope.isHistory=!0):($scope.restrictEdit=!$scope.hasEditAccess(repository.commonService.prefix.WorkOrder,void 0,checkOtherDo)||$scope.model.EndDate&&!$scope.isDirtyEndDate||!1,$scope.restrictRedo=!$scope.hasEditAccess(repository.commonService.prefix.WorkOrder,void 0,checkOtherDo),$scope.restrictDelete=!$scope.hasDeleteAccess(repository.commonService.prefix.WorkOrder,void 0,checkOtherDo),!$scope.restrictRedo&&$scope.showCompleteButton&&$scope.isUpdate&&$scope.model.EndDate?($scope.restrictRedo=!1,$scope.allowCompletion=!1):($scope.restrictRedo=!0,$scope.allowCompletion=!0))}else $scope.restrictEdit=!$scope.hasCreateAccess(repository.commonService.prefix.WorkOrder,null),$scope.restrictRedo=!0,$scope.allowCompletion=!1};$scope.$watch("model.EndDate",function(newValue,oldValue){newValue!==oldValue&&(newValue&&($scope.isDirtyEndDate=!0),oldValue&&!newValue&&($scope.isDirtyEndDate=!1))}),$scope.getPropertyValue=function(building,column){return listService.GetPropertyValue(building,column)};var prefillCustomerFromArea=function(guidArea,skipModal){if(!$scope.isUpdate){var customerFieldRule=registeredFieldService.getLocalRegisteredField(repository.apiData.workOrder.prefix,"GuidCustomer");!(customerFieldRule&&customerFieldRule.Hidden)&&$localStorage.generalOptions.UseCustomerInRequest&&!$scope.model.GuidCustomer&&guidArea&&areaService.getActiveCustomer(guidArea,skipModal).then(function(customer){$scope.modelDto.customer=customer.Caption,$scope.onCustomerSelect(customer)})}},prefillAreaFromCustomer=function(guidCustomer,skipModal){if(!$scope.isUpdate){var areaFieldRule=registeredFieldService.getLocalRegisteredField(repository.apiData.workOrder.prefix,"GuidArea");!(areaFieldRule&&areaFieldRule.Hidden)&&$localStorage.generalOptions.UseCustomerInRequest&&!$scope.model.GuidArea&&guidCustomer&&customerService.getActiveHousing(guidCustomer,skipModal).then(function(area){$scope.modelDto.area=area.Caption,$scope.onAreaSelect(area)})}};$scope.sparePartInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-sparepart-componentXSupplier-partnumber","Delenummer"),Property:"SparePart.ComponentXSupplier.PartNumber",PropertyType:"string"},{Position:2,Title:translationService.translate("web-sparepart-component-description","Komponentnavn"),Property:"SparePart.Component.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-sparePart-location","Plassering"),Property:"SparePart.Location",PropertyType:"string"},{Position:4,Title:translationService.translate("web-workorderxsparepart-Quantity","Antall"),Property:"Quantity",PropertyType:"number"},{Position:5,Title:translationService.translate("web-workorderxsparepart-Price","Price"),Property:"Price",PropertyType:"double"},{Position:6,Title:translationService.translate("web-workorderxsparepart-QuantityWithdrawn","Antall tatt ut"),Property:"QuantityWithdrawn",PropertyType:"number"},{Position:7,Title:translationService.translate("web-sparePart-Inventory","Beholdning"),Property:"SparePart.Inventory",PropertyType:"number"},{Position:8,Title:translationService.translate("web-componentXSupplier-supplier-description","Leverandør"),Property:"SparePart.ComponentXSupplier.Supplier.Description",PropertyType:"string"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{UpdatedDate:"desc"},filter:{PropertyFilter:[{Property:"GuidWorkOrder",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("IsInvoiced"),repository.GetPaginated(repository.apiData.workOrderSparePart.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}))},this.add=function(){var selectedGuids=[];me.table.data.forEach(function(sparePart){selectedGuids.push(sparePart.GuidSparePart)}),$modal.open({templateUrl:"app/WorkOrder/views/createWorkOrderXSparePart.html",controller:"CreateWorkOrderXSparePartController",size:"xl",resolve:{params:function(){return{isUpdate:!1,excludeGuids:selectedGuids,workOrder:$scope.model}}}}).result.then(function(item){item&&item.GuidSparePart&&(item.GuidWorkOrder=$scope.model.Guid,repository.createSingle(repository.apiData.workOrderSparePart.url,item).then(function(result){item.QuantityWithdrawn||(item.QuantityWithdrawn=0),repository.growl(translationService.translate("web-workorder-sparepart-added","Reservedel er lagt til arbeidsordre"),"success"),me.table.reload()}))},function(){})},this.update=function(sparePart){me.canEdit(sparePart)&&$modal.open({templateUrl:"app/WorkOrder/views/createWorkOrderXSparePart.html",controller:"CreateWorkOrderXSparePartController",resolve:{params:function(){return{isUpdate:!0,guid:sparePart.Guid,workOrder:$scope.model}}}}).result.then(function(item){item&&item.GuidSparePart&&(item.GuidWorkOrder=$scope.model.Guid,item.Guid=sparePart.Guid,repository.updateSingle(repository.apiData.workOrderSparePart.url,item).then(function(result){repository.growl(translationService.translate("web-spare-part-updated","Reservedel er oppdatert"),"success"),me.table.reload()}))})},this.remove=function(sparePart){me.canDelete(sparePart)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-workorder-sparepart-swal-confirmRemove","Reservedelen vil bli fjernet fra arbeidsordren"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-sparePart-button-confirm","Ja, fjern reservedelen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.workOrderSparePart.url,sparePart.Guid).then(function(result){swal(translationService.translate("web-workorder-swal-sparePartRemoval-success","Reservedelen ble fjernet!"),result,"success"),repository.growl(translationService.translate("web-workorder-sparepart-removed","Reservedelen er fjernet fra arbeidsordre"),"success"),me.table.reload()})})},this.updateWithdrawal=function(sparePart,withdraw){me.canEdit(sparePart)&&$modal.open({templateUrl:"app/WorkOrder/views/withdrawSparePartModal.html",controller:"CreateWorkOrderXSparePartController",resolve:{params:function(){return{withdraw:withdraw,isUpdate:!0,guid:sparePart.Guid}}}}).result.then(function(item){repository.updateSingle(repository.apiData.workOrderSparePart.url,item).then(function(result){repository.growl(translationService.translate("web-spare-part-updated","Reservedel er oppdatert"),"success"),me.table.reload()})})},this.contextMenuOptions=function(item){var options=[];if(me.canEdit(item)){var editIcon=" fa-pen-to-square",editText=translationService.translate("web-workorder-workOrderXSparePart-edit","Rediger reservedel"),restrictContextEdit=$scope.model.EndDate||"History"===$scope.model.Stage||"Project"===$scope.model.Stage&&$scope.model.Project&&$scope.model.Project.ClosedDate;(item.IsInvoiced||restrictContextEdit)&&(editIcon="fa-eye",editText=translationService.translate("web-workorder-workOrderXSparePart-open","Åpne reservedel")),options.push({html:' '+editText+"",click:function($itemScope,$event,modelValue,text,$li){me.update(item)}});var withdrawText=translationService.translate("web-workorder-workOrderXSparePart-withdraw","Ta ut reservedeler"),enableWithdraw=!0;"History"===$scope.model.Stage?(enableWithdraw=!1,withdrawText=translationService.translate("web-workorder-workOrderXSparePart-withdraw-woIsHistory","Kan ikke ta ut reservedel når AO er i historikk.")):$scope.model.EndDate?(enableWithdraw=!1,withdrawText=translationService.translate("web-workorder-workOrderXSparePart-withdraw-woHasEndDate","Kan ikke ta ut reservedel når AO er fullført.")):"Project"===$scope.model.Stage&&$scope.model.Project&&$scope.model.Project.ClosedDate?(enableWithdraw=!1,withdrawText=translationService.translate("web-workorder-workOrderXSparePart-withdraw-projectIsCompleted","Kan ikke ta ut reservedel når AO er koblet til et fullført prosjekt.")):item.IsInvoiced&&(enableWithdraw=!1,withdrawText=translationService.translate("web-workorder-workOrderXSparePart-withdraw-isInvoiced","Kan ikke ta ut fra en fakturert reservedel.")),options.push({html:' '+withdrawText+"",click:function($itemScope,$event,modelValue,text,$li){me.updateWithdrawal(item,!0)},enabled:enableWithdraw});var refillText=translationService.translate("web-workorder-workOrderXSparePart-refill","Legg tilbake reservedeler"),enableRefill=!0;"History"===$scope.model.Stage?(enableRefill=!1,refillText=translationService.translate("web-workorder-workOrderXSparePart-refill-woIsHistory","Kan ikke legge tilbake reservedel når AO er i historikk.")):$scope.model.EndDate?(enableRefill=!1,refillText=translationService.translate("web-workorder-workOrderXSparePart-refill-woHasEndDate","Kan ikke legge tilbake reservedel når AO er fullført.")):"Project"===$scope.model.Stage&&$scope.model.Project&&$scope.model.Project.ClosedDate?(enableRefill=!1,refillText=translationService.translate("web-workorder-workOrderXSparePart-refill-projectIsCompleted","Kan ikke legge tilbake reservedel når AO er koblet til et fullført prosjekt.")):item.IsInvoiced&&(enableRefill=!1,refillText=translationService.translate("web-workorder-workOrderXSparePart-refill-isInvoiced","Kan ikke legge tilbake fra en fakturert reservedel.")),options.push({html:' '+refillText+"",click:function($itemScope,$event,modelValue,text,$li){me.updateWithdrawal(item,!1)},enabled:enableRefill})}if(me.canDelete(item)){var deleteText=translationService.translate("web-workorder-workOrderXSparePart-delete","Slett reservedel"),enableDelete=!0;"History"===$scope.model.Stage?(enableDelete=!1,deleteText=translationService.translate("web-workorder-workOrderXSparePart-delete-woIsHistory","Kan ikke slette reservedel når AO er i historikk.")):$scope.model.EndDate?(enableDelete=!1,deleteText=translationService.translate("web-workorder-workOrderXSparePart-delete-woHasEndDate","Kan ikke slette reservedel når AO er fullført.")):"Project"===$scope.model.Stage&&$scope.model.Project&&$scope.model.Project.ClosedDate?(enableDelete=!1,deleteText=translationService.translate("web-workorder-workOrderXSparePart-delete-projectIsCompleted","Kan ikke slette reservedel når AO er koblet til et fullført prosjekt.")):item.IsInvoiced&&(enableDelete=!1,deleteText=translationService.translate("web-workorder-workOrderXSparePart-delete-isInvoiced","Kan ikke slette fakturert reservedel")),options.push({hasTopDivider:!0,html:' '+deleteText+"",click:function($itemScope,$event,modelValue,text,$li){me.remove(item)},enabled:enableDelete})}return options},this.canEdit=function(workOrderXSparePart){return workOrderXSparePart&&$scope.hasEditAccess("WorkOrderXSparePart")},this.canDelete=function(workOrderXSparePart){return workOrderXSparePart&&$scope.hasDeleteAccess("WorkOrderXSparePart")}},$scope.resourceGroupInfo=new function(){var me=this,setColumns=function(){me.columns=[{Position:1,Title:translationService.translate("web-WorkOrderXResourceGroup-resourceGroup","Ressurs"),Property:"ResourceGroup.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-WorkOrderXResourceGroup-person","Person"),Property:"Person.FirstName",PropertyType:"string"}],me.TimeAndCostVisibility.showEstimatedCost&&me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-WorkOrderXResourceGroup-estimatedCost","Est. Kost"),Property:"EstimatedCost", PropertyType:"double"}),me.TimeAndCostVisibility.showEstimatedTime&&me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-WorkOrderXResourceGroup-estimatedTime","Est. Tid"),Property:"EstimatedTime",PropertyType:"double"}),me.TimeAndCostVisibility.showRealCost&&me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-WorkOrderXResourceGroup-realCost","Kost"),Property:"RealCost",PropertyType:"double"}),me.TimeAndCostVisibility.showRealTime&&me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-WorkOrderXResourceGroup-realTime","Tid"),Property:"RealTime",PropertyType:"double"}),me.TimeAndCostVisibility.showNote&&!me.TimeAndCostVisibility.showRealTime&&me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-WorkOrderXResourceGroup-note","Kommentar"),Property:"Note",PropertyType:"string"}),me.columns.push({Position:me.columns.length+1,Title:translationService.translate("web-WorkOrderXResourceGroup-registeredDate","Registrert Dato"),Property:"RegisteredDate",PropertyType:"date"})};this.initTable=function(){me.table||(setColumns(),me.table=new ngTableParams({page:1,count:10,sorting:{"ResourceGroup.Id":"asc"},filter:{PropertyFilter:[{Property:"GuidWorkOrder",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("Person.LastName"),columns.push("ResourceGroup.Description"),columns.push("ResourceGroup.Guid"),columns.push("IsInvoiced"),me.TimeAndCostVisibility.showEstimatedCost||columns.push("EstimatedCost"),me.TimeAndCostVisibility.showEstimatedTime||columns.push("EstimatedTime"),me.TimeAndCostVisibility.showRealCost||columns.push("RealCost"),me.TimeAndCostVisibility.showRealTime||columns.push("RealTime"),columns.push("Note"),repository.GetPaginated(repository.apiData.workOrderXResourceGroup.url,params.page()-1,params.count(),params.sorting(),params.filter(),null,JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)})}}))};var getResourceGroup=function(){return $scope.model.ResourceGroup?($scope.model.ResourceGroup.Guid=$scope.model.GuidResourceGroup,$scope.model.ResourceGroup):null};this.add=function(){$modal.open({templateUrl:"app/workOrder/views/editWorkOrderXResourceGroupModal.html",controller:"WorkOrderXResourceGroupController",resolve:{params:function(){return{GuidWorkOrder:$scope.model.Guid,GuidProject:$scope.model.GuidProject,ResourceGroup:getResourceGroup()}}}}).result.then(function(cost){me.table.reload()})},this.update=function(resource){me.canEdit(resource)&&$modal.open({templateUrl:"app/workOrder/views/editWorkOrderXResourceGroupModal.html",controller:"WorkOrderXResourceGroupController",resolve:{params:function(){return{GuidWorkOrderXResourceGroup:resource.Guid}}}}).result.then(function(cost){me.table.reload()})},this.remove=function(resource){me.canDelete(resource)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-resource-message","Ressursen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-resource-button-confirm","Ja, fjern ressursen!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.workOrderXResourceGroup.url,resource.Guid).then(function(result){swal(translationService.translate("web-swal-resource-success","Ressursen ble fjernet!"),result,"success"),repository.growl(translationService.translate("web-workorder-resoursgroup-removed","Ressurs er fjernet fra arbeidsordre"),"success"),me.table.reload()})})},this.contextMenuOptions=function(item){var options=[];if(me.canEdit(item)){var editIcon=" fa-pen-to-square",editText=translationService.translate("web-workorder-workOrderXResourceGroup-edit","Rediger ressurs"),restrictContextEdit=$scope.model.EndDate||"History"===$scope.model.Stage||"Project"===$scope.model.Stage&&$scope.model.Project&&$scope.model.Project.ClosedDate;(item.IsInvoiced||restrictContextEdit)&&(editIcon="fa-eye",editText=translationService.translate("web-workorder-workOrderXResourceGroup-open","Åpne ressurs")),options.push({html:' '+editText+"",click:function($itemScope,$event,modelValue,text,$li){me.update(item)}})}if(me.canDelete(item)){var deleteText=translationService.translate("web-workorder-workOrderXResourceGroup-delete","Slett ressurs"),enableDelete=!0;"History"===$scope.model.Stage?(enableDelete=!1,deleteText=translationService.translate("web-workorder-workOrderXResourceGroup-delete-woIsHistory","Kan ikke slette ressurs når AO er i historikk.")):$scope.model.EndDate?(enableDelete=!1,deleteText=translationService.translate("web-workorder-workOrderXResourceGroup-delete-woHasEndDate","Kan ikke slette ressurs når AO er fullført.")):"Project"===$scope.model.Stage&&$scope.model.Project&&$scope.model.Project.ClosedDate?(enableDelete=!1,deleteText=translationService.translate("web-workorder-workOrderXResourceGroup-delete-projectIsCompleted","Kan ikke slette ressurs når AO er koblet til et fullført prosjekt.")):item.IsInvoiced&&(enableDelete=!1,deleteText=translationService.translate("web-workorder-workOrderXResourceGroup-delete-isInvoiced","Kan ikke slette fakturert ressurs")),options.push({hasTopDivider:!0,html:' '+deleteText+"",click:function($itemScope,$event,modelValue,text,$li){me.remove(item)},enabled:enableDelete})}return options},this.canEdit=function(workOrderXResourceGroup){return workOrderXResourceGroup&&$scope.hasEditAccess("WorkOrderXResourceGroup")},this.canDelete=function(workOrderXResourceGroup){return workOrderXResourceGroup&&$scope.hasDeleteAccess("WorkOrderXResourceGroup")}},$scope.purchaseOrderItemInfo=new function(){var me=this;this.columns=[{Position:1,Title:translationService.translate("web-purchaseOrderItem-Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-purchaseOrderItem-Description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-supplier-Description","Leverandør navn"),Property:"Supplier.Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-purchaseOrderItem-OrderedQuantity","Bestilt antall"),Property:"OrderedQuantity",PropertyType:"number"},{Position:5,Title:translationService.translate("web-purchaseOrderItem-UnitPrice","Enhetspris"),Property:"UnitPrice",PropertyType:"double"},{Position:6,Title:translationService.translate("web-purchaseOrderItem-OrderedAmount","Bestilt beløp"),Property:"OrderedAmount",PropertyType:"double"},{Position:7,Title:translationService.translate("web-purchaseOrderItem-Status","Status"),Property:"Status",PropertyType:"enum.PurchaseOrderItemStatus"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{PropertyFilter:[{Property:"GuidWorkOrder",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];me.columns.forEach(function(col){columns.push(col.Property)}),columns.push("PurchaseOrder.Id"),columns.push("IsInvoiced"),repository.GetPaginated(repository.apiData.purchaseOrderItem.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){me.table.settings().total=result.TotalCount,me.table.settings().filterDelay=500,$defer.resolve(result.List)})}}))},this.canEdit=function(purchaseOrderItem){return purchaseOrderItem&&$scope.hasEditAccess("PurchaseOrderItem")},this.canDelete=function(purchaseOrderItem){return purchaseOrderItem&&$scope.hasDeleteAccess("PurchaseOrderItem")&&"Proposal"===purchaseOrderItem.Status},this.canCreateCost=function(purchaseOrderItem){return purchaseOrderItem&&$scope.hasCreateAccess("Cost")&&"Proposal"!==purchaseOrderItem.Status&&"Closed"!==purchaseOrderItem.Status};var openAddModal=function(){$modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"md",resolve:{params:function(){var guidCostCenter,costCenterCaption;return $scope.model.Area&&$scope.model.Area.GuidCostCenter?(guidCostCenter=$scope.model.Area.GuidCostCenter,costCenterCaption=$scope.model.Area.CostCenter.Caption):$scope.model.Building&&$scope.model.Building.GuidCostCenter?(guidCostCenter=$scope.model.Building.GuidCostCenter,costCenterCaption=$scope.model.Building.CostCenter.Caption):$scope.model.Estate&&$scope.model.Estate.GuidCostCenter&&(guidCostCenter=$scope.model.Estate.GuidCostCenter,costCenterCaption=$scope.model.Estate.CostCenter.Caption),{purchaseOrderItem:{GuidWorkOrder:$scope.model.Guid,GuidDataOwner:repository.commonService.getFilterData().selectedDataOwner.Guid,GuidBuilding:$scope.model.GuidBuilding,GuidSupplier:$scope.model.GuidSupplier,Supplier:$scope.model.Supplier,GuidDepartment:$scope.model.GuidDepartment,GuidCostCenter:guidCostCenter},costCenterCaption:costCenterCaption}}}}).result.then(function(result){me.table.reload()})};this.add=function(){$scope.model.StartDate?originalStartDate!==$scope.model.StartDate?updateEntity().then(function(result){openAddModal()}).catch(error):openAddModal():swal(translationService.translate("web-swal-workorder-addPurchaseOrderItemError","Feil ved opprettelse av bestillingsobjekt"),translationService.translate("web-swal-workorder-addPurchaseOrderItem-ErrorMessage","Det er ikke mulig å legge til bestillingsobjekt på en arbeidsordre uten startdato"),"warning")},this.update=function(purchaseOrderItem){me.canEdit(purchaseOrderItem)&&$modal.open({templateUrl:"app/purchaseOrder/views/purchaseOrderItemModal.html",controller:"PurchaseOrderItemModalController",size:"xl",resolve:{params:function(){return{Guid:purchaseOrderItem.Guid}}}}).result.then(function(result){me.table.reload()})},this.remove=function(purchaseOrderItem){me.canDelete(purchaseOrderItem)&&swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-purchaseOrderItem-message","Bestilling objektet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-purchaseOrderItem-button-confirm","Ja, fjern bestilling objektet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.purchaseOrderItem.url,purchaseOrderItem.Guid).then(function(result){swal(translationService.translate("web-swal-purchaseOrderItem-success","Bestilling objektet ble fjernet!"),result,"success"),repository.growl(translationService.translate("web-workorder-purchaseorder-removed","Bestilling objektet er fjernet fra bestillingen"),"success"),me.table.reload()})})},this.createCost=function(purchaseOrderItem){if(me.canCreateCost(purchaseOrderItem)){var persistedData={};persistedData.GuidPurchaseOrderItem=purchaseOrderItem.Guid,persistedData.PurchaseOrderItem=purchaseOrderItem.Caption,repository.persistedData.setPersistedData("cost.create",persistedData),$scope.$parent.navigation.go("cost.create",{showPersistantData:!0},{reload:!0})}},this.contextMenuOptions=function(item){var options=[];if(me.canEdit(item)){var editIcon=" fa-pen-to-square",editText=translationService.translate("web-workorder-purchaseorderitem-edit","Rediger konteringsobjekt"),restrictContextEdit=$scope.model.EndDate||"History"===$scope.model.Stage||"Project"===$scope.model.Stage&&$scope.model.Project&&$scope.model.Project.ClosedDate;(item.IsInvoiced||restrictContextEdit)&&(editIcon="fa-eye",editText=translationService.translate("web-workorder-purchaseorderitem-open","Åpne konteringsobjekt")),options.push({html:' '+editText+"",click:function($itemScope,$event,modelValue,text,$li){me.update(item)}})}if(item.GuidPurchaseOrder&&$rootScope.userInfo.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:item.GuidPurchaseOrder})," fa-cart-shopping",translationService.translate("web-workorder-viewPurchaseOrder","Se bestilling"))),me.canCreateCost(item)&&options.push({html:' '+translationService.translate("web-workorder-purchaseorderitem-createCost","Legg til kostnad")+"",click:function($itemScope,$event,modelValue,text,$li){me.createCost(item)}}),me.canDelete(item)){var deleteText=translationService.translate("web-workorder-purchaseOrderItem-delete","Slett konteringsobjekt"),enableDelete=!0;"History"===$scope.model.Stage?(enableDelete=!1,deleteText=translationService.translate("web-workorder-purchaseOrderItem-delete-woIsHistory","Kan ikke slette konteringsobjekt når AO er i historikk.")):$scope.model.EndDate?(enableDelete=!1,deleteText=translationService.translate("web-workorder-purchaseOrderItem-delete-woHasEndDate","Kan ikke slette konteringsobjekt når AO er fullført.")):"Project"===$scope.model.Stage&&$scope.model.Project&&$scope.model.Project.ClosedDate?(enableDelete=!1,deleteText=translationService.translate("web-workorder-purchaseOrderItem-delete-projectIsCompleted","Kan ikke slette konteringsobjekt når AO er koblet til et fullført prosjekt.")):item.IsInvoiced&&(enableDelete=!1,deleteText=translationService.translate("web-workorder-purchaseOrderItem-delete-isInvoiced","Kan ikke slette fakturert konteringsobjekt")),options.push({hasTopDivider:!0,html:' '+deleteText+"",click:function($itemScope,$event,modelValue,text,$li){me.remove(item)},enabled:enableDelete})}return options}},$scope.costInfo=new function(){this.columns=[],this.columns.addColumn=function(translationId,defaultText,property,propertyType){return this.push({Position:this.length,Title:translationService.translate(translationId,defaultText),Property:property,PropertyType:propertyType}),this},this.columns.addColumn("web-cost-InvoiceNumber","Fakturanr.","InvoiceNumber","string").addColumn("web-account-id","Konto","Account.Id","string").addColumn("web-account-description","Beskrivelse","Account.Description","string").addColumn("web-cost-amount","Beløp","Amount","double").addColumn("web-cost-InvoiceDate","Fakturadato","InvoiceDate","date").addColumn("web-supplier-description","Leverandør","Supplier.Description","string").addColumn("web-cost-vouchernumber","Bilagsnr","VoucherNumber","string")};var getCardTables=function(){$scope.sparePartInfo.initTable(),$scope.purchaseOrderItemInfo.initTable(),$scope.requestModel=null,$scope.hasReadAccess(repository.apiData.request.prefix)&&repository.GetPaginated(repository.apiData.request.url,0,1,{Id:"asc"},{PropertyFilter:[{Property:"GuidWorkOrder",Operator:"=",Value:$scope.model.Guid}]}).then(function(result){$scope.requestModel=result.List[0]})},setProperties=function(){var workOrder=$scope.model;workOrder.Estate&&($scope.modelDto.estate=workOrder.Estate.Caption),workOrder.Building&&($scope.modelDto.building=workOrder.Building.Caption),workOrder.Equipment&&($scope.modelDto.equipment=workOrder.Equipment.Caption),workOrder.Project&&($scope.modelDto.project=workOrder.Project.Caption),workOrder.Area&&($scope.modelDto.area=workOrder.Area.Caption),workOrder.Department&&($scope.modelDto.department=workOrder.Department.Caption),workOrder.Supplier&&($scope.modelDto.supplier=workOrder.Supplier.Caption),workOrder.Customer&&($scope.modelDto.customer=workOrder.Customer.Caption),workOrder.InvoiceCustomer&&($scope.modelDto.invoiceCustomer=workOrder.InvoiceCustomer.Description),workOrder.ResourceResponsible&&($scope.modelDto.resourceResponsible=workOrder.ResourceResponsible.Caption),workOrder.Person&&($scope.modelDto.person=workOrder.Person.Caption),workOrder.Priority&&workOrder.Priority.Color&&($scope.model.Priority.Color=colorService.convertToRainbow(workOrder.Priority.Color))},columns=["Estate.Id","Estate.Description","Estate.Guid","Estate.GuidCostCenter","Estate.CostCenter.Id","Estate.CostCenter.Description","Building.Id","Building.Description","Building.GuidCostCenter","Building.Guid","Building.CostCenter.Id","Building.CostCenter.Description","Equipment.Id","Equipment.Description","Equipment.Guid","Equipment.CanHaveDowntime","Area.Id","Area.Description","Area.Guid","Area.IsHousing","Area.GuidCostCenter","Area.CostCenter.Id","Area.CostCenter.Description","Project.Id","Project.Description","Project.Guid","Project.ClosedDate","Project.GuidOwnerPerson","Project.GuidManagerPerson","ResourceGroup.Id","ResourceGroup.Description","ResourceGroup.CostPrHour","Department.Id","Department.Description","Cause.Id","ActivityCategory.Description","ActivityCategory.UseInRequest","ResponsiblePerson.FirstName","ResponsiblePerson.LastName","ResponsiblePerson.Email","Supplier.Id","Supplier.Description","ActivityGroup.Id","Request.GuidEquipment","Request.GuidBuilding","Customer.Id","Customer.Description","PeriodicTask.GuidEquipment","PeriodicTask.GuidBuilding","PeriodicTask.GuidEstate","PeriodicTask.Period","PeriodicTask.Id","PeriodicTask.Description","Priority.Description","Priority.HasDeadline","Priority.DeadlinePeriodNumber","Priority.DeadlinePeriodUnit","Priority.Color","ResourceResponsible.FirstName","ResourceResponsible.LastName","ResourceResponsible.Email","UserPrintedBy.RealName","UserUpdatedBy.RealName","UserCreatedBy.RealName","UserClosedBy.RealName","InvoiceCustomer.Id","InvoiceCustomer.Description"],getPresets=function(){var defer=$q.defer();return $scope.isUpdate?$.Deferred().resolve(null).promise():(registeredFieldService.getRegisteredField(repository.commonService.prefix.WorkOrder).then(function(registeredFields){var customerRule=_.filter(registeredFields,{DomainFieldName:"GuidCustomer"})[0],presets=null,setParameter=function(name,value){return!!value&&(presets||(presets={}),presets[name]=value,!0)},selectedBuilding=repository.commonService.getFilterData().selectedBuilding;if(selectedBuilding&&(setParameter("GuidBuilding",selectedBuilding.Guid),selectedBuilding.Estate&&setParameter("GuidEstate",selectedBuilding.Estate.Guid)),repository.commonService.getFilterData().selectedEstate&&setParameter("GuidEstate",repository.commonService.getFilterData().selectedEstate.Guid),$stateParams.showPersistantData){var persistentData=repository.persistedData.getPersistedData("workOrder.create");persistentData&&(setParameter("GuidEstate",persistentData.guidEstate),setParameter("GuidBuilding",persistentData.guidBuilding),setParameter("GuidArea",persistentData.guidArea),setParameter("GuidEquipment",persistentData.guidEquipment),setParameter("GuidProject",persistentData.guidProject),customerRule&&!customerRule.Hidden&&setParameter("GuidCustomer",persistentData.guidCustomer),persistentData.model&&(setParameter("GuidResourceGroup",persistentData.model.GuidResourceGroup),setParameter("GuidResponsiblePerson",persistentData.model.GuidResponsiblePerson),setParameter("GuidDepartment",persistentData.model.GuidDepartment),setParameter("GuidCause",persistentData.model.GuidCause),setParameter("GuidActivityCategory",persistentData.model.GuidActivityCategory),setParameter("GuidPriority",persistentData.model.GuidPriority)),setParameter("GuidRequest",persistentData.guidRequest))}var webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){if("object"==typeof prefill.Value)switch(prefill.Property){case"Building":case"Equipment":case"Area":case"ResourceResponsible":case"ActivityCategory":case"Priority":case"Cause":case"Department":case"ResourceGroup":case"Customer":case"Supplier":case"ResponsiblePerson":case"ActivityGroup":case"InvoiceCustomer":setParameter("Guid"+prefill.Property,prefill.Value.Guid)}else if("@CurrentBuilding"===prefill.Value){var building=repository.commonService.getFilterData().selectedBuilding;building.Guid&&setParameter("GuidBuilding",building.Guid)}else"@LoggedInPerson"===prefill.Value&&setParameter("GuidResponsiblePerson",repository.authService.getUserData().guidPerson)}),defer.resolve(presets)}),defer.promise)},onCreate=function(){setProperties();var workOrder=$scope.model;if($scope.canEditProjectReference=!0,$stateParams.showPersistantData){var persistentData=repository.persistedData.getPersistedData("workOrder.create");if(persistentData){if(persistentData.defaultDescription&&(workOrder.Description=persistentData.defaultDescription),persistentData.defaultReference&&(workOrder.Reference=persistentData.defaultReference),persistentData.defaultText&&(workOrder.ExplanatoryText=persistentData.defaultText),persistentData.defaultStartDate&&(workOrder.StartDate=persistentData.defaultStartDate),persistentData.guidRequest){generatedFrom=repository.commonService.prefix.Request;for(var countCombo=1;countCombo<=40;countCombo++){var fieldCombo="Combo"+String(countCombo).padStart(2,"0");persistentData[fieldCombo]&&(workOrder[fieldCombo]=persistentData[fieldCombo])}for(var countDate=1;countDate<=30;countDate++){var fieldDate="Date"+String(countDate).padStart(2,"0");persistentData&&(workOrder[fieldDate]=persistentData[fieldDate])}for(var countText=1;countText<=30;countText++){var fieldText="Text"+String(countText).padStart(2,"0");persistentData[fieldText]&&(workOrder[fieldText]=persistentData[fieldText])}for(var countNumber=1;countNumber<=10;countNumber++){var fieldNumber="Number"+String(countNumber).padStart(2,"0");persistentData[fieldNumber]&&(workOrder[fieldNumber]=persistentData[fieldNumber])}}persistentData.fromDeviation&&(workOrder.DeviationGuids=[],persistentData.guidSelections.forEach(function(guid){workOrder.DeviationGuids.push(guid)}),generatedFrom=repository.commonService.prefix.Deviation,1===persistentData.guidSelections.length&&persistentData.enumTypeGuid&&repository.getSingle(repository.apiData.deviationType.url,persistentData.enumTypeGuid).then(function(result){result&&result.Data&&(workOrder.Description=workOrder.Description+" - "+result.Data.Id)})),persistentData.fromCondition&&(workOrder.ConditionGuids=[],persistentData.guidSelections.forEach(function(guid){workOrder.ConditionGuids.push(guid)}),generatedFrom=repository.commonService.prefix.Condition),persistentData.fromEquipment&&(generatedFrom=repository.commonService.prefix.Equipment),persistentData.fromOperationalMessage&&(generatedFrom=repository.commonService.prefix.OperationalMessage,workOrder.OperationalMessageGuids=[],persistentData.guidSelections.forEach(function(guid){workOrder.OperationalMessageGuids.push(guid)})),persistentData.guidProject&&(generatedFrom=repository.commonService.prefix.Project)}}$scope.modelDto.CompletionRate=workOrder.CompletionRate||0,$timeout(function(){$scope.activateAutocomplete=!0},250);var webMenuParams=repository.getMenuParameters($scope.navigation.params.menuGuid);webMenuParams&&webMenuParams.Prefill&&webMenuParams.Prefill.forEach(function(prefill){"object"!=typeof prefill.Value&&"@CurrentBuilding"!==prefill.Value&&"@LoggedInPerson"!==prefill.Value&&($scope.model[prefill.Property]=prefill.Value)}),workOrder.Priority&&$scope.onPrioritySelect(workOrder.Priority),workOrder.Description&&(workOrder.Description=workOrder.Description.substr(0,fieldLengths.Description)),workOrder.GuidArea?prefillCustomerFromArea(workOrder.GuidArea,!0):workOrder.GuidCustomer&&prefillAreaFromCustomer(workOrder.GuidArea,!0)},onGet=function(response){var workOrder=response.Data?response.Data:response;$scope.model=workOrder,originalStartDate=$scope.model.StartDate,$scope.extendWorkOrderType=getWorkOrderType(),$scope.isUpdate?(getCardTables(),$scope.enableWebNavigation=$rootScope.userInfo.enableWebNavigation,$scope.isClosable="Proposal"===$scope.model.PurchaseOrderStatus||"NoOrder"===$scope.model.PurchaseOrderStatus,$scope.restrictDueDate=!!$scope.model.Priority&&!!$scope.model.Priority.HasDeadline,$scope.modelDto.CompletionRate=Number((100*$scope.model.CompletionRate).toFixed(0)),setProperties(),updateAccess(),workOrder.GuidProject?$scope.canEditProjectReference=workOrder.Project.GuidManagerPerson===$scope.userInfo.guidPerson||workOrder.Project.GuidOwnerPerson===$scope.userInfo.guidPerson||$scope.userInfo.isProjectAdministrator||$scope.userInfo.isSystemAdministrator:$scope.canEditProjectReference=!0,$scope.reloads.documents=!0,$scope.reloads.deviations=!0,$scope.reloads.alarmLogs=!0,$scope.reloads.controlLists=!0,$scope.reloads.economyInfo=!0,$scope.reloadConditions=!0,$timeout(function(){$scope.activateAutocomplete=!0},250)):onCreate()},getEntity=function(){var defer=$q.defer(),queryString=JSON.stringify(columns);return $stateParams.guidEntityToCopy&&(queryString+="&GuidCopyFrom="+$stateParams.guidEntityToCopy),getPresets().then(function(presets){repository.getMainModel(repository.apiData.workOrder.url,$scope.isUpdate?$stateParams.guid:"00000000-0000-0000-0000-000000000000",queryString,presets?JSON.stringify(presets):null).then(function(response){onGet(response),defer.resolve(response)}).catch(function(error){repository.growl(error,"danger"),defer.reject()})}),defer.promise},updateEntity=function(){var defer=$q.defer(),parentProperties=[];for(var propertyName in $scope.model)if(propertyName.startsWith("Guid")){var parentPropertyName=_.capitalize(propertyName.substring(4)),parent=$scope.model[parentPropertyName];parent&&parentProperties.push(parentPropertyName)}var payloadEntity=angular.copy($scope.model);return parentProperties.forEach(function(field){delete payloadEntity[field]}),function(){($scope.isUpdate?repository.updateSingle:repository.createSingle)(repository.apiData.workOrder.url,payloadEntity).then(function(response){parentProperties.forEach(function(field){!response[field]&&response["Guid"+field]&&$scope.model[field]&&(response[field]=angular.copy($scope.model[field]))}),onGet(response),defer.resolve(response)}).catch(function(error){defer.reject(error)})}(),defer.promise};getEntity(),$scope.onResourceGroupSelect=function(resourceGroup){if(!resourceGroup)return void($scope.model.GuidResourceGroup="");$scope.model.GuidResourceGroup=resourceGroup.Guid},$scope.onResponsiblePersonSelect=function(person){if(!person)return void($scope.model.GuidResponsiblePerson="");$scope.activateAutocomplete=!1,$scope.model.GuidResponsiblePerson=person.Guid,$localStorage.generalOptions.OverrideActWithPersInfo&&($scope.model.GuidResourceGroup!==person.GuidResourceGroup&&($scope.model.GuidResourceGroup=person.GuidResourceGroup,$scope.model.ResourceGroup={Guid:person.GuidResourceGroup,Caption:person.ResourceGroup?person.ResourceGroup.Caption:null}),$scope.model.GuidDepartment!==person.GuidDepartment&&($scope.model.GuidDepartment=person.GuidDepartment,$scope.modelDto.department=person.Department?person.Department.Caption:null)),$timeout(function(){$scope.activateAutocomplete=!0},250)},$scope.onEstateSelect=function(estate){if(!estate)return void($scope.model.GuidEstate="");$scope.model.GuidEstate!==estate.Guid&&($scope.model.GuidBuilding="",$scope.modelDto.building="",$scope.model.GuidEquipment="",$scope.modelDto.equipment="",$scope.model.GuidArea="",$scope.modelDto.area=""),$scope.model.GuidEstate=estate.Guid},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidEquipment="",$scope.modelDto.equipment="",$scope.model.GuidArea="",$scope.modelDto.area=""),$scope.model.GuidBuilding=building.Guid,$scope.model.GuidEstate&&""!==$scope.model.GuidEstate&&$scope.model.GuidEstate===building.GuidEstate||($scope.model.GuidEstate=building.GuidEstate,$scope.modelDto.estate=building.Estate.Id+" - "+building.Estate.Description)},$scope.onEquipmentSelect=function(equipment){if(!equipment)return void($scope.model.GuidEquipment="");$scope.model.GuidEquipment=equipment.Guid,$scope.model.GuidEstate&&""!==$scope.model.GuidEstate||($scope.model.GuidEstate=equipment.GuidEstate||equipment.Building.Estate.Guid,$scope.modelDto.estate=equipment.Building.Estate.Id+" - "+equipment.Building.Estate.Description),$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=equipment.GuidBuilding,$scope.modelDto.building=equipment.Building.Id+" - "+equipment.Building.Description),equipment.GuidArea&&($scope.model.GuidArea=equipment.GuidArea,$scope.modelDto.area=equipment.Area.Id+" - "+equipment.Area.Description)},$scope.onAreaSelect=function(area){if(!area)return void($scope.model.GuidArea="");$scope.model.GuidArea=area.Guid,$scope.model.GuidBuilding&&""!==$scope.model.GuidBuilding||($scope.model.GuidBuilding=area.GuidBuilding,$scope.modelDto.building=area.Building.Id+" - "+area.Building.Description),$scope.model.GuidEstate&&""!==$scope.model.GuidEstate||($scope.model.GuidEstate=area.GuidEstate||area.Building.Estate.Guid,$scope.modelDto.estate=area.Building.Estate.Id+" - "+area.Building.Estate.Description),prefillCustomerFromArea(area.Guid)},$scope.onCustomerSelect=function(customer){if(!customer)return void($scope.model.GuidCustomer="");$scope.model.GuidCustomer=customer.Guid,prefillAreaFromCustomer(customer.Guid)},$scope.autoCompleteFilter=function(filterName){var filter={},estateFieldRule=registeredFieldService.getLocalRegisteredField(repository.apiData.workOrder.prefix,"GuidEstate"),isEstateHidden=estateFieldRule&&estateFieldRule.Hidden;switch(filterName){case"estate":return filter;case"activityCategory":return{PropertyFilter:[{Property:"UseInWorkOrder",Operator:"=",Value:"true"},{Property:"IsAbstract",Operator:"=",Value:"0"}]};case"building":return $scope.model.GuidEstate&&!isEstateHidden?(filter.PropertyFilter=[{Property:"GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}],filter):filter;case"equipment":return filter={GuidBuilding:$scope.model.GuidBuilding,IsMaintainable:1,PropertyFilter:[]},!$scope.model.GuidEstate||$scope.model.GuidBuilding||isEstateHidden||(filter.PropertyFilter=[{Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]),filter.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:!1}),filter;case"area":return filter={GuidBuilding:$scope.model.GuidBuilding},$scope.model.GuidEstate&&!isEstateHidden&&(filter.PropertyFilter=[{Property:"Building.GuidEstate",Operator:"=",Value:$scope.model.GuidEstate}]),filter;case"person":return $localStorage.generalOptions.UseOnlyActivPersonOnActiv&&(filter.DoesMaintenanceTasks=1),$localStorage.generalOptions.UseOnlyPersInBldOnActiv&&(filter.GuidBuildingResponsible=$scope.model.GuidBuilding),filter;case"resourceResponsible":return filter.DoesMaintenanceTasks=!0,filter;case"resourceGroup":return filter.PropertyFilter=[{Property:"DoesMaintenanceTasks",Operator:"=",Value:"true"}],filter;case"supplier":return filter.PropertyFilter=[{Property:"IsDeactivated",Operator:"=",Value:"false"}],filter;case"priority":return filter.PropertyFilter=[{Property:"EntityType",Operator:"=",Value:6}],filter;case"cause":return $scope.model.GuidResourceGroup&&(filter.FilterOnResourceGroup=$scope.model.GuidResourceGroup),filter;case"project":return filter.FilterModel={Condition:"and",Rules:[{Property:"ClosedDate",Operator:"=",value:null},{Property:"IsTemplate",Operator:"=",value:!1}]},$localStorage.userData.isSystemAdministrator||$localStorage.userData.isProjectAdministrator||filter.FilterModel.Rules.push({Condition:"or",Rules:[{Property:"GuidOwnerPerson", Operator:"=",value:$localStorage.userData.guidPerson},{Property:"GuidManagerPerson",Operator:"=",value:$localStorage.userData.guidPerson}]}),filter}},$scope.completeWorkOrder=function(){$modal.open({templateUrl:"app/workOrder/views/completeWorkOrderModal.html",controller:"CompleteWorkOrderModalController",scope:$scope}).result.then(function(result){$scope.newResourceGroup={RealTime:result.RealTime,Note:result.Note,GuidHourType:result.GuidHourType},$scope.createWorkOrder("workOrder.list",!0)},function(reason){"canceled"===reason&&getEntity()})},$scope.activateWorkOrder=function(){if("Project"!==$scope.model.Stage)return!1;workOrderService.activateWorkOrders([$scope.model.Guid]).then(function(result){$scope.goBack("workOrder.edit",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid}),repository.growl(translationService.translate("web-workorder-activate-success","Arbeidsordren er aktivert"),"success")}).catch(function(error){repository.growl(error,"danger")})},$scope.closeWorkOrder=function(){repository.updateSingle(repository.apiData.workOrder.endpoint.closePayment,{Guid:$scope.model.Guid,GuidUser:repository.authService.getUserData().guidUser}).then(function(result){repository.growl(translationService.translate("web-workorder-close-success","Arbeidsordren er lukket"),"success"),$scope.goBack("workOrder.edit",{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid})},function(error){repository.growl(error,"danger")})},$scope.releaseWorkOrder=function(){$scope.model.EndDate=null,$scope.createWorkOrder("workOrder.edit")};var convertToDate=function(date){return"string"==typeof date?new Date(date):date||null},hasShowError=!1;$scope.createWorkOrder=function(destination,showErrorAsSwal){hasShowError=!1;var workOrder=$scope.model;workOrder.StartDate=convertToDate(workOrder.StartDate),workOrder.PrintedDate=convertToDate(workOrder.PrintedDate),workOrder.EndDate=convertToDate(workOrder.EndDate),workOrder.ReportedEndDate=convertToDate(workOrder.ReportedEndDate),workOrder.DueDate=convertToDate(workOrder.DueDate),workOrder.CompletionRate=$scope.modelDto.CompletionRate/100;var successNavigate=function(destination,guid){"function"==typeof $stateParams.onSaved&&$stateParams.onSaved(angular.copy($scope.model)),$scope.isModal&&"workOrder.edit"===destination||($scope.isModal?$scope.cancel():$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid}))},success=function(result){repository.growl($scope.isUpdate?translationService.translate("web-workorder-update","Arbeidsordren ble oppdatert"):translationService.translate("web-workorder-created","Arbeidsordren er opprettet"),"success");var guid=$scope.isUpdate?workOrder.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid),$scope.isUpdate&&$scope.isDirtyEndDate&&workOrder.PeriodicTask&&"HourOfUse"===workOrder.PeriodicTask.Period?($scope.isDirtyEndDate=!1,$modal.open({templateUrl:"app/equipment/views/equipmentOperatingHoursModal.html",controller:"EquipmentOperatingHoursController",size:"sm",resolve:{params:function(){return{GuidEquipment:workOrder.GuidEquipment,ReadDate:new Date,GuidPeriodicTask:workOrder.GuidPeriodicTask}}}}).result.then(function(){successNavigate(destination,guid)},function(){successNavigate(destination,guid)})):successNavigate(destination,guid)},error=function(error){workOrder.EndDate&&"History"!==workOrder.Stage&&delete workOrder.EndDate;var errorMessage="string"==typeof error?error:error.Data.Message;!hasShowError&&errorMessage.includes(translationService.translate("api-workOrder-checkStateStatusOfWorkOrder-newControlList","En eller flere kontrollister blir lagt til p.g.a kontrolliste regler. Vennligst vent litt og se igjennom de nye kontrollistene før du prøver å fullføre."))&&(hasShowError=!0,destination="workOrder.edit",updateEntity().then(success,error)),showErrorAsSwal?swal("",errorMessage.split(/, (?=[A-Z])/).join("\n\n"),"warning"):repository.growl(errorMessage,"danger"),hasShowError=!0},runUpdate=function(){if($scope.newResourceGroup&&$scope.newResourceGroup.RealTime&&$scope.userInfo.guidPerson){var columns=["ResourceGroup.CostPrHour"];return void repository.getSingle(repository.apiData.person.url,$scope.userInfo.guidPerson,JSON.stringify(columns)).then(function(result){var person=result.Data,costPrHour=person.ResourceGroup.CostPrHour,registeredDate=$scope.model.EndDate?$scope.model.EndDate:(new Date).toISOString(),resourceGroup={GuidWorkOrder:workOrder.Guid,GuidPerson:person.Guid,GuidHourType:$scope.newResourceGroup.GuidHourType,GuidPersonResourceGroup:person.GuidResourceGroup,GuidResourceGroup:person.GuidResourceGroup,RealTime:$scope.newResourceGroup.RealTime,Note:$scope.newResourceGroup.Note,EstimatedTime:0,EstimatedCost:0,RealCost:costPrHour*$scope.newResourceGroup.RealTime,RegisteredDate:registeredDate};repository.createSingle(repository.apiData.workOrderXResourceGroup.url,resourceGroup).then(function(result){$scope.newResourceGroup=null,$scope.resourceGroupInfo.table.reload(),updateEntity().then(success,error)}).catch(function(result){repository.growl(result,"danger")})})}$scope.isUpdate?updateEntity().then(success,error):(workOrder.GeneratedFrom=generatedFrom,!workOrder.EndDate||generatedFrom!==repository.commonService.prefix.Deviation&&generatedFrom!==repository.commonService.prefix.Condition?updateEntity().then(success,error):swal({title:translationService.translate("web-swal-error-Wo-FromInvalid-title","Direkte opprettelse og lukking av AO er ikke mulig"),text:translationService.translate("web-swal-error-Wo-FromInvalid-description","Det er ikke mulig å opprette en arbeidsordre med ferdigdato ferdig utfylt når arbeidsordre blir opprettet fra avvik eller tilstand"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-error-Wo-FromInvalid-confirm","Opprett uten ferdigmelding"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,delete workOrder.EndDate,$scope.createWorkOrder(destination)}))},shouldActivate=function(){var deferred=$q.defer();if($scope.isUpdate&&"Project"===workOrder.Stage&&(workOrder.EndDate||0!==workOrder.CompletionRate)){var text=translationService.translate("web-swal-workOrder-activate-message-following","Følgende handlinger forrårsaket denne meldingen: \n");workOrder.EndDate&&(text+=translationService.translate("web-workOrder-EndDate","Sluttdato")+"\n"),0!==workOrder.CompletionRate&&(text+=translationService.translate("web-workOrder-CompletionRate","Fullføringsgrad")+"\n"),workOrderService.shouldActivateWorkOrder(null,text).then(function(result){workOrder.Stage="Active",deferred.resolve()},function(error){error&&repository.growl(error),deferred.reject()})}else deferred.resolve();return deferred.promise};moment(workOrder.EndDate).isAfter(moment(new Date))?swal({title:translationService.translate("web-workOrder-endDate-forwardInTime","Ferdigdato er satt frem i tid"),text:translationService.translate("web-workOrder-endDate-continue","Fortsette?"),type:"warning",confirmButtonText:"Fortsett",showCancelButton:!0,cancelButtonText:"Avbryt"},function(result){swal.close(),$timeout(function(){result&&shouldActivate().then(function(){runUpdate()})},100)}):shouldActivate().then(function(){runUpdate()})},$scope.sendEmail=function(){var onNewDocument=($scope.documents.concat($scope.model.Images),function(){$scope.reloads.forceDocuments=!1,$timeout(function(){$scope.reloads.forceDocuments=!0},250)}),onNewImage=function(){repository.getMainModel(repository.apiData.workOrder.url,$stateParams.guid).then(function(response){$scope.model.Images=response.Data.Images})};$modal.open({templateUrl:"app/common/views/emailModal.html",controller:"EmailModalController",size:"lg",resolve:{params:function(){return{entity:"WorkOrder",model:$scope.model,prefillSubjectWithCaption:!0,onNewDocument:onNewDocument,onNewImage:onNewImage}}}}).result.then(function(){$scope.reloads.alarmLogs=!0})},$scope.removeWorkOrder=function(){var text=$scope.model.GuidRequest?translationService.translate("web-swal-workorder-hasrequestmessage","Arbeidsordren er koblet opp mot en melding. Ønsker du fortsatt å slette arbeidsordren?"):translationService.translate("web-swal-workorder-message","Arbeidsordren vil bli permanent fjernet!");swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:text,type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-workorder-button-confirm","Ja, slett arbeidsordren!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.workOrder.url,$scope.model.Guid).then(function(){swal.close(),$scope.goBack("workOrder.list",{menuGuid:$scope.navigation.params.menuGuid}),repository.growl(translationService.translate("web-workOrder-growl-deleted","Arbeidsordren har blitt fjernet"),"success")})})},$scope.onStartDateSelect=function(){$scope.model.StartDate&&$scope.model.Priority&&$scope.onPrioritySelect($scope.model.Priority)},$scope.onPrioritySelect=function(priority){if(!priority)return $scope.model.GuidPriority="",void delete $scope.model.Priority;$scope.model.GuidPriority=priority.Guid,$scope.model.Priority=priority,priority.HasDeadline?($scope.restrictDueDate=!0,$scope.model.StartDate||($scope.model.StartDate=new Date),"WorkDay"===priority.DeadlinePeriodUnit?repository.getWithUrlParameter(repository.apiData.workingDaysOff.url+repository.apiData.workingDaysOff.endpoint.getDueDate,"startDate="+new Date($scope.model.StartDate).toISOString()+"&workDays="+priority.DeadlinePeriodNumber).then(function(result){$scope.model.DueDate=result,$scope.restrictDueDate=!0}):$scope.model.DueDate=enumService.getTimeUnitDate($scope.model.StartDate,priority.DeadlinePeriodUnit,priority.DeadlinePeriodNumber)):$scope.restrictDueDate=!1},$scope.printWorkOrder=function(){$scope.model.PrintedDate=new Date,$scope.createWorkOrder("workOrder.edit");var url=$scope.navigation.href("report.print",{reportName:"PrintWorkOrder",reportParams:JSON.stringify({Guid:$scope.model.Guid})});$window.open(url,"_blank")},$scope.onActivityCategorySelect=function(category){if(!category)return $scope.newDynamicProperty=null,void($scope.model.GuidActivityCategory="");category.DynamicProperty&&category.DynamicProperty.Groups.length>0?$scope.newDynamicProperty=category.DynamicProperty:$scope.newDynamicProperty=null,$scope.model.GuidActivityCategory=category.Guid},$scope.createNewRequest=function(){var newRequest={model:angular.copy($scope.model),building:$scope.modelDto.building,area:$scope.modelDto.area,equipment:$scope.modelDto.equipment,guidWorkOrder:$scope.model.Guid,resourceGroup:$scope.model.ResourceGroup?$scope.model.ResourceGroup.Caption:null,responsiblePerson:$scope.modelDto.person,department:$scope.modelDto.department,cause:$scope.model.Cause?$scope.model.Cause.Id:null,priority:$scope.model.Priority?$scope.model.Priority.Description:null};if(delete newRequest.model.GuidGisEntity,$scope.model.ActivityCategory&&!0===$scope.model.ActivityCategory.UseInRequest){for(var countCombo=1;countCombo<=20;countCombo++){var fieldCombo="Combo"+String(countCombo).padStart(2,"0");$scope.model[fieldCombo]&&(newRequest[fieldCombo]=$scope.model[fieldCombo])}for(var countDate=1;countDate<=30;countDate++){var fieldDate="Date"+String(countDate).padStart(2,"0");$scope.model[fieldDate]&&(newRequest[fieldDate]=$scope.model[fieldDate])}for(var countText=1;countText<=20;countText++){var fieldText="Text"+String(countText).padStart(2,"0");$scope.model[fieldText]&&(newRequest[fieldText]=$scope.model[fieldText])}for(var countNumber=1;countNumber<=10;countNumber++){var fieldNumber="Number"+String(countNumber).padStart(2,"0");$scope.model[fieldNumber]&&(newRequest[fieldNumber]=$scope.model[fieldNumber])}}else newRequest.model.GuidActivityCategory="",newRequest.model.ActivityCategory=null;repository.persistedData.setPersistedData("request.create",newRequest),$scope.navigation.go("request.create",{showPersistantData:!0},{reload:!0})},$scope.addExistingRequest=function(){$modal.open({templateUrl:"app/common/views/singleSelectModal.html",controller:"SingleSelectModalController",size:"lg",resolve:{modalParams:function(){var propertyFilter=[{Property:"GuidWorkOrder",Operator:"=",Value:""},{Property:"Status",Operator:"<>",Value:"7"},{Property:"GuidWorkOrder",Operator:"=",Value:""},{Property:"Status",Operator:"<>",Value:"3"}];return $scope.model.GuidBuilding&&propertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:$scope.model.GuidBuilding,allowToggle:!0,filterValue:$scope.modelDto.building,isDisabled:!1}),$scope.model.GuidEquipment&&propertyFilter.push({Property:"GuidEquipment",Operator:"=",Value:$scope.model.GuidEquipment,allowToggle:!0,filterValue:$scope.modelDto.equipment,isDisabled:!1}),$scope.model.GuidArea&&propertyFilter.push({Property:"GuidArea",Operator:"=",Value:$scope.model.GuidArea,allowToggle:!0,filterValue:$scope.modelDto.area,isDisabled:!1}),{title:translationService.translate("web-workOrder-addExistingRequest","Legg til eksisterende melding"),url:repository.apiData.request.url,sorting:{Id:"desc"},filter:{PropertyFilter:propertyFilter},columns:[{title:translationService.translate("web-request-id","Id"),property:"Id"},{title:translationService.translate("web-building-id"),property:"Building.Id"},{title:translationService.translate("web-building-description"),property:"Building.Description"},{title:translationService.translate("web-request-description"),property:"Description"},{title:translationService.translate("web-request-contactperson"),property:"ContactPerson"},{title:translationService.translate("web-request-status"),property:"Status",PropertyType:"enum.requeststatus"},{title:translationService.translate("web-request-duedate"),property:"DueDate"},{title:translationService.translate("web-request-telephone"),property:"Telephone"}]}}}}).result.then(function(item){$scope.model.GuidRequest=item.Guid,$scope.createWorkOrder("workOrder.edit")},function(msg){})},$scope.navigate=function(){$scope.isModal?$scope.cancel():$scope.goBack("workOrder.list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.cancel=function(){$modalStack.dismissAll()},$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.generateCalendarEvent=function(){repository.getSingle(repository.apiData.workOrderCalendar.url,$scope.model.Guid,null).then(function(response){var blob=new Blob([response],{type:"text/calendar"});if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(blob,$scope.model.Id+".ics");else{var element=document.createElement("a");element.style.display="none",element.href=window.URL.createObjectURL(blob),element.download=$scope.model.Id+".ics",document.body.appendChild(element),element.click(),document.body.removeChild(element),window.URL.revokeObjectURL(element.href)}},function(error){repository.growl(error,"danger")})};var getMenuLink=function(url,icon,text){return{html:' '+text+"",isHref:!0}};$scope.isUpdate&&(signalR.on("UpdatedWorkOrderSums"+$stateParams.guid,function(updatedWorkOrder){Object.keys(updatedWorkOrder).forEach(function(key){$scope.model[key]=updatedWorkOrder[key]}),$scope.reloads.economyInfo=!1,$timeout(function(){$scope.reloads.economyInfo=!0},250)}),$scope.$on("$destroy",function(){signalR.off("UpdatedWorkOrderSums"+$stateParams.guid)}))}angular.module("Plania").controller("WorkOrderController",["$scope","Repository","$q","$stateParams","$modal","$modalStack","ngTableParams","$rootScope","$window","TranslationService","$localStorage","ListService","EnumService","$timeout","RegisteredFieldService","WorkOrderService","SignalR","AreaService","CustomerService","ColorService",controller])}(),function(){function workOrderService(repository,translationService,$q){var service={},errorMessagesStage0=[{system:"web-workOrderXResourceGroup-realTime-workOrder-stage0",default:"Kan ikke registrere timer på en planlagt arbeidsordre"},{system:"web-workOrder-stage0-completionRate",default:"Kan ikke sette fullføringsgrad på en planlagt arbeidsordre"},{system:"web-workOrder-stage0-endDate",default:"Kan ikke sette fullføringsgrad på en planlagt arbeidsordre"},{system:"web-purchaseOrder-CanActivateWorkOrder",default:"Kan ikke bestille med en eller flere bestillingsobjekter koblet til en planlagt arbeidsordre, men arbeidsordren kan bli aktivert ved å fortsette"}];return service.activateWorkOrders=function(workOrderGuids){return repository.runAction(repository.apiData.workOrder.endpoint.activateWorkOrders,workOrderGuids)},service.shouldActivateWorkOrder=function(workOrderGuid,errorMessage){var deferred=$q.defer();if(!repository.authService.hasEditAccess(repository.commonService.prefix.WorkOrder))return $.Deferred().reject(errorMessage).promise();var swalText=errorMessage;return errorMessage&&(swalText+="\n\n"),swalText+=translationService.translate("web-swal-workOrder-activate-message","Arbeidsordren må bli aktivert for å utføre denne handlingen, ønsker du å aktivere nå?"),swal({title:translationService.translate("web-swal-workOrder-activate","Arbeidsordren er ikke aktiv"),text:swalText,type:"warning",showCancelButton:!0,confirmButtonColor:"#2196f3",confirmButtonText:translationService.translate("web-button-yes","Ja"),cancelButtonText:translationService.translate("web-button-no","Nei"),closeOnConfirm:!1},function(isSuccess){window.onkeydown=null,window.onfocus=null,isSuccess?workOrderGuid?service.activateWorkOrders([workOrderGuid]).then(function(result){swal.close(),deferred.resolve(result)},function(error){swal.close();var workOrderError=translationService.translate("web-workOrder","Arbeidsordre")+" - "+error;deferred.reject(workOrderError)}):(deferred.resolve(),swal.close()):(swal.close(),deferred.reject())}),deferred.promise},service.isWorkOrderStage0=function(errorMessage){if(errorMessage)for(var i=0;i