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 shouldUseFullscreen=function(){return $state.includes("map")||$state.includes("dwg.view")||$state.includes("document.viewPdf")||$state.includes("ifcFile.view")};vm.showFullscreen=shouldUseFullscreen(),$rootScope.$on("$stateChangeSuccess",function(){vm.showFullscreen=shouldUseFullscreen()}),vm.sidebarStat=function(event){angular.element(event.target).parent().hasClass("active")||(vm.sidebarToggle.left=!1)}}!function(window,document){"use strict";function copyProperties(srcObj,destObj){for(var key in destObj)destObj.hasOwnProperty(key)&&srcObj.hasOwnProperty(key)&&(destObj[key]=srcObj[key])}function isElementInViewport(el){"function"==typeof jQuery&&el instanceof jQuery&&(el=el[0]);var rect=el.getBoundingClientRect();return rect.top>=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&&$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()),Sentry.configureScope(function(scope){scope.addEventProcessor(function(event){return $localStorage.generalOptions&&$localStorage.generalOptions.SentryTrackIssues&&$localStorage.planiaStatus&&$localStorage.planiaStatus.ApplicationVersion?$localStorage.planiaStatus.ApplicationVersion.endsWith(".1001")?null:$location.host().startsWith("localhost")?null:(event.release=$localStorage.planiaStatus.ApplicationVersion,event.request&&event.request.url&&event.request.url!==$location.absUrl()&&(event.request.url=$location.absUrl()),event):null})}),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}String.prototype.includes||(String.prototype.includes=function(search,start){"use strict";return"number"!=typeof start&&(start=0),!(start+search.length>this.length)&&-1!==this.indexOf(search,start)}),String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(search,pos){return pos=!pos||pos<0?0:+pos,this.substring(pos,pos+search.length)===search}}),String.prototype.capitalizeFirstLetter||Object.defineProperty(String.prototype,"capitalizeFirstLetter",{value:function(){return this.charAt(0).toUpperCase()+this.slice(1)}}),Array.prototype.includes||(Array.prototype.includes=function(search,start){"use strict";return"number"!=typeof start&&(start=0),!(start>=this.length)&&-1!==this.indexOf(search,start)}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{value:function(predicate){if(null===this)throw new TypeError('"this" is null or not defined');var o=Object(this),len=o.length>>>0;if("function"!=typeof predicate)throw new TypeError("predicate must be a function");for(var thisArg=arguments[1],k=0;k"},{name:"dashboard.view",url:"/view/:guid?:menuGuid??filter",availableWebMenu:"Dashboard",filters:dashboardFilter,params:{editMode:!1},templateUrl:"app/dashboard/dashboard.html",controller:"DashboardController"},{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",params:{showPersistantData:!1,menuGuid:"",guidEntityToCopy:""},templateUrl:"app/workOrder/views/editWorkOrder.html",controller:"WorkOrderController",excludeFromHistory:!0},{name:"workOrderTemplate",url:"/workOrderTemplate",abstract:!0,template:""},{name:"workOrderTemplate.list",availableWebMenu:"",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:"KontaktPersonliste",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:"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:"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.userWebProfile}},{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:"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:"Kart entitetsliste",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",templateUrl:"app/planiasystem/views/planiaSystem.html",controller:"PlaniaSystemController"},{name:"controlList",url:"/controlList",abstract:!0,template:""},{name:"controlList.list",availableWebMenu:"Sjekkliste",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.list",availableWebMenu:"Tegning",filters:drawingFilter,url:"/list/:menuGuid??filter",templateUrl:"app/dwg/views/listDrawing.html",controller:"ListController",params:{entityData:apiData.drawing}},{name:"ifcFile",url:"/ifc",abstract:!0,template:""},{name:"ifcFile.edit",url:"/edit/:guid",templateUrl:"app/ifc/views/editIfc.html",controller:"IfcEditController"},{name:"ifcFile.list",url:"/list/:menuGuid??filter",templateUrl:"app/ifc/views/listIfcFile.html",controller:"ListController",params:{entityData:apiData.ifcFile}},{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",url:"/list/:menuGuid??filter",templateUrl:"app/dataImport/views/listDataImport.html",controller:"ListController",params:{entityData:apiData.dataImport}},{name:"dataImport.create",url:"/edit",params:{menuGuid:"",guidEntityToCopy:""},templateUrl:"app/dataImport/views/editDataImport.html",controller:"DataImportController",excludeFromHistory:!0},{name:"dataImport.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/dataImport/views/editDataImport.html",controller:"DataImportController"},{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:"entityPermission",url:"/entityPermission",abstract:!0,template:""},{name:"entityPermission.list",url:"/list/:menuGuid??filter",templateUrl:"app/entityPermission/listEntityPermission.html",controller:"ListController",params:{entityData:apiData.entityPermissionProfile}},{name:"entityPermission.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/entityPermission/entityPermission.html",controller:"EntityPermissionController"},{name:"entityPermission.create",url:"/create",params:{menuGuid:""},templateUrl:"app/entityPermission/entityPermission.html",controller:"EntityPermissionController",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:"changelog",url:"/changelog",controller:"ChangelogController",templateUrl:"app/changelog/changelog.html"},{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:""},templateUrl:"app/projectCategory/views/editProjectCategory.html",controller:"ProjectCategoryController"},{name:"projectCategory.create",url:"/create",params:{menuGuid:""},templateUrl:"app/projectCategory/views/editProjectCategory.html",controller:"ProjectCategoryController",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:""},templateUrl:"app/activityCategory/views/editActivityCategory.html",controller:"ActivityCategoryController"},{name:"activityCategory.create",url:"/create",params:{menuGuid:""},templateUrl:"app/activityCategory/views/editActivityCategory.html",controller:"ActivityCategoryController",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:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"consequenceType.create",url:"/create",params:{menuGuid:""},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:"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",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",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",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:""},templateUrl:"app/contractCategory/views/editContractCategory.html",controller:"ContractCategoryController"},{name:"contractCategory.create",url:"/contractCategory",params:{menuGuid:""},templateUrl:"app/contractCategory/views/editContractCategory.html",controller:"ContractCategoryController",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:""},templateUrl:"app/customer/views/customer.html",controller:"CustomerController"},{name:"customer.create",url:"/create",params:{menuGuid:""},templateUrl:"app/customer/views/customer.html",controller:"CustomerController",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:""},templateUrl:"app/customer/views/housingCustomer.html",controller:"CustomerController"},{name:"housingCustomer.create",url:"/create",params:{menuGuid:""},templateUrl:"app/customer/views/housingCustomer.html",controller:"CustomerController",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",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/views/listNamedSelection.html",controller:"ListController",params:{entityData:apiData.namedSelection}},{name:"namedSelection.edit",url:"/edit/:guid",params:{menuGuid:""},templateUrl:"app/namedSelection/views/namedSelection.html",controller:"NamedSelectionController"},{name:"namedSelection.create",url:"/create",params:{menuGuid:""},templateUrl:"app/namedSelection/views/namedSelection.html",controller:"NamedSelectionController",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:"equipmentOperatingHours.dashboard",availableWebMenu:"Drifttimer dashbord",url:"/dashboard",templateUrl:"app/equipmentOperatingHours/views/equipmentOperatingHoursDashboard.html",controller:"EquipmentOperatingHoursDashboardController",params:{entityData:apiData.equipmentOperatingHours}},{name:"equipmentOperatingHourType",url:"/equipmentOperatingHourType",abstract:!0,template:""},{name:"equipmentOperatingHourType.list",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",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:""},templateUrl:"app/documentCategory/views/editDocumentCategory.html",controller:"SimpleGenericFormController"},{name:"documentCategory.create",url:"/create",params:{menuGuid:""},templateUrl:"app/documentCategory/views/editDocumentCategory.html",controller:"SimpleGenericFormController",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:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController"},{name:"customerCategory.create",url:"/create",params:{menuGuid:""},templateUrl:"app/common/views/simpleGenericForm.html",controller:"SimpleGenericFormController",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",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:""},templateUrl:"app/mobileMenuProfile/views/mobileMenuProfile.html",controller:"MobileMenuProfileController"},{name:"mobileMenuProfile.create",url:"/create",params:{menuGuid:""},templateUrl:"app/mobileMenuProfile/views/mobileMenuProfile.html",controller:"MobileMenuProfileController",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",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",excludeFromHistory:!0},{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.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:"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:"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:"changeSet",url:"/changeSet",abstract:!0,template:""},{name:"changeSet.list",availableWebMenu:"Endringssett",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"}}}]}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"}),console.log($scope.filters.GetLoggedInCleanerDrawing),"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"}),console.log($scope.filters.GetLoggedInCleanerCleaning),"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.updateSingleDictionary(repository.apiData.webMenu.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(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.createMultipleWithGuid(repository.apiData.webProfileWebMenu.url,$scope.model.Guid,JSON.stringify(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)};$scope.isUpdate?repository.getSingle(repository.apiData.account.url,$stateParams.guid).then(function(response){$scope.model=response.Data,$scope.reload=!0,updateAccess(),getCardTables()},function(error){repository.growl(error,"danger")}):($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:{},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:"Velg dimensjoner",columns:[{Title:translationService.translate("web-accountingDimension-id"),Property:"Id"}],useObjects:!0,url:repository.apiData.accounting.url,sorting:{Id:"asc"},filter:{},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.createMultipleWithGuid(repository.apiData.accountAccounting.url,$scope.model.Guid,arrayOfAccountXAccountingDimensions).then(function(result){repository.growl("Dimensjon(er) har blitt lagt til på kontoen","success"),$scope.accountXAccountingDimensionTable.reload()})})},$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.updateSingleDictionary(repository.apiData.account.url,$scope.model).then(success,error):repository.createSingleDictionary(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){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","Accounting1.Id","string").AddColumn("web-accounting-description","Beskrivelse","Accounting1.Description","string"),function(){modalParams.isLastDimension||($scope.accountingXAccountingDimensionTable=new ngTableParams({page:1,count:10,sorting:{},filter:{GuidParentAccounting:$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:"Velg dimensjoner",columns:[{Title:translationService.translate("web-accountingDimension-id"),Property:"Id"}],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.GuidAccounting)}),selectedGuids}()}}}}).result.then(function(selectedEntities){var arrayOfAccountingXAccountingDimensions=[];selectedEntities.forEach(function(entity){arrayOfAccountingXAccountingDimensions.push({GuidParentAccounting:$scope.model.Guid,GuidChildAccounting:entity.Guid})}),repository.createMultipleWithGuid(repository.apiData.accountingXAccounting.url,$scope.model.Guid,JSON.stringify(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.isUpdate=!!modalParams.dim,$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.updateSingleDictionary(repository.apiData.accounting.url,$scope.model).then(success,error):repository.createSingleDictionary(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(){angular.module("Plania").controller("ListAccountingController",["$scope","Repository","$state","TranslationService","$modal","ListService","config","$localStorage",function($scope,repository,$state,translationService,$modal,listService,config,$localStorage){$scope.selected={},$scope.selectedIndex=-1,$scope.showFilter=!1,$scope.showViewButton=!1,function(){$scope.restrictEdit=!repository.authService.hasCreateAccess($state.params.entityData.prefix)}();var getItems=function(){$scope.dimensions=[];var filter={},columns=[];columns.push("Id"),columns.push("Description"),columns.push("DimensionNumber"),columns.push("DataOwner.Dimension1"),columns.push("DataOwner.Dimension2"),columns.push("DataOwner.Dimension3"),columns.push("DataOwner.Dimension4"),columns.push("DataOwner.Dimension5");var page=0,pageSize=500;repository.GetPaginated($state.params.entityData.url,page,pageSize,{UpdatedDate:"desc"},filter,null,JSON.stringify(columns)).then(function(result){result.TotalCount,result.List.forEach(function(dimension){var existingDimension=_.find($scope.dimensions,function(dim){return dim.dimensionNumber===dimension.DimensionNumber});if(existingDimension)existingDimension.data.push(dimension);else{var data={dimensionNumber:dimension.DimensionNumber,data:[dimension]};$scope.dimensions.push(data)}}),$scope.dimensions=_.sortBy($scope.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){$modal.open({templateUrl:"app/accounting/views/editAccounting.html",controller:"AccountingModalController",resolve:{modalParams:function(){return{dim:dim,isLastDimension:!_.some($scope.dimensions,{dimensionNumber:dim.DimensionNumber+1})}}}}).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()})})}}])}(),function(){function controller($scope,repository,$stateParams,translationService,listService){$scope.isUpdate="activityCategory.edit"===$scope.navigation.current.name,$scope.model={Guid:$stateParams.guid},$scope.activateAutocomplete=!1,$scope.viewMode=!!$scope.isUpdate,$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.ActivityCategory,checkOtherDo),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ActivityCategory,checkOtherDo)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.ActivityCategory)};if(updateAccess(),$scope.isUpdate){var columns=[];repository.getSingle(repository.apiData.activityCategory.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"),$scope.activateAutocomplete=!0})}var updateSuccess=function(result,destination){repository.growl($scope.isUpdate?translationService.translate("update-activityCategory-success","Kategori har blitt oppdatert."):translationService.translate("create-activityCategory-success","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})},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.updateSingleDictionary(repository.apiData.activityCategory.url,$scope.model).then(success,updateError):repository.createSingleDictionary(repository.apiData.activityCategory.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-activityCategory-message","Kategori vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-activityCategory-button-confirm","Ja, fjern kategori"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.activityCategory.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-activityCategory-success","Kategori ble fjernet!"),result,"success"),$scope.goBack("activityCategory.list",{menuGuid:$scope.navigation.params.menuGuid})})})}}angular.module("Plania").controller("ActivityCategoryController",["$scope","Repository","$stateParams","TranslationService","ListService",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,$scope.model.EmailBody=decodeHtml($scope.model.EmailBody)},function(error){repository.growl(error,"danger")});var decodeHtml=function(html){var tmpElement=document.createElement("textarea");return tmpElement.innerHTML=html,tmpElement.value};$scope.getTrustedHtml=function(string){return string?$sce.trustAsHtml(string):""},$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.updateSingleDictionary(repository.apiData.apiClient.url,modelToSave).then(success).catch(error):repository.createSingleDictionary(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","User.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;i0;var checkOtherDataOwner=repository.commonService.getFilterData().selectedDataOwner.Guid!==$scope.model.GuidDataOwner;$scope.restrictEdit=!authService.hasEditAccess(repository.commonService.prefix.Area,checkOtherDataOwner),$scope.restrictDelete=!authService.hasDeleteAccess(repository.commonService.prefix.Area,checkOtherDataOwner),area.Building&&($scope.modelDto.building=area.Building.Caption),area.Drawing&&($scope.modelDto.drawing=area.Drawing.Caption),area.Person&&($scope.modelDto.cleaner=area.Person.Caption),area.CleaningQuality&&($scope.modelDto.cleaningQuality=area.CleaningQuality.Caption),area.ResourceGroup&&($scope.modelDto.cleaningTeam=area.ResourceGroup.Caption),$scope.reload=!0,$scope.reloads.deviations=!0,$scope.reloads.controlLists=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},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},function(error){repository.growl(error,"danger")})},building=repository.commonService.getFilterData().selectedBuilding;building.Guid&&($scope.modelDto.building=building.Name,$scope.model.GuidBuilding=building.Guid);var 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"Building":$scope.modelDto.building=prefill.Value.Label,$scope.model.GuidEstate=prefill.Value.Guid;break;case"AreaCategory":$scope.model.GuidAreaCategory=prefill.Value.Guid,$scope.model.AreaCategory={Guid:prefill.Value.Guid,Description:prefill.Value.Label,Caption:prefill.Value.Label};break;case"CleaningQuality":$scope.modelDto.cleaningQuality=prefill.Value.Label,$scope.model.GuidCleaningQuality=prefill.Value.Guid;break;case"ResourceGroup":$scope.modelDto.cleaningTeam=prefill.Value.Label,$scope.model.GuidCleaningTeam=prefill.Value.Guid;break;case"Person":$scope.modelDto.cleaner=prefill.Value.Label,$scope.model.GuidCleaner=prefill.Value.Guid}else"@CurrentBuilding"===prefill.Value?building.Guid&&($scope.modelDto.building=building.Name,$scope.model.GuidBuilding=building.Guid):$scope.model[prefill.Property]=prefill.Value}),$stateParams.showPersistantData){var persistentData=repository.persistedData.getPersistedData("area.create");persistentData&&($scope.model.GuidBuilding=persistentData.GuidBuilding,$scope.modelDto.building=persistentData.Building)}getCategoryPrefill(),$scope.activateAutocomplete=!0}$scope.updateArea=function(destination){$scope.model.ComputedGrossArea||($scope.model.ComputedGrossArea="0"),$scope.model.ComputedNetArea||($scope.model.ComputedNetArea="0"),$scope.model.ComputedGrossArea=$scope.model.ComputedGrossArea.replace(",","."),$scope.model.ComputedNetArea=$scope.model.ComputedNetArea.replace(",",".");var success=function(result){repository.growl($scope.update?"Rom har blitt oppdatert":"Rom har blitt lagret","success");var areaGuid=$scope.update?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,areaGuid),$scope.isModal&&"area.edit"===destination||("area.edit"===destination?$scope.navigation.go(destination,{guid:areaGuid},{reload:!0}):$scope.cancel())},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.update?repository.updateSingleDictionary(repository.apiData.area.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(repository.apiData.area.url,$scope.model).then(success).catch(error)},$scope.cancel=function(){$scope.isModal?$modalStack.dismissAll():$scope.goBack("area.list",{menuGuid:$scope.navigation.params.menuGuid})},$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.removeArea=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-area-message","Rommet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-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.area.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-area-success","Rommet ble fjernet!"),result,"success"),repository.growl("Rommet har blitt fjernet","success"),$scope.goBack("area.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.onBuildingSelect=function(building){if(!building)return void($scope.model.GuidBuilding="");$scope.model.GuidBuilding!==building.Guid&&($scope.model.GuidDrawing="",$scope.modelDto.drawing=null),$scope.model.Address=building.Address,$scope.model.GuidBuilding=building.Guid},$scope.onDrawingSelect=function(drawing){if(!drawing)return $scope.model.GuidDrawing="",void($scope.modelDto.drawing=null);$scope.model.GuidDrawing=drawing.Guid,$scope.model.GuidBuilding=drawing.GuidBuilding,$scope.modelDto.drawing=drawing.Caption},$scope.getProgressType=function(){return $scope.model.RealCapacity<=$scope.model.CalculatedCapacity?"success":"danger"},$scope.addCleaningTask=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,model=result.model,areaXCleaningTasks=[JSON.stringify({GuidCleaningTask:cleaningTask.Guid,RecurrenceRule:recurrenceRule,GuidArea:$scope.model.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){repository.growl(result),$scope.cleaningTaskTable.reload()},function(error){repository.growl(error,"danger")})},function(error){})},$scope.isPaused=function(task){var today=moment().startOf("day");return task.PausedFromDate&&task.PausedToDate&&today.isBetween(task.PausedFromDate,task.PausedToDate,"days","[]")},$scope.setCleaningPauseDate=function(task){$modal.open({templateUrl:"app/area/views/editAreaXCleaningTaskStartDateModal.html",controller:"AreaXCleaningTaskController",size:"md",resolve:{modalParams:function(){return{Guid:task.Guid,SuggestedPause:{From:new Date,To:(new Date).setDate((new Date).getDate()+1)}}}}}).result.then(function(result){repository.growl(result,"info"),$scope.cleaningTaskTable.reload()})},$scope.editCleaningTask=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,"info"),$scope.cleaningTaskTable.reload()})},$scope.removeCleaningTask=function(task){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([task.Guid])).then(function(result){swal(translationService.translate("web-swal-area-cleaningTask-success","Renholdsoppgaven ble fjernet!"),result,"success"),repository.growl("Renholdsoppgaven har blitt fjernet","success"),$scope.cleaningTaskTable.reload()})})},$scope.editComponent=function(component){$modal.open({templateUrl:"app/area/views/editComponentArea.html",controller:"AreaComponentController",resolve:{params:function(){return{component:component,AddComponents:!1}}}}).result.then(function(){$scope.componentTable.reload(),$scope.isComponentCollapsed=!1},function(){$scope.isComponentCollapsed=!1})},$scope.addComponents=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"}],useObjects:!1}}}}).result.then(function(guids){var model=[];guids.forEach(function(guid){model.push({GuidArea:$scope.model.Guid,GuidComponent:guid})}),repository.createMultipleWithGuid(repository.apiData.componentArea.url,$scope.model.Guid,JSON.stringify(model)).then(function(result){$scope.componentTable.reload()})},function(){})},$scope.removeComponent=function(component){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,component.Guid).then(function(result){swal(translationService.translate("web-swal-equipment-component-success","Komponenten ble fjernet!"),result,"success"),$scope.componentTable.reload()})})},$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})},$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(JSON.stringify({Guid:entity,GuidArea:$scope.model.Guid}))}),repository.patch(repository.apiData.person.url,null,changeList).then(function(result){repository.growl(translationService.translate("web-area-person-connection-success","Personene har blitt lagt til arealet"),"success"),$scope.reloads.persons=!$scope.reloads.persons},function(error){repository.growl(error,"danger")})}})}}angular.module("Plania").controller("AreaController",["$scope","Repository","$stateParams","ngTableParams","$modal","authService","$modalStack","TranslationService","ListService","EnumService","$state",controller])}(),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.updateSingleDictionary(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.updateSingleDictionary(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.unit,$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)},getAccountingLabels=function(guidDataOwner){repository.getSingle(repository.apiData.dataOwner.url,guidDataOwner).then(function(response){$scope.modelDto.dataOwner=response.Data},function(error){repository.growl(error,"danger")})};if($scope.isAccountingMandatory=function(accountingColumn){if(!$scope.modelDto||!$scope.modelDto.dataOwner)return!1;if("GuidDepartment"===accountingColumn)return $scope.modelDto.dataOwner.DepartmentCost;var lastDimensionCost=$scope.modelDto.dataOwner.LastDimensionCost;return!(!angular.isDefined(lastDimensionCost)||!accountingColumn.startsWith("GuidAccounting"))&&lastDimensionCost>=parseInt(accountingColumn.slice(-1))},$scope.onGetValidityRules=function(originalValidityRules){if(!$scope.isAccountingMandatory(originalValidityRules.DomainFieldName))return originalValidityRules;var validityRules=_.clone(originalValidityRules);return validityRules.Mandatory=!0,validityRules},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"accounting0":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:0,Operator:"="}],filter;case"accounting1":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:1,Operator:"="}],filter;case"accounting2":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:2,Operator:"="}],filter;case"accounting3":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:3,Operator:"="}],filter;case"accounting4":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:4,Operator:"="}],filter}},$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,$scope.model.Account&&($scope.modelDto.accountCaption=$scope.getEntityCaption($scope.model.Account)),$scope.model.CostCenter&&($scope.modelDto.costCenterCaption=$scope.getEntityCaption($scope.model.CostCenter)),$scope.model.Department&&($scope.modelDto.departmentCaption=$scope.getEntityCaption($scope.model.Department)),$scope.model.Accounting0&&($scope.modelDto.accounting0Caption=$scope.getEntityCaption($scope.model.Accounting0)),$scope.model.Accounting1&&($scope.modelDto.accounting1Caption=$scope.getEntityCaption($scope.model.Accounting1)),$scope.model.Accounting2&&($scope.modelDto.accounting2Caption=$scope.getEntityCaption($scope.model.Accounting2)),$scope.model.Accounting3&&($scope.modelDto.accounting3Caption=$scope.getEntityCaption($scope.model.Accounting3)),$scope.model.Accounting4&&($scope.modelDto.accounting4Caption=$scope.getEntityCaption($scope.model.Accounting4)),updateAccess(),getAccountingLabels($scope.model.GuidDataOwner)},function(error){repository.growl(error,"danger")})}else{var article=$scope.model;article.PriceAdjustmentType="Undefined",article.Type="Undefined",getAccountingLabels(repository.commonService.getFilterData().selectedDataOwner.Guid)}$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.updateSingleDictionary(repository.apiData.article.url,$scope.model).then(success,error)):repository.createSingleDictionary(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.isUpdate||getAccountingLabels(repository.commonService.getFilterData().selectedDataOwner.Guid)}),$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,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)},getAccountingLabels=function(guidDataOwner){repository.getSingle(repository.apiData.dataOwner.url,guidDataOwner).then(function(response){$scope.modelDto.dataOwner=response.Data},function(error){repository.growl(error,"danger")})};$scope.isAccountingMandatory=function(accountingColumn){if(!$scope.modelDto.dataOwner)return!1;if("GuidDepartment"===accountingColumn)return $scope.modelDto.dataOwner.DepartmentCost;var LastDimensionBudget=$scope.modelDto.dataOwner.LastDimensionBudget;return!(!angular.isDefined(LastDimensionBudget)||!accountingColumn.startsWith("GuidAccounting"))&&LastDimensionBudget>=parseInt(accountingColumn.slice(-1))},$scope.onGetValidityRules=function(originalValidityRules){if(!$scope.isAccountingMandatory(originalValidityRules.DomainFieldName))return originalValidityRules;var validityRules=_.clone(originalValidityRules);return validityRules.Mandatory=!0,validityRules};var setProperties=function(){$scope.model.Service&&($scope.service=$scope.getEntityCaption($scope.model.Service)),$scope.model.Account&&($scope.modelDto.accountCaption=$scope.getEntityCaption($scope.model.Account)),$scope.model.CostCenter&&($scope.modelDto.costCenterCaption=$scope.getEntityCaption($scope.model.CostCenter)),$scope.model.Department&&($scope.modelDto.departmentCaption=$scope.getEntityCaption($scope.model.Department)),$scope.model.Accounting0&&($scope.modelDto.accounting0Caption=$scope.getEntityCaption($scope.model.Accounting0)),$scope.model.Accounting1&&($scope.modelDto.accounting1Caption=$scope.getEntityCaption($scope.model.Accounting1)),$scope.model.Accounting2&&($scope.modelDto.accounting2Caption=$scope.getEntityCaption($scope.model.Accounting2)),$scope.model.Accounting3&&($scope.modelDto.accounting3Caption=$scope.getEntityCaption($scope.model.Accounting3)),$scope.model.Accounting4&&($scope.modelDto.accounting4Caption=$scope.getEntityCaption($scope.model.Accounting4))},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(),getAccountingLabels($scope.model.GuidDataOwner)},function(error){repository.growl(error,"danger"),"Ingen data funnet"===error&&($scope.notFoundError=!0)}):($scope.model.Year=moment().year(),getAccountingLabels(repository.commonService.getFilterData().selectedDataOwner.Guid)),$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={PropertyFilter:[{Operand:"AND",Property:"GuidBudget",Operator:"=",Value:$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:{PropertyFilter:[{Operand:"AND",Property:"GuidBudget",Operator:"=",Value:$scope.model.Guid},{Operand:"AND",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={PropertyFilter:[{Operand:"AND",Property:"GuidBudget",Operator:"=",Value:$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.updateSingleDictionary(repository.apiData.budget.url,$scope.model).then(success,error):repository.createSingleDictionary(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.$on($scope.events.newSelection,function(){$scope.isUpdate||getAccountingLabels(repository.commonService.getFilterData().selectedDataOwner.Guid)}),$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"service":return filter.PropertyFilter=[{Property:"IsBudgetable",Operator:"=",Value:"1"}],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,ngTableParams,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};var availableHashLocations=["#info","#area","#equipment","#maintenance"],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","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","Person.Guid","Person.FirstName","Person.LastName","User.RealName","User1.RealName"];repository.getMainModel(repository.apiData.building.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.reload=!0,$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.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.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.updateSingleDictionary(repository.apiData.building.url,$scope.model).then(success).catch(error)):($scope.model.BuildingXBuildingSelection=[{GuidBuildingSelection:repository.commonService.getFilterData().selectedSelection.Guid}],repository.createSingleDictionary(repository.apiData.building.url,$scope.model).then(success,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","ngTableParams","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="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.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,ngTableParams,repository,translationService,$modal,$rootScope,listService,$timeout,registeredFieldService){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.imageApiUrl=$rootScope.imageApiUrl,$scope.userInfo=$rootScope.userInfo,$scope.customization=$rootScope.customization,$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.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$scope.getPropertyValue=function(building,column){return listService.GetPropertyValue(building,column)},$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.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.onFileSelect=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,GuidBuilding:$scope.model.Guid};files.push(newFile),onLoadEndHandler()},reader.readAsDataURL(file)}function onLoadEndHandler(image){$scope.model.GuidBuildingImage&&repository.deleteSingle(repository.apiData.image.url,$scope.model.GuidBuildingImage).then(function(result){console.log(result)}),repository.createMultiple(repository.apiData.image.url,files).then(function(result){$scope.model.GuidBuildingImage=result[0].Guid},function(error){repository.growl(error)})}if(images&&0!==images.length){var files=[];handleFileUpload(images[0])}},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"person":return filter.PropertyFilter=[{Property:"IsOperationsManager",Operator:"=",Value:!0}],filter;case"referenceData":return filter.PropertyFilter=[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null,Operand:"OR"},{Property:"ReferenceType.Context",Operator:"=",Value:1}],filter}},$scope.supplierInfo=new function(){var me=this;this.showSupplierLineOfBusiness=!1,this.columns=[{Position:1,Title:translationService.translate("web-supplier-id"),Property:"Supplier.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-supplier-description"),Property:"Supplier.Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-supplier-supplierLineOfBusiness","Bransje"),Property:"Supplier.SupplierLineOfBusiness.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-supplier-address1"),Property:"Supplier.Address1",PropertyType:"string"},{Position:5,Title:translationService.translate("web-supplier-postalcode"),Property:"Supplier.PostalCode",PropertyType:"string"},{Position:6,Title:translationService.translate("web-supplier-postalarea"),Property:"Supplier.PostalArea",PropertyType:"string"},{Position:7,Title:translationService.translate("web-supplier-email"),Property:"Supplier.Email",PropertyType:"string"}],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.Guid"),columns.push("Supplier.GuidSupplierLineOfBusiness"),repository.GetPaginated(repository.apiData.buildingSupplier.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/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.createMultipleWithGuid(repository.apiData.buildingSupplier.url,$scope.model.Guid,JSON.stringify(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","Leverandøren vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-building-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.buildingSupplier.url,supplier.Guid).then(function(result){swal(translationService.translate("web-swal-building-supplier-success","Leverandøren ble fjernet!"),result,"success"),repository.growl("Personen har blitt fjernet","success"),me.table.reload()})})},this.canEdit=function(workOrderXSparePart){return workOrderXSparePart&&$scope.hasEditAccess("WorkOrderXSparePart")},this.canDelete=function(workOrderXSparePart){return workOrderXSparePart&&$scope.hasDeleteAccess("WorkOrderXSparePart")},this.initTable(),this.initRegisteredFields()},$scope.buildingPersonInfo=new function(){var me=this;this.isLoading=!1,this.columns=[{Position:1,Title:translationService.translate("web-person-employeenr"),Property:"Person.EmployeeNr",PropertyType:"string"},{Position:2,Title:translationService.translate("web-person-firstname"),Property:"Person.FirstName",PropertyType:"string"},{Position:3,Title:translationService.translate("web-person-lastname"),Property:"Person.LastName",PropertyType:"string"},{Position:4,Title:translationService.translate("web-person-position"),Property:"Person.Position",PropertyType:"string"},{Position:5,Title:translationService.translate("web-resourcegroup-id"),Property:"Person.ResourceGroup.Id",PropertyType:"autocomplete", AutocompleteProperty:"GuidResourceGroup",AutocompleteService:"resourceGroup"},{Position:6,Title:translationService.translate("web-person-telephoneWork"),Property:"Person.TelephoneWork",PropertyType:"string"},{Position:7,Title:translationService.translate("web-person-cellphone"),Property:"Person.Cellphone",PropertyType:"string"},{Position:8,Title:translationService.translate("web-person-email"),Property:"Person.Email",PropertyType:"string"},{Position:9,Title:translationService.translate("web-personrole-id"),Property:"PersonRole.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidPersonRole",AutocompleteService:"personRole"}],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.Guid"),this.isLoading=!0,repository.GetPaginated(repository.apiData.buildingPerson.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.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(),$scope.isPersonCollapsed=!1},function(){$scope.isPersonCollapsed=!1})},this.remove=function(buildingXPerson){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-building-person-message","Personen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-building-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.buildingPerson.url,buildingXPerson.Guid).then(function(result){swal("Suksess!",translationService.translate("web-swal-building-person-success","Personen ble fjernet!"),"success"),repository.growl("Personen har blitt fjernet","success"),me.table.reload()})})},this.canEdit=function(workOrderXSparePart){return workOrderXSparePart&&$scope.hasEditAccess("WorkOrderXSparePart")},this.canDelete=function(workOrderXSparePart){return workOrderXSparePart&&$scope.hasDeleteAccess("WorkOrderXSparePart")},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.openBuildingTypeInfoModal=function(){$scope.model.GuidBuildingType&&$modal.open({templateUrl:"app/referenceData/views/referenceDataInfoModal.html",controller:"ReferenceDataInfoModalController",resolve:{modalParams:function(){return{guid:$scope.model.GuidBuildingType,initialModel:$scope.model.BuildingType}}},size:"lg"})}}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",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,ngTableParams,$filter){var filter={};params.excludeGuids&¶ms.excludeGuids.length>0&&(filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:params.excludeGuids.join(",")}]),$scope.supplierTable=new ngTableParams({page:1,count:10,sorting:{description:"asc"},filter:filter},{total:0,counts:[10,25,50],getData:function($defer,params){repository.GetPaginated(repository.apiData.supplier.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)},function(error){repository.growl(error,"danger")})}});var selectedSuppliers=[];$scope.saveSupplier=function(){repository.createMultipleWithGuid(repository.apiData.buildingSupplier.url,params.guidBuilding,selectedSuppliers).then(function(result){repository.growl("Leverandør har blitt lagt til bygg","success"),$modalInstance.close("OK")})},$scope.addSupplier=function(guid){if(_.contains(selectedSuppliers,guid))for(var i=0;i0&&(filter={PropertyFilter:[{Property:"Guid",Operator:"notin",Value:selected.join(",")}]}),params.isOperationsManager&&(filter.PropertyFilter?filter.PropertyFilter.push({Property:"IsOperationsManager",Operator:"=",Value:!0}):filter={PropertyFilter:[{Property:"IsOperationsManager",Operator:"=",Value:!0}]}),$scope.entities=new ngTableParams({page:1,count:10,sorting:$scope.isAddingBuilding?{id:"asc"}:{employee_nr:"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.updateSingleDictionary(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.createMultipleWithGuid(repository.apiData.buildingPerson.url,"ListOfModels",JSON.stringify(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
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"}]}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}}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,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.createMultipleWithGuid(repository.apiData.resourceGroupCause.url,$scope.model.Guid,JSON.stringify(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.updateSingleDictionary(repository.apiData.cause.url,$scope.model).then(success,error):repository.createSingleDictionary(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,20),$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={PropertyFilter:[{Property:"EntityType",Operator:"=",Value:$scope.entityType},{Property:"GuidEntity",Operator:"=",Value:$scope.guidEntity}]};"all"!==$scope.currentSelectedFilterType.value&&changeSetFilter.PropertyFilter.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){$scope.newestVersionIsExpanded=!0}angular.module("Plania").controller("ChangelogController",["$scope",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:"IS_ADDITIONAL_TASK",Operator:"=",Value:"1"}]};case"person":return{PropertyFilter:[{Property:"DOES_CLEANING_TASKS",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(JSON.stringify({Guid:taskGuid,DelayedDate:(new Date).toISOString()}))}),$scope.isRunningAction=!0,repository.patch(repository.apiData.areaXCleaningTask.url,null,changeList).then(function(result){$scope.isRunningAction=!1,repository.growl(translationService.translate("web-cleaningTask-delayedTask","Rengjøring utsatt"),"success"),$scope.ok("delayed")},function(error){$scope.isRunningAction=!1,repository.growl(error,"danger")})},$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(JSON.stringify(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(JSON.stringify(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"},{GuidCleaningTask: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(){var area=[JSON.stringify({Guid:$scope.area.Guid,CleaningComment:$scope.area.CleaningComment})];repository.createMultiple(repository.apiData.massUpdate.url,area,"Prefix="+repository.apiData.area.prefix).then(function(result){getData($scope.area.Guid)})},$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,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.createSingleDictionary(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(JSON.stringify(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(JSON.stringify(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.updateSingleDictionary(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,[JSON.stringify(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:"DOES_CLEANING_TASKS",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(JSON.stringify(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(JSON.stringify({Guid:taskGuid,DelayedDate:(new Date).toISOString()}))}),$scope.isRunningAction=!0,repository.patch(repository.apiData.areaXCleaningTask.url,null,changeList).then(function(result){$scope.isRunningAction=!1,repository.growl(translationService.translate("web-cleaningTask-delayedTask","Rengjøring utsatt"),"success"),$scope.ok("delayed")},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()||!(!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(","),Operand:"AND"},{Property:"CleaningTask.CleaningType",Operator:"<>",Value:"1",Operand:"AND"},{Property:"CleaningTask.CleaningType",Operator:"<>",Value:"3",Operand:"AND"}]},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(JSON.stringify(change))}),repository.patch(repository.apiData.areaXCleaningTask.url,null,changeList).then(function(result){repository.growl(translationService.translate("web-cleaningTask-multipleOnHold-updateSuccess","Oppgaver oppdatert"),"success"),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(JSON.stringify(change))}),repository.patch(repository.apiData.areaXCleaningTask.url,null,changeList).then(function(result){repository.growl(translationService.translate("web-cleaningTask-multipleOnHold-updateSuccess","Oppgaver oppdatert"),"success"),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(JSON.stringify(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)?"zmdi-alert-circle c-red":$scope.hasWarnings(areaXCleaningTask)?"zmdi-alert-triangle c-orange":"zmdi-check-circle c-green"},$scope.hasMissingProperties=function(task){var mandatoryFields=task.AttributeValues.filter(function(attr){return"Mandatory"===attr.ValidityRule});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){$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","Person1.FirstName","Person1.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.Person1?request.Person1.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(){$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.createSingleDictionary(repository.apiData.request.url,$scope.request).then(function(result){repository.growl("Meldingen ble sendt","success"),$scope.request={},$scope.selectedRequest={},$scope.autoCompleteModel.responsible="",$scope.autoCompleteModel.activityCategory="",$scope.autoCompleteModel.priority="",$scope.ok(result)},function(error){repository.growl(error,"danger")})}}angular.module("Plania").controller("TechnicalRequestController",["$scope","Repository","EnumService","RegisteredFieldService","Constants",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","User1.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.updateSingleDictionary(repository.apiData.cleaningQuality.url,$scope.model).then(success,error):repository.createSingleDictionary(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(JSON.stringify({Guid:guid,GuidCleaningQuality:$scope.model.Guid}))}),repository.createMultiple(repository.apiData.massUpdate.url,areas,"Prefix="+repository.apiData.area.prefix).then(function(result){repository.growl("Rommene har blitt lagt til","success"),$scope.areaTable.reload()})},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;var areas=[JSON.stringify({Guid:area.Guid,GuidCleaningQuality:null})];repository.createMultiple(repository.apiData.massUpdate.url,areas,"Prefix="+repository.apiData.area.prefix).then(function(result){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-cleaningQualityControl-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-cleaningQualityControl-button-confirm","Ja, fjern rommet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null;var postModel={Guid:$scope.model.Guid};repository.updateSingleDictionary(repository.apiData.cleaningQualityControlArea.url+"/SetNotAvailable/",postModel).then(function(result){repository.growl(result,"success"),$modalInstance.close("ok")},function(result){ repository.growl(result,"danger")})},function(error){repository.growl(error,"danger")})},$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.updateSingleDictionary(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.updateSingleDictionary(repository.apiData.cleaningQualityControl.url,$scope.model).then(success,error)):repository.createSingleDictionary(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-message","Kontrollen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-cleaningQualityControl-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(JSON.stringify({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){("Recurrence"!==col.Property||showRecurrence)&&columns.push(col)}),$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&&repository.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;var data={guid:$scope.model.Guid,id:$scope.model.Id,explanatoryText:$scope.model.ExplanatoryText,recurrence:$scope.model.Recurrence,recurrenceRule:$scope.model.RecurrenceRule,estimatedTime:$scope.model.EstimatedTime,estimatedCost:$scope.model.EstimatedCost,isTemplate:$scope.model.IsTemplate};persistentDataService.setPersistedData("cleaningTask.create",data),$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.updateSingleDictionary(repository.apiData.cleaningTask.url,toSave).then(success,error):repository.createSingleDictionary(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.Guid=persistentData.guid,$scope.model.Id=persistentData.id,$scope.model.ExplanatoryText=persistentData.explanatoryText,$scope.model.Recurrence=persistentData.recurrence,$scope.model.RecurrenceRule=persistentData.recurrenceRule,$scope.model.EstimatedCost=persistentData.estimatedCost,$scope.model.EstimatedTime=persistentData.estimatedTime,$scope.model.IsTemplate=persistentData.isTemplate)}$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.updateSingleDictionary(repository.apiData.cleaningTask.url,toSave).then(success,error):repository.createSingleDictionary(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,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.RecurrenceRule&&$scope.model.RecurrenceRule.StartDate&&($scope.model.StartDate=$scope.model.RecurrenceRule.StartDate),$scope.model.RecurrenceRule&&$scope.model.RecurrenceRule.Until&&($scope.model.UntilDate=$scope.model.RecurrenceRule.Until),$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,object.RecurrenceRule&&object.RecurrenceRule.StartDate?$scope.model.StartDate=new Date(object.RecurrenceRule.StartDate):$scope.model.StartDate=new Date,object.RecurrenceRule&&object.RecurrenceRule.Until&&($scope.model.UntilDate=new Date(object.RecurrenceRule.Until)),$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(){angular.module("Plania").controller("SelectedDataOwnerController",["$scope","$rootScope","Repository",function($scope,$rootScope,repository){$scope.count=10,$scope.totalCount=0,$scope.dataOwners=[],$scope.selectedDataOwner=repository.commonService.getFilterData().selectedDataOwner,$scope.filter={includeAllDataOwners:"false"};var columns=["Id","Description","Dimension1","DocumentType.Id","DocumentCategory1.Description"];$scope.getDataOwners=function(){repository.GetPaginated(repository.apiData.dataOwner.url,0,$scope.count,{id:"asc"},$scope.filter,$scope.selectedDataOwner.Guid,JSON.stringify(columns)).then(function(result){$scope.dataOwners=result.List,$scope.totalCount=result.TotalCount;var storedDataOwner=repository.commonService.getFilterData().selectedDataOwner,broadcastChange=storedDataOwner.Guid!==$scope.selectedDataOwner.Guid;""===storedDataOwner.Guid||$scope.filter.Dropdown||($scope.selectedDataOwner=_.filter($scope.dataOwners,{Guid:storedDataOwner.Guid})[0],repository.commonService.setDataOwner($scope.selectedDataOwner),broadcastChange&&$rootScope.$broadcast($rootScope.events.updateMenu,!0))},function(error){repository.growl(error,"danger")})},$scope.getDataOwners(),$scope.addMoreData=function(){$scope.count+=100,$scope.getDataOwners()},$scope.changeDataOwner=function(owner){owner.Guid!==$scope.selectedDataOwner.Guid&&(repository.commonService.setDataOwner(owner),repository.commonService.setEmptyBuilding(),repository.authService.hasReadAccess(repository.commonService.prefix.BuildingSelection)&&repository.commonService.setEmptySelection(),$rootScope.$broadcast($rootScope.events.updateMenu,!0),$rootScope.$broadcast($rootScope.events.newSelection,!0))},$scope.$on($scope.events.newSelection,function(){$scope.selectedDataOwner=repository.commonService.getFilterData().selectedDataOwner,$scope.getDataOwners()})}])}(),function(){function controller($scope,$rootScope,repository,commonService){$scope.count=30,$scope.totalCount=0,$scope.buildings=[],$scope.selectedBuilding=commonService.getFilterData().selectedBuilding,$scope.filter={excludeBuilding:!0,PropertyFilter:[{Property:"IsTemplate",Operator:"=",Value:!1}]};var columns=["Id","Description","Estate.Guid","Estate.Id","Estate.Description"];$scope.getBuildings=function(setBuilding){repository.GetPaginated(repository.apiData.building.url,0,$scope.count,{id:"asc"},$scope.filter,null,JSON.stringify(columns)).then(function(result){if(result&&result.List&&($scope.totalCount=result.TotalCount,$scope.buildings=result.List,1===result.List.length&&setBuilding)){var building=result.List[0];commonService.setBuilding(building),$scope.selectedBuilding={Guid:building.Guid,Name:building.Caption}}},function(error){repository.growl(error,"danger")})},$scope.getBuildings(),$scope.addMoreData=function(){$scope.count+=100,$scope.getBuildings()},$scope.changeBuilding=function(selected){selected.Guid!==$scope.selectedBuilding.Guid&&(commonService.setBuilding(selected),$rootScope.$broadcast($rootScope.events.newSelection,!0))},$scope.setEmptyBuilding=function(){$scope.filter.dropdown="",$scope.selectedBuilding.Guid&&(commonService.setEmptyBuilding(),$rootScope.$broadcast($rootScope.events.newSelection,!1))},$scope.$on($scope.events.newSelection,function(event,reloadBuildings,fromEstate){$scope.selectedBuilding=commonService.getFilterData().selectedBuilding,""===$scope.selectedBuilding.Guid&&reloadBuildings&&$scope.getBuildings(!fromEstate)})}angular.module("Plania").controller("ActiveBuildingController",["$scope","$rootScope","Repository","CommonService",controller])}(),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.createSingleDictionary(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:{},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.ValidityRule=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.createSingleDictionary(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"},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"}})}(),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","ValidityRule"],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){console.log(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 1==(1&item.ValidityRule)},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.updateSingleDictionary(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.LanguageXWebText,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.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}},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"zmdi-inbox c-blue";case"Sent":return"zmdi-mail-send c-green";default:return"zmdi-close-circle 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"}})}(),angular.module("Plania").directive("calendarWidget",function($compile,Repository,$timeout,TranslationService,$rootScope){return{restrict:"A",scope:{select:"&",control:"=",edit:"=",eventSource:"=",viewType:"=",editFunction:"=",removeFunction:"="},link:function(scope,element){scope.internalControl=scope.control||{};var toolbarHeight=75,calendarHeight=360;scope.showActive=!0,scope.actionLinks='";var setHeight=function(height){calendarHeight=height,element.fullCalendar("option","height",calendarHeight),element.fullCalendar("option","contentHeight",calendarHeight-toolbarHeight)},date=new Date,d=date.getDate(),m=date.getMonth(),y=date.getFullYear(),columns=["StartDate","DueDate","EndDate","Estate.Id","Estate.Description","Building.Id","Building.Description","Equipment.Id","Equipment.Description","Description","Id"],setPreviousColour=function(startDate){element.find(".fc-prev-button").css("color","#fff");var workOrderFilter={showActive:scope.showActive,PropertyFilter:[]},guidPerson=$rootScope.userInfo.guidPerson,guidPersonResourceGroup=$rootScope.userInfo.guidPersonResourceGroup,startDateStr=startDate.toISOString();guidPerson&&(workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"GUID_RESPONSIBLE_PERSON",Operator:"=",Value:guidPerson}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:"<=",Value:startDateStr}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"EndDate",Operator:"=",Value:""}),workOrderFilter.PropertyFilter.push({Operand:"OR",Property:"RESOURCE_GROUP.People.GUID",Operator:"=",Value:guidPerson}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:"<=",Value:startDateStr}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"EndDate",Operator:"=",Value:""}),workOrderFilter.PropertyFilter.push({Operand:"OR",Property:"WORK_ORDER_X_RESOURCE_GROUP.GUID_PERSON",Operator:"=",Value:guidPerson}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:"<=",Value:startDateStr}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"EndDate",Operator:"=",Value:""})),guidPersonResourceGroup&&(workOrderFilter.PropertyFilter.push({Operand:"OR",Property:"WORK_ORDER_X_RESOURCE_GROUP.GUID_RESOURCE_GROUP",Operator:"=",Value:guidPersonResourceGroup}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:"<=",Value:startDateStr}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"EndDate",Operator:"=",Value:""})),workOrderFilter.PropertyFilter.length&&Repository.GetPaginated(Repository.apiData.workOrder.url,0,1,{StartDate:"desc"},workOrderFilter,null,JSON.stringify(columns)).then(function(result){result.TotalCount>0&&element.find(".fc-prev-button").css("color","#f44336")})},language=TranslationService.getLocale();language&&"nb-no"!==language||(language="nb"),element.fullCalendar({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){setPreviousColour(new Date(start));var startDate=new Date(start),endDate=new Date(end);startDate.setMonth(startDate.getMonth()-1);var workOrderFilter={showActive:scope.showActive,PropertyFilter:[]},guidPerson=$rootScope.userInfo.guidPerson,guidPersonResourceGroup=$rootScope.userInfo.guidPersonResourceGroup,startDateStr=startDate.toISOString(),endDateStr=endDate.toISOString();guidPerson&&(workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"GUID_RESPONSIBLE_PERSON",Operator:"=",Value:guidPerson}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:">=",Value:startDateStr}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:"<=",Value:endDateStr}),workOrderFilter.PropertyFilter.push({Operand:"OR",Property:"RESOURCE_GROUP.People.GUID",Operator:"=",Value:guidPerson}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:">=",Value:startDateStr}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:"<=",Value:endDateStr}),workOrderFilter.PropertyFilter.push({Operand:"OR",Property:"WORK_ORDER_X_RESOURCE_GROUP.GUID_PERSON",Operator:"=",Value:guidPerson}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:">=",Value:startDateStr}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:"<=",Value:endDateStr})),guidPersonResourceGroup&&(workOrderFilter.PropertyFilter.push({Operand:"OR",Property:"WORK_ORDER_X_RESOURCE_GROUP.GUID_RESOURCE_GROUP",Operator:"=",Value:guidPersonResourceGroup}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:">=",Value:startDateStr}),workOrderFilter.PropertyFilter.push({Operand:"AND",Property:"StartDate",Operator:"<=",Value:endDateStr})),workOrderFilter.PropertyFilter.length&&Repository.GetPaginated(Repository.apiData.workOrder.url,0,-1,{StartDate:"desc"},workOrderFilter,null,JSON.stringify(columns)).then(function(result){var events=[];result.List.forEach(function(item){var eventColor="bgm-blue";if(item.EndDate&&(eventColor="bgm-green"),!item.EndDate&&new Date(item.StartDate)
'+event.titleLabel+" "+event.title+"
";if(event.data.Equipment&&(content=content+'
'+TranslationService.translate("web-calendar-equipment","Anlegg:")+" "+event.data.Equipment.Id+" - "+event.data.Equipment.Description+"
"),event.data.EstimatedTime&&(content=content+'
'+TranslationService.translate("web-calendar-estimatedTime","Estimert tid:")+" "+event.data.EstimatedTime+"
"),event.data.DueDate){var date=new Date(event.data.DueDate),formattedDate=("0"+date.getDate()).slice(-2)+"."+("0"+(date.getMonth()+1)).slice(-2)+"."+date.getFullYear();content=content+'
'+TranslationService.translate("web-calendar-calculatedEndDate","Antatt sluttdato:")+" "+formattedDate+"
"}$(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"),scope.$root.navigation.go("workOrder.edit",{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.$watch("showActive",function(newValue,oldValue){newValue!==oldValue&&element.fullCalendar("refetchEvents")}),$rootScope.$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.$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){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(),params.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(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}),"zmdi-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",createEntity:"=createEntity",disableAdd:"=disableAdd",totalCount:"=totalCount",addEntity:"=addEntity",reloadTable:"=reloadTable",useContextMenu:"=useContextMenu",contextMenuOptions:"=contextMenuOptions"},controller:["$scope","Repository","TranslationService","NgTableParams","ListService","$rootScope",controller],templateUrl:"app/common/directives/views/childEntities.html"}})}(),function(){function controller($scope,$modal,ngTableParams,repository,translationService,documentService,$rootScope,$window){$scope.documentsIsLoading=!0,$scope.search={},$scope.enableWebNavigation=repository.enableWebNavigation,$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",$scope.sortingProperties=[{value:"Document.Description",label:translationService.translate("web-document-description","Beskrivelse")},{value:"Document.DocumentCategory.Description",label:"Kategori"},{value:"Document.DocumentType.Id",label:"Type"},{value:"Document.Supplier.Description",label:"Leverandør"}],$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"}],$rootScope.hasModule("DataAcquisition")&&$scope.columns.push({Position:7,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","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=repository.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 postModel=angular.copy(document);postModel.RequestAction="setDataAcquisitionStatus",postModel.RequestActionParameter1=status;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.updateSingleDictionary(repository.apiData.documentXEntity.url,postModel).then(success,updateError)})},$scope.setArchiveStatus=function(documentXEntity,archiveStatus){var properties={ArchiveStatus:archiveStatus};repository.patch(repository.apiData.documentXEntity.url,documentXEntity.Guid,JSON.stringify(properties)).then(function(result){$scope.documentTable.reload(),repository.growl("Arkivstatus oppdatert","success")},function(error){repository.growl(error,"danger")})},$scope.openDocumentInArchiveSystem=function(xRef){$window.open(xRef.JournalId,"_blank")}}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",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,repository){$scope.isExternalUser=$localStorage.userData.isExternalUser,$scope.isCollapsed=$localStorage.dynamicPropertiesIsCollapsed;$scope.$parent&&$scope.$parent.isUpdate;$scope.toggleCollapsed=function(){$scope.isCollapsed=!$scope.isCollapsed,$localStorage.dynamicPropertiesIsCollapsed=$scope.isCollapsed};var reinitDynamicFieldDefaultValues=function(){$scope.model&&$scope.model.DynamicProperty&&$scope.model.DynamicProperty.Groups.forEach(function(group){group.Items.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.$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()))):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()},function(){ $scope.model[$scope.guidProperty]=oldPropertyValue,$scope.autoCompleteProperty=oldAutoCompleteValue}):(oldPropertyValue=newValue,oldAutoCompleteValue=$scope.autoCompleteProperty,$scope.model.DynamicProperty=$scope.newDynamicProperty,reinitDynamicFieldDefaultValues()))})}angular.module("Plania").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","Repository",controller],templateUrl:"app/common/directives/dynamicProperty/dynamicPropertyDirective.html"}})}(),function(){angular.module("Plania").directive("plCategoryGrid",[function(){return{restrict:"E",scope:{dynamicProperty:"=dynamicProperty",isAbstract:"=isAbstract"},templateUrl:"app/common/directives/dynamicProperty/plCategoryGrid.html",controller:["$scope","$element","TranslationService","$modal","Repository","Constants","$timeout",controller]}}]);var controller=function($scope,$element,translationService,$modal,repository,constants,$timeout){$scope.grid={};var projectNumbers=constants.dynamicProperties.projectCategory;$scope.numberOfFields={Text:[],Numeric:[],Date:[],Combo:[]};for(var i=0;i-1},$scope.setNumberedFieldsAvailability=function(newValue,oldValue,propertyType){var oldItem=_.find($scope.numberOfFields[propertyType],function(n){return n.number===oldValue});oldItem&&(oldItem.isAvailable=!0);var newItem=_.find($scope.numberOfFields[propertyType],function(n){return n.number===newValue});newItem&&(newItem.isAvailable=!1)},$scope.fieldTypeItems=[{Guid:null,Name:translationService.translate("web-enum-dynamicProperty-Text","Text"),Type:"Text",icon:"text-format",LabelValue:"Feltnavn"},{Guid:null,Name:translationService.translate("web-enum-dynamicProperty-Numeric","Nummer"),Type:"Numeric",icon:"collection-item-1",LabelValue:"Feltnavn"},{Guid:null,Name:translationService.translate("web-enum-dynamicProperty-Date","Dato"),Type:"Date",icon:"calendar",LabelValue:"Feltnavn"},{Guid:null,Name:translationService.translate("web-enum-dynamicProperty-Combo","Nedtrekksfelt"),Type:"Combo",icon:"caret-down-circle",LabelValue:"Feltnavn"}],$scope.selectedGroup={},$scope.selectedProperty={},$timeout(function(){$(".grid-stack").on("change",function(e,nodes){for(var i=$scope.dynamicProperty.Groups.length-1;i>=0;i--)for(var group=$scope.dynamicProperty.Groups[i],j=group.Items.length-1;j>=0;j--){var property=group.Items[j],node=_.find(nodes,{id:property.Guid});node&&(property.WebLayout.Height=node.height,property.WebLayout.Width=node.width,property.WebLayout.PointY=node.y,property.WebLayout.PointX=node.x)}})},500);var isAvailable=function(property,gridId,x,y){return!$scope.grid[gridId]||!_.find($scope.grid[gridId].grid.nodes,function(b){var a={x:x,y:y,width:property.WebLayout.Width,height:property.WebLayout.Height};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.selectGroup=function(group){$scope.selectedGroup=group,$scope.selectedProperty=null},$scope.removeSelectedGroup=function(){_.remove($scope.dynamicProperty.Groups,{Guid:$scope.selectedGroup.Guid}),$scope.dynamicProperty.Groups[0]&&$scope.selectGroup($scope.dynamicProperty.Groups[0])},$scope.removeSelectedProperty=function(){_.remove($scope.selectedGroup.Items,{Guid:$scope.selectedProperty.Guid});var node=_.find($scope.grid[$scope.selectedGroup.Guid].grid.nodes,function(node){return node.id===$scope.selectedProperty.Guid});node&&($scope.grid[$scope.selectedGroup.Guid].remove_widget(node.el),$scope.selectedProperty=null)},$scope.addNewGroup=function(){var indexPosition=$scope.dynamicProperty.Groups.length,newGroup={Guid:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var d=(new Date).getTime(),r=(d+16*Math.random())%16|0;return d=Math.floor(d/16),("x"===c?r:3&r|8).toString(16)}),Title:"tab: "+indexPosition,IndexPosition:indexPosition,Items:[]};$scope.dynamicProperty.Groups.push(newGroup),$scope.selectedGroup=newGroup};var gridOptions={cellHeight:75,animate:!0,disableResize:!0};if($scope.addNewProperty=function(property){var width=12,positionY=$scope.selectedGroup.Items.length%2?0:1,gridId=$scope.selectedGroup.Guid;void 0===$scope.grid[gridId]&&($scope.grid[gridId]=$("#"+gridId).gridstack(gridOptions).data("gridstack")),$scope.grid[gridId]&&GridStackUI.Utils.sort($scope.grid[gridId].grid.nodes,1,width);var newProperty={Guid:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var d=(new Date).getTime(),r=(d+16*Math.random())%16|0;return d=Math.floor(d/16),("x"===c?r:3&r|8).toString(16)}),WebLayout:{Width:4,Height:1,PointY:positionY},auto_position:!1,Type:property.Type,LabelPropertyValue:translationService.translate("web-dynamicProperties-labelPlaceholder","Angi ledetekst"),NotEditableInListView:!0},field=_.find($scope.numberOfFields[newProperty.Type],function(v){return v.isAvailable});field&&(newProperty.Field=field.number);for(var i=0;;++i){var x=i%width,y=Math.floor(i/width);if(!(x+newProperty.WebLayout.Width>width)&&isAvailable(newProperty,gridId,x,y)){newProperty.WebLayout.PointX=x,newProperty.WebLayout.PointY=y;break}}$scope.selectedGroup.Items.push(newProperty),$scope.selectedProperty=newProperty},$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:{},columns:[{title:"Nedtrekksfelt",property:"Value"}]}}}}).result.then(function(item){$scope.selectedProperty.GuidNamedSelection=item.Guid,$scope.selectedProperty.NamedSelection=item},function(msg){})},$scope.selectProperty=function(property){$scope.selectedProperty=property},$scope.attachWidget=function(element,attrs,property){$scope.setNumberedFieldsAvailability(property.Field,-1,property.Type);var gridId=attrs.groupGuid;void 0===$scope.grid[gridId]&&($scope.grid[gridId]=$("#"+gridId).gridstack(gridOptions).data("gridstack")),$scope.grid[gridId]&&$scope.grid[gridId].addWidget(element,attrs.gsX,attrs.gsY,attrs.gsWidth,attrs.gsHeight,attrs.gsAutoPosition,null,null,null,null,attrs.gsId)},$scope.$watch("dynamicProperty",function(newValue,oldValue){newValue!==oldValue&&($scope.selectedGroup=newValue.Groups[0])}),!$scope.dynamicProperty||!$scope.dynamicProperty.Groups){var defaultGroup={Guid:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var d=(new Date).getTime(),r=(d+16*Math.random())%16|0;return d=Math.floor(d/16),("x"===c?r:3&r|8).toString(16)}),Title:"Egendefinerte felter",IndexPosition:0,Items:[]};$scope.dynamicProperty={Groups:[defaultGroup]},$scope.selectedGroup=defaultGroup}}}(),function(){angular.module("Plania").directive("plCategoryGridProperty",[function(TranslationService){return{restrict:"E",require:"^plCategoryGrid",scope:{property:"=property",selectedProperty:"=selectedProperty",selectProperty:"=selectProperty"},link:function(scope,element,attrs,gridCtrl){scope.$parent.attachWidget(element,attrs,scope.property),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)})}},templateUrl:"app/common/directives/dynamicProperty/plcategorygridProperty.html",controller:["$scope","$element","TranslationService",controller]}}]);var controller=function($scope,$element,translationService){}}(),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.createSingleDictionary(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.updateSingleDictionary(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){return!!comment.Comment.toLowerCase().includes($scope.searchString.toLowerCase())||(!!comment.UserCreatedBy.RealName.toLowerCase().includes($scope.searchString.toLowerCase())||!!comment.UserCreatedBy.Username.toLowerCase().includes($scope.searchString.toLowerCase()))}}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(){var columns=["Name","Url","Type","Description","IndexPosition","EntityType","UseUrlEncoding","HttpHeaders","ActionRule","EntityTasks","Filter"];repository.GetPaginated(repository.apiData.entityLink.url,0,1e4,{IndexPosition:"asc"},entityLinkFilter,null,JSON.stringify(columns)).then(function(result){$scope.totalCount=result.TotalCount,$scope.entityLinks=result.List.filter(function(link){return link.Visible}),_.forEach($scope.entityLinks,function(link){if(link.ActionRule&&(link.ParsedActionRule=JSON.parse(link.ActionRule),link.ParsedActionRule.OnlyOnce)){if(link.CurrentEntityTask=angular.copy(link.EntityTasks[0]),!link.CurrentEntityTask||!link.CurrentEntityTask.GuidUserCreatedBy)return;repository.getSingle(repository.apiData.user.url,link.CurrentEntityTask.GuidUserCreatedBy,null).then(function(result){link.CurrentEntityTask.UserCreatedBy=result.Data.RealName},function(error){repository.growl(error,"danger"),link.CurrentEntityTask.UserCreatedBy=""})}})},function(error){repository.growl(error,"danger")})}if($scope.guidEntity&&$scope.entityType){var entityLinkFilter={GuidEntity:$scope.guidEntity,PropertyFilter:[{Property:"EntityType",Operator:"=",Value:$scope.entityType},{Property:"Type",Operator:"=",Value:"1"}]};$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,null,!0).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],link:function(scope,element,attrs){},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;mIlastPage&&$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"},controller:["$scope","$modal","ngTableParams","config","Repository","$filter","$window","TranslationService",controller],link:function(scope,element,attrs){},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="zmdi-info-outline":"danger"===$scope.severity?$scope.icon="zmdi-alert-circle":"warning"===$scope.severity?$scope.icon="zmdi-alert-triangle":"success"===$scope.severity&&($scope.icon="zmdi-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:"@"},controller:["$scope","Constants",controller],templateUrl:"app/common/directives/views/plDatepickerDirective.html",link:linkFunction}});var 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])}}(),function(){angular.module("Plania").directive("plDeactivatedWarning",function(){return{restrict:"E",replace:!0,template:' Deaktivert for fremtidig bruk'}})}(),function(){angular.module("Plania").directive("plEntityNavigation",["Repository",function(repository){return{restrict:"E",scope:{entity:"=entity",guid:"=guid",model:"=model",context:"=context",target:"=target"},templateUrl:"app/common/directives/views/entityNavigation.html",link:function(scope,element,attrs){var apiData=_.find(repository.apiData,function(o){return o.prefix===scope.entity&&(!scope.context||o.contextId===scope.context)});scope.navigationState=apiData.navigationState,scope.canNavigate=!1,scope.$watch("guid",function(newValue,oldValue){newValue?scope.canNavigate=scope.$parent.$root.hasReadAccess(scope.entity)&&repository.enableWebNavigation:scope.model=null})}}}])}(),function(){function controller($scope,enumService,translationService){var enumNumberToString=function(enumValue){enumValue&&$scope.enumType&&("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){$scope.ngDisabled||($scope.ngDisabled=!1),void 0===$scope.disableSearch&&($scope.disableSearch=!0),$scope.selectedValueProperty||($scope.selectedValueProperty="Value");var 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=["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"]),validOptions.length>0?(_.remove(options,function(option){return!validOptions.some(function(o){return o===option.StringValue})}),options):options};$scope.applyChange=function(newValue){$scope.selectedValue=newValue,$scope.onChange&&"function"==typeof $scope.onChange&&$scope.onChange(newValue)},$scope.enumType&&enumService.GetEnumValues($scope.enumType).then(function(result){if($scope.enumSelectOptions=limitEnumOptions(result),$scope.includeUndefined||_.remove($scope.enumSelectOptions,function(option){return"Undefined"===option.StringValue||"Udefinert"===option.StringValue}),(""===$scope.selectedValue||null===$scope.selectedValue||"Undefined"===$scope.selectedValue)&&!$scope.includeUndefined&&result.length>0&&($scope.selectedValue=result[0][$scope.selectedValueProperty]),$scope.selectedValue&&!$scope.multiple){var selectedEnumOption=_.find(result,function(enumValue){return enumValue[$scope.selectedValueProperty].toString()===$scope.selectedValue.toString()});selectedEnumOption&&($scope.selectedValue=selectedEnumOption[$scope.selectedValueProperty])}!$scope.enumType||"prefix"!==$scope.enumType.toLowerCase()&&"documentationcontext"!==$scope.enumType.toLowerCase()||$scope.enumSelectOptions.sort(function(a,b){return a.TranslatedValueb.TranslatedValue?1:0})})}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"},controller:["$scope","EnumService",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",function($animate,$localStorage,registeredFieldService){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",function($animate,$localStorage,registeredFieldService){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++,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",function($animate,$localStorage,registeredFieldService){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){console.log(error)})}()}}}])}(),function(){angular.module("Plania").directive("plPrintExcelListDirective",function(){return{restrict:"E",scope:{domainName:"=domainName",table:"=table",selectedListSetup:"=selectedListSetup"},controller:["$scope","Repository","$window","TranslationService","config",printController],replace:!0,template:''}});var printController=function($scope,repository,$window,translationService,config){$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;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,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",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"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"10088"!==$localStorage.generalOptions.CustomerId&&"12258"!==$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"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"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":return autoCompleteService.referenceData;case"referencetype":return autoCompleteService.referenceType;case"periodictask":return autoCompleteService.periodicTask;case"workordertemplate":return autoCompleteService.workOrderTemplate}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.active&&getCaptionTextIfNull())}),$scope.$watch("validate",function(newValue,oldValue){newValue!==oldValue&&newValue&&($scope.checkValid(),$scope.validate=!1)});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){setTimeout(function(){scope.setIndex(-1),"postal"===scope.onType?scope.showError=!1:(void 0===scope.isValid&&scope.checkValid(),scope.completing&&scope.suggestions&&1===scope.suggestions.length&&(scope.select(scope.suggestions[0]),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(){return{restrict:"A",require:"ngModel",link:function(scope,element,attrs,ngModelController){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",[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())})}}]),angular.module("Plania").directive("plEqualHeightColumns",[function(){return{restrict:"A",scope:{},link:function(scope,element){var columns=element.find('>[class*="col-"]');console.log(columns)}}}]),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="fa fa-file-word-o c-blue";break;case"pdf":scope.iconClass="fa fa-file-pdf-o c-red";break;case"txt":scope.iconClass="fa fa-file-text-o c-gray";break;case"wma":case"mp3":scope.iconClass="fa fa-file-audio-o c-purple";break;case"csv":case"xls":case"xlsx":scope.iconClass="fa fa-file-excel-o c-green";break;case"zip":scope.iconClass="fa fa-file-archive-o c-brown";break;case"jpg":case"jpeg":case"png":scope.iconClass="fa fa-file-image-o c-teal";break;case"eml":scope.iconClass="fa fa-at c-blue";break;case"ppt":case"pptx":scope.iconClass="fa fa-file-powerpoint-o c-teal";break;case"mp4":scope.iconClass="fa fa-play-circle-o c-deeporange";break;default:scope.iconClass="fa fa-file-text-o"}0===scope.filePath.indexOf("http")&&(scope.iconClass="fa fa-link 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)switch($state.params.entityData.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,null,!0).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}}}}).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){return listService.getGroupName($state.params.entityData.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)}),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",hideSettings:"=hideSettings"},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){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 console.log("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.updateSingleDictionary(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.updateSingleDictionary(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 marker={icon:entityInfo.marker.icon,markerColor:entityInfo.marker.color,shape:entityInfo.marker.shape,prefix:"zmdi",type:"extraMarker"};$scope.mapData.markers[$scope.gisEntity.Guid.replace(/-/g,"")]={icon:marker,weight:entityInfo.weight,lat:$scope.gisEntity.Coordinates[0].lat,lng:$scope.gisEntity.Coordinates[0].lng,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),newGisEntity.EntityType=$scope.entityModel.Prefix,newGisEntity.GuidEntity=$scope.entityModel.Guid,repository.createSingleDictionary(repository.apiData.gisEntity.url,newGisEntity).then(function(result){var changeList=[];changeList.push(JSON.stringify({GuidGisEntity:result.Guid})),repository.patch(repository.apiData[$scope.entity].url,$scope.entityModel.Guid,changeList).then(function(patchResult){repository.growl("Koordinater opprettet","info"),$scope.entityModel.GuidGisEntity=result.Guid,$scope.showMap=!0,getMarker(result.Guid)},function(error){repository.growl(error,"danger")})},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;var changeList=[];changeList.push(JSON.stringify({GuidGisEntity:null})),repository.patch(repository.apiData[$scope.entity].url,$scope.entityModel.Guid,changeList).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",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)),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($itemScope,$event,modelValue,text,$li){$scope.addNewChild(modelValue)}}),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($itemScope,$event,modelValue,text,$li){$scope.addNewDocument(item)}}),options.push({html:''+translationService.translate("web-equipment-treeview-addExistingDocument","Legg til eksisterende dokument")+"",click:function($itemScope,$event,modelValue,text,$li){$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,getTreeModel=function(){repository.GetPaginated(url,0,pageSize,{Id:"asc"},filter,"",JSON.stringify(columns)).then(function(result){$scope.treeModel=result.List,$scope.totalCount=result.TotalCount,$scope.counts.totalCount=result.TotalCount;var filterData=repository.commonService.getFilterData();""===filterData.selectedBuilding.Guid&&""===filterData.selectedSelection.Guid||(0===$scope.treeModel.length?$scope.selectedItem=null:$scope.selectedItem=$scope.treeModel[0]),saveTreeView()})};$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},{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);repository.GetPaginated(getChildUrl(item),-1,-1,{Id:"asc" },getChildFilter(item),"",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(("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"zmdi-settings c-bluegray";case areaPrefix:return"zmdi-layers c-lightblue";case buildingPrefix:return item.IsGround?"zmdi-nature-people":"zmdi-balance c-brown";case estatePrefix:return"zmdi-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.$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:{topLevelEntity:"=topLevelEntity",parentGuid:"=parentGuid",filterEntity:"=filterEntity",totalCount:"=totalCount",filterProperty:"=filterProperty",usage:"=usage",itemTable:"=itemTable",selectedItem:"=selectedItem",fromState:"=navigationFromState",canSelectNone:"=canSelectNone",treeViewContext:"=treeViewContext"},controller:["$scope","$rootScope","Repository","$state","$sessionStorage","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",color:"=color"},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.createSingleDictionary(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",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(){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",commonService.getFilterData().selectedEstate&&(params.GuidEstate=commonService.getFilterData().selectedEstate.Guid),params},alreadyPrinted=!1,refreshReport=function(){var rs=reportViewer.reportSource();rs.parameters=getParams(),rs.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+".trdx",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/userProfileMenu"+attr.userProfileMenu+".html"}}})}(),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(){$scope.isCollapsed=!1,$modal.open({templateUrl:"app/video/views/createVideoModal.html",controller:"CreateVideoXEntityController",resolve:{params:resolveParams}}).result.then(function(){$scope.videoTable.reload(),$scope.isCollapsed=!1},function(msg){$scope.isCollapsed=!1})},$scope.addExistingVideo=function(){$scope.isCollapsed=!1,$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(),$scope.isCollapsed=!1})},function(msg){$scope.isCollapsed=!1})},$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(),$scope.isCollapsed=!1},function(){$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}}}})}}angular.module("Plania").directive("videos",function(){return{restrict:"E",scope:{isCollapsed:"=isCollapsed",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){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,setAttachments=function(){params.attachments&&_.isArray(params.attachments)&¶ms.attachments.forEach(function(attachment){1===attachment.ArchiveType?$scope.attachments.push(attachment):params.preselectedAttachments&&_.contains(params.preselectedAttachments,attachment.Guid)&&$scope.attachments.push(attachment)})},fetchDocuments=function(){var filter={};params.documentFilter?filter=params.documentFilter:filter["Guid"+entity]=$scope.model.Guid;var documentColumns=["Document.Id","Document.Description","Document.Guid","Document.FilePath","ArchiveType"];return repository.GetPaginated(repository.apiData.documentXEntity.url,0,1e3,{"Document.Description":"asc"},filter,"",JSON.stringify(documentColumns)).then(function(response){return response.List.forEach(function(document){_.find(params.attachments,{Guid:document.Guid})||params.attachments.push(document)}),setAttachments(),params.attachments})},fetchImages=function(){var url="";if("WorkOrder"===entity?url=repository.apiData.workOrder.url:"Request"===entity&&(url=repository.apiData.request.url),url)return repository.getSingle(url,$scope.model.Guid).then(function(response){return response.Data.Images.forEach(function(image){_.find(params.attachments,{Guid:image.Guid})||params.attachments.push(image)}),setAttachments(),params.attachments})};params.getAllDocuments?fetchDocuments():setAttachments(),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.emailTemplates.forEach(function(emailTemplate){emailTemplate.TemplateBody=decodeHtml(emailTemplate.TemplateBody)}),$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.forEach(function(attachment){var guid;guid=attachment.GuidDocument?attachment.GuidDocument:attachment.Guid,0===attachments.length?attachments+=guid:attachments+=","+guid}),$scope.email.subject||($scope.email.subject=$scope.getEntityCaption($scope.model));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:encodeHtml($scope.email.body),EmailFrom:$scope.email.from,Attachments:attachments,Status:"Outbox"};params.returnEmailObject?$modalInstance.close(postEmail):repository.createSingleDictionary(repository.apiData.alarmLog.url,postEmail).then(function(result){swal("Suksess!","Eposten ble lagt til i utboksen","success"),$modalInstance.close(result)},function(error){swal("Feil!",error,"error")})};var encodeHtml=function(html){var tmpElement=document.createElement("div");return $(tmpElement).text(html).html()},decodeHtml=function(html){var tmpElement=document.createElement("textarea");return tmpElement.innerHTML=html,tmpElement.value};$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(){var parameters={entity:entity,guid:$scope.model.Guid,attachments:params.attachments,selectedAttachmentGuids:_.map($scope.attachments,function(o){return o.Guid}),onNewDocument:onNewDocument,onNewImage:onNewImage,reloadDocuments:function(){return reloadDocuments?reloadDocuments().then(function(documents){return documents.forEach(function(document){_.find(params.attachments,{Guid:document.Guid})||params.attachments.push(document)}),setAttachments(),params.attachments}):fetchDocuments()},reloadImages:function(){return reloadImages?reloadImages().then(function(images){return images.forEach(function(image){_.find(params.attachments,{Guid:image.Guid})||params.attachments.push(image)}),setAttachments(),params.attachments}):fetchImages()}};"PurchaseOrder"===entity&&(parameters.connectedEntity="WorkOrder",parameters.connectedEntityGuid=$scope.model.GuidWorkOrder),$modal.open({templateUrl:"app/common/modal/views/selectAttachmentModal.html",controller:"SelectAttachmentModalController",size:"lg",resolve:{params:function(){return parameters}}}).result.then(function(result){result.forEach(function(attachment){_.find($scope.attachments,{Guid:attachment.Guid})||$scope.attachments.push(attachment)})},function(error){})},$scope.openDocument=function(document){documentService.openDocument(document.Document)}}angular.module("Plania").controller("EmailModalController",["$scope","$modalInstance","$modal","params","TranslationService","DocumentService","Repository","$q","$sce","$filter","$localStorage",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($sce){return function(msg){return msg=(msg+"").replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,"$1
$2"),$sce.trustAsHtml(msg)}}angular.module("Plania").filter("nl2br",["$sce",filter])}(),function(){function filter($filter){return function(value){return $filter("number")(value,2)}}angular.module("Plania").filter("plCurrency",["$filter",filter])}(),function(){function filter($sce){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")),$sce.trustAsHtml(newText)}}angular.module("Plania").filter("plLimitTo",["$sce",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,$modalInstance,params,Upload){$scope.selectedImageFile=params.image,$scope.targetSize=params.targetSize,$scope.areaType=params.areaType,$scope.uploadImage=function(){$modalInstance.close(Upload.dataUrltoBlob($scope.croppedDataUrl,$scope.selectedImageFile.name))},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("ImageUploadModalController",["$scope","$modalInstance","params","Upload",controller])}(),function(){function controller($scope,repository,translationService){$scope.selectedLanguage={},repository.GetPaginated(repository.apiData.language.url,0,100,{},{}).then(function(result){$scope.languages=result.List,$scope.selectedLanguage=_.find(result.List,function(o){return o.Locale===translationService.getLocale()})}),$scope.getFlagCssClass=function(language){if(!language)return"flag-no";switch(language.Locale){case"da-dk":return"flag-dk";case"fr-fr":return"flag-fr";case"nb-no":return"flag-no";case"sv-se":return"flag-se";case"en-gb":return"flag-gb"}},$scope.changeUserLanguage=function(language){$scope.selectedLanguage=language,translationService.setLocale(language.Locale);var users=[JSON.stringify({Guid:repository.authService.getUserData().guidUser,GuidLanguage:language.Guid})];repository.createMultiple(repository.apiData.massUpdate.url,users,"Prefix=User").then(function(response){window.location.reload()})}}angular.module("Plania").controller("LanguageSelectionController",["$scope","Repository","TranslationService",controller])}(),function(){angular.module("Plania").controller("ListController",["$scope","Repository","$state","TranslationService","DocumentService","$modal","ListService","$localStorage","ListCompressionService","$rootScope","OperationalMessageService","config",function($scope,repository,$state,translationService,documentService,$modal,listService,$localStorage,listCompressionService,$rootScope,operationalMessageService,config){$scope.selected={},$scope.selectedIndex=-1,$scope.showFilter=!1,$scope.showViewButton=!1,$scope.showDrawingEditButton=!1,$scope.clickable=!0,$scope.showTreeView=!1,$scope.filters={PropertyFilter:[]},$scope.prefix=$state.params.entityData.prefix,$scope.contextId=$state.params.entityData.contextId||"List-"+$scope.prefix,$scope.generalOptions=$localStorage.generalOptions;var isViewDestroyed=!1,urlFilter=null,menuParams=null;if($scope.routeEntity=$scope.navigation.current.name.replace(".list",""),$scope.titleSystemName="web-"+$scope.routeEntity+"-table-title",$scope.titleDefaultName=translationService.translate("web-"+$scope.routeEntity),$scope.title=translationService.translate($scope.titleSystemName,$scope.titleDefaultName),$scope.treeView={selectedTreeViewItem:{}},$localStorage["showTreeView"+$state.params.entityData.prefix]&&($scope.showTreeView=$localStorage["showTreeView"+$state.params.entityData.prefix]),"Document"===$state.params.entityData.prefix&&($scope.showViewButton=!0),"Drawing"===$state.params.entityData.prefix&&($scope.showDrawingEditButton=!0),"sparePartCountingItem"===$state.params.entityData.prefix&&($scope.clickable=!1),"Supplier"===$state.params.entityData.prefix&&$scope.filters.PropertyFilter.push({Property:"IsDeactivated",Operator:"=",Value:"0"}),"ResourceGroup"===$state.params.entityData.prefix&&"cleaning.resourceGroup.list"===$state.current.name&&$scope.filters.PropertyFilter.push({Property:"DoesCleaningTasks",Operator:"=",Value:!0}),"Contract"===$state.params.entityData.prefix&&("contract.list"===$state.current.name?$scope.filters.PropertyFilter.push({Property:"RentalType",Operator:"=",Value:"0"}):"housingContract.list"===$state.current.name?$scope.filters.PropertyFilter.push({Property:"RentalType",Operator:"=",Value:"1"}):"reinvoicingContract.list"===$state.current.name&&$scope.filters.PropertyFilter.push({Property:"RentalType",Operator:"=",Value:"2"})),"Area"===$state.params.entityData.prefix&&($scope.filters.PropertyFilter.push({Property:"IsDeactivated",Operator:"=",Value:"0"}),"housing.list"===$state.current.name?$scope.filters.PropertyFilter.push({Property:"IsHousing",Operator:"=",Value:"1"}):"area.list"===$state.current.name&&$scope.filters.PropertyFilter.push({Property:"IsHousing",Operator:"=",Value:"0"})),"AreaXCleaningTask"===$state.params.entityData.prefix&&($scope.filters.CleaningStatus="Active"),"Building"===$state.params.entityData.prefix&&$scope.filters.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:"building.list"===$state.current.name?"0":"1"}),"Equipment"===$state.params.entityData.prefix&&$scope.filters.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:"equipment.list"===$state.current.name?"0":"1"}),"SparePart"===$state.params.entityData.prefix&&$scope.filters.PropertyFilter.push({Property:"IsDeactivated",Operator:"=",Value:"0"}),"Condition"===$state.params.entityData.prefix&&($scope.filters.PropertyFilter.push({Property:"Type",Operator:"<>",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"})),"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 propertyFilter=[{Property:"GuidOwnerPerson",Operator:"=",value:$scope.userInfo.guidPerson,Operand:"AND"},{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"},{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"},{Property:"GuidManagerPerson",Operator:"=",value:$scope.userInfo.guidPerson,Operand:"OR"},{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"},{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"}],anyActiveProjects={Prefix:"Project",FromDate:new Date(0).toISOString(),ToDate:null,DateProperty:null,IncludePeriodicTask:!1,Interval:null,PropertyFilter:propertyFilter,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)};$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"];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&&($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(){})};$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:"lg",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("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($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.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;default:$scope.navigation.go(prefix.charAt(0).toLowerCase()+prefix.slice(1)+".create",{guidEntityToCopy:selectedGuid})}}},$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.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.createSingleDictionary(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.createSingleDictionary(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.addOperationalMessage=function(){$modal.open({templateUrl:"app/operationalMessage/views/operationalMessageModal.html",controller:"OperationalMessageModalController",resolve:{params:function(){return{}}}}).result.then(function(){$scope.items.reload()})},$scope.editDrawing=function(drawing){$modal.open({templateUrl:"app/dwg/views/editDrawingModal.html",controller:"EditDrawingModalController",size:"lg",resolve:{params:function(){return{Guid:drawing.Guid}}}}).result.then(function(){$scope.items.reload()},function(){$scope.items.reload()})},$scope.addNewDrawing=function(){$modal.open({templateUrl:"app/dwg/views/editDrawingModal.html",controller:"EditDrawingModalController",size:"lg",resolve:{params:function(){return{}}}}).result.then(function(){$scope.items.reload()},function(){$scope.items.reload()})},$scope.addNewIfcFile=function(){$modal.open({templateUrl:"app/ifc/views/createIfcFileModal.html",controller:"CreateIfcFileModalController"}).result.then(function(guids){1===guids.length||"string"==typeof guids?(guid=1===guids.length?guids[0]:guids,$scope.navigation.go("ifcFile.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(guids){$scope.navigation.go("sparePart.edit",{guid: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(){console.log("cancel")})},$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.Estate&&(workOrder.guidEstate=item.GuidEstate,workOrder.estate=item.Estate.Id+" - "+item.Estate.Description),!workOrder.guidBuilding&&item.Building&&(workOrder.guidBuilding=item.GuidBuilding,workOrder.building=item.Building.Id+" - "+item.Building.Description),!workOrder.guidEquipment&&item.Equipment&&(workOrder.guidEquipment=item.GuidEquipment,workOrder.equipment=item.Equipment.Id+" - "+item.Equipment.Description),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={PropertyFilter:[{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"},{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"}]};$scope.userInfo.isSystemAdministrator||$scope.userInfo.isProjectAdministrator||(filter.PropertyFilter=[{Property:"GuidOwnerPerson",Operator:"=",value:$scope.userInfo.guidPerson,Operand:"AND"},{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"},{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"},{Property:"GuidManagerPerson",Operator:"=",value:$scope.userInfo.guidPerson,Operand:"OR"},{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"},{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"}]),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,JSON.stringify(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(repository.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&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("equipment.edit",{guid:item.GuidEquipment}),translationService.translate("web-listview-contextMenu-equipment-view","Gå til anlegg")))},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&&repository.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&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("dwg.view",{guid:item.GuidDrawing}),translationService.translate("web-listview-contextMenu-area-viewDrawing","Gå til SVG-visningen")))},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"))),$scope.hasEditAccess("Drawing")&&options.push({html:' '+translationService.translate("web-listview-contextMenu-drawing-edit","Åpne tegningsinfo")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.editDrawing(item)}})},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")&&repository.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&&repository.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&&repository.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&&repository.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&&repository.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")&&repository.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,JSON.stringify({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&&repository.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&&repository.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&&repository.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&&repository.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)}})},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&&repository.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&&repository.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.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"))),options.push({html:' '+translationService.translate("web-listview-contextMenu-dataImport-copy","Opprett ny fra eksisterende")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.navigation.go("dataImport.create",{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.ChangeSet=function(item,options){me.useDefaultParentObjectNavigation=!0,options.push({html:' '+translationService.translate("web-listview-contextMenu-changeSet-view","Åpne endringssett")+"",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))}}},$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.keywords=repository.filterKeyWords,$scope.user=repository.authService.getUserData(),$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)})})},$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) };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())},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}},setSorting=function(doStringify){$scope.model.Sorting={},$scope.model.Sorting[$scope.sortingProperty]=$scope.sortingParam,doStringify&&($scope.model.Sorting=JSON.stringify($scope.model.Sorting))};$scope.ok=function(){setSorting(!1);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=filter)}$modalInstance.close("ok")},$scope.cancel=function(){$scope.model.Columns=originalColumnSetup,$scope.model.Id=originalObject.Id,$scope.model.IsPublicView=originalObject.IsPublicView,$scope.model.IsDefaultView=originalObject.IsDefaultView,$modalInstance.dismiss("canceled")},$scope.save=function(){setSorting(!0),setColumnPositionOnModel(),repository.updateSingle(repository.apiData.webListView.url,$scope.model).then(function(result){repository.growl("Listeoppsettet har blitt lagret","success"),$scope.model.Columns.forEach(function(col){col.Filter&&(col.Filter=JSON.parse(col.Filter))}),$scope.model.Sorting=JSON.parse($scope.model.Sorting),$modalInstance.close("saved")})},$scope.saveAs=function(){var text="";$scope.user.isSystemAdministrator||(text=' Listeoppsettet blir lagret som ett privat listeoppsett.'),swal({title:translationService.translate("listSetup-swal-saveas-title","Lagre som..."),type:"input",cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),text:text,html:!0,showCancelButton:!0,closeOnConfirm:!1,animation:"slide-from-top",inputValue:$scope.model.Id,inputPlaceholder:translationService.translate("listSetup-label-name","Navn")},function(inputValue){return!1!==inputValue&&(""===inputValue?(swal.showInputError("Du må skrive inn et navn for å lagre"),!1):"plania standard"===inputValue.toLowerCase()?(swal.showInputError(translationService.translate("listsetup-saveas-changename","Du må velge et annet navn enn Plania standard for å få lagret listen.")),!1):($scope.model.Id=inputValue,$scope.user.isSystemAdministrator||($scope.model.IsPublicView=!1),setColumnPositionOnModel(),setSorting(!0),$scope.model.EntityType=$scope.model.EntityName||$scope.model.EntityType,void repository.createSingle(repository.apiData.webListView.url,$scope.model).then(function(result){swal("Success!",translationService.translate("listsetup-saveas-success","Listeoppsettet ble opprettet"),"success"),$scope.model.Guid=result,$scope.model.Columns.forEach(function(col){col.Filter&&(col.Filter=JSON.parse(col.Filter))}),$scope.model.Sorting=JSON.parse($scope.model.Sorting),originalObject.Columns=originalColumnSetup,$modalInstance.close("savedNew")})))})},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-listsetup-message","Listeoppsettet vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-listsetup-button-confirm","Ja, slett listeoppsettet!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.webListView.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-listsetup-success","Listeoppsettet ble fjernet!"),result,"success"),$modalInstance.close("deleted")})})},$scope.toggleHide=function(column){column.Filter&&(column.Filter[0].Hidden=!column.Filter[0].Hidden)}}angular.module("Plania").controller("ListSetupModalController",["$scope","$modalInstance","$modal","params","Repository","TranslationService","$localStorage",controller])}(),angular.module("Plania").controller("MainController",["$scope","$timeout","$state","$rootScope",controller]),function(){function controller($scope,$modalInstance,params,repository,translationService,enumService){var entityPrefix=params.prefix,apiData=_.find(repository.apiData,function(o){return o.prefix===params.prefix});$scope.datePickers={},$scope.showPeriodicCleaningRecurrence=params.showPeriodicCleaningRecurrence,repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix[entityPrefix]).then(function(result){$scope.fieldRules=result,$scope.columns=[],params.columns.slice().forEach(function(column){var columnFieldRule=_.find($scope.fieldRules,function(o){return o.FieldName===column.Property});"UpdatedDate"!==column.Property&&"CreationDate"!==column.Property&&(columnFieldRule&&(columnFieldRule.Unique||columnFieldRule.NotEditableInListView)||("date"===column.PropertyType&&($scope.datePickers[column.Title]=!1),column.Property.indexOf("CleaningQuality.")>=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&&(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?(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=JSON.stringify(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(JSON.stringify(editedRow))}),"AreaXCleaningTask"===entityPrefix?repository.patch(apiData.url,null,editedRows).then(function(response){$scope.updateResult=response,$modalInstance.close()},function(error){repository.growl(error,"danger")}):repository.createMultiple(repository.apiData.massUpdate.url,editedRows,"Prefix="+params.prefix).then(function(response){$scope.updateResult=response,0===response.length&&$modalInstance.close()})},$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.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,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?"zmdi-alert-circle c-red":"zmdi-check-circle c-green":"zmdi-help"},$scope.getPwdMustContainLettersIcon=function(){var newPassword=$scope.viewModel.NewPassword;return newPassword?$scope.passwordRules.PwdMustContainLetters&&!stringContainsALetter(newPassword)?"zmdi-alert-circle c-red":"zmdi-check-circle c-green":"zmdi-help"},$scope.getPwdMustContainDigitsIcon=function(){var newPassword=$scope.viewModel.NewPassword;return newPassword?$scope.passwordRules.PwdMustContainDigits&&!stringContainsANumber(newPassword)?"zmdi-alert-circle c-red":"zmdi-check-circle c-green":"zmdi-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.createSingleDictionary(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.updateSingleDictionary(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.createSingleDictionary(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(),repository.updateSingle(repository.apiData.webListView.url,$scope.model).then(function(result){repository.growl("Listeoppsettet har blitt lagret","success"),$modalInstance.close("saved")})}}angular.module("Plania").controller("EditTableColumnsModalController",["$scope","$modalInstance","$modal","params","Repository","TranslationService",controller])}(),function(){function controller($scope,$modalInstance,params,repository,$modal){$scope.selectedDocuments=[],$scope.documents=[],params.attachments.forEach(function(attachment){$scope.documents.push(angular.copy(attachment))}),$scope.connectedEntityDocuments=[],$scope.entityType=params.entity;var guidEntity=params.guid,onNewDocument=params.onNewDocument,onNewImage=params.onNewImage,reloadDocuments=params.reloadDocuments,reloadImages=params.reloadImages;$scope.canAddImage="WorkOrder"===$scope.entityType||"Request"===$scope.entityType,$scope.canAddDocument=!0,$scope.documents.forEach(function(document){_.contains(params.selectedAttachmentGuids,document.Guid)?(document.isAlreadySelected=!0,$scope.selectedDocuments.push(document)):document.isAlreadySelected=!1}),params.connectedEntity&¶ms.connectedEntityGuid&&repository.GetPaginated(repository.apiData.documentXEntity.url,0,100,{"Document.Id":"desc"},{PropertyFilter:[{Property:"Guid"+params.connectedEntity,Operator:"=",Value:params.connectedEntityGuid}]},0,JSON.stringify(columns)).then(function(response){$scope.connectedEntityDocuments=response.List}),$scope.isSelected=function(guid){return _.find($scope.selectedDocuments,{Guid:guid})},$scope.selectDocument=function(document){if(!document.isAlreadySelected)if(_.find($scope.selectedDocuments,{Guid:document.Guid}))for(var i=0;i<$scope.selectedDocuments.length;i++){var doc=$scope.selectedDocuments[i];if(doc.Guid===document.Guid)return void $scope.selectedDocuments.splice(i,1)}else $scope.selectedDocuments.push(document)};var resolveParams=function(){var params={};return params["guid"+$scope.entityType]=guidEntity,params};$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)}),reloadDocuments&&"function"==typeof reloadDocuments&&reloadDocuments(guids).then(function(documents){documents.forEach(function(document){if(!_.find($scope.documents,{Guid:document.Guid})){var newDocument=angular.copy(document);$scope.documents.push(angular.copy(newDocument)),guids.includes(newDocument.GuidDocument)&&$scope.selectDocument(newDocument)}})}),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=[];if(images&&Array.isArray(images)&&images.forEach(function(image){image.Guid&&guids.push(image.Guid)}),reloadImages&&"function"==typeof reloadImages){var promise=reloadImages();promise&&promise.then(function(images){images.forEach(function(image){if(!_.find($scope.documents,{Guid:image.Guid})){var newImage=angular.copy(image);$scope.documents.push(angular.copy(newImage)),guids.includes(newImage.Guid)&&$scope.selectDocument(newImage)}})})}onNewImage&&"function"==typeof onNewImage&&onNewImage(images)})},$scope.ok=function(){$modalInstance.close($scope.selectedDocuments)},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("SelectAttachmentModalController",["$scope","$modalInstance","params","Repository","$modal",controller])}(),function(){function controller($scope,$modalInstance,translationService){$scope.availableIcons=["alert-circle","alert-octagon","alert-polygon","alert-triangle","help","info","notifications-active","notifications","chart","chart-donut","assignment","assignment-check","thumb-up","thumb-up-down","case","dns","flag","home","puzzle-piece","money","money-box","shopping-cart","shopping-basket","truck","store","shield-security","shield-check","check-all","check","plus","plus-circle","star","comment-alert","comment","comments","camera","desktop-windows","device-hub","keyboard","phone","smartphone","wifi","arrow-right-top","trending-down","trending-flat","trending-up","arrows","rotate-left","rotate-right","my-location","pin","apps","view-dashboard","view-column","widgets","grid","view-list","alarm","alarm-check","time-interval","time","time-countdown","timer","calendar","fire","flower-alt","flash","file-text","file-plus","file","format-list-bulleted","format-list-numbered","copy"],$scope.ok=function(selectedIcon){$modalInstance.close(selectedIcon)},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("SelectIconModalController",["$scope","$modalInstance",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={}),$scope.itemTable=new ngTableParams({page:1,count:10,sorting:modalParams.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(){function controller($scope,$rootScope,repository,commonService,translationService){$scope.count=20,$scope.totalCount=0,$scope.selections=[],$scope.changeSelectionAccess=$scope.hasReadAccess(repository.commonService.prefix.BuildingSelection),$scope.selectedSelection={};var storedSelection=commonService.getFilterData().selectedSelection;storedSelection&&($scope.selectedSelection=storedSelection),$scope.filter={IncludeGuid:$scope.selectedSelection.Guid},$scope.getSelections=function(){$scope.changeSelectionAccess&&repository.GetPaginated(repository.apiData.buildingSelection.url,0,$scope.count,{description:"asc"},$scope.filter,"",JSON.stringify(["Description"])).then(function(result){result&&($scope.totalCount=result.TotalCount,$scope.selections=result.List);var storedSelection=commonService.getFilterData().selectedSelection;""!==storedSelection.Guid&&$scope.selectedSelection&&storedSelection.Guid!==$scope.selectedSelection.Guid&&$rootScope.$broadcast($rootScope.events.newSelection,!0),$scope.selectedSelection&&!$scope.selectedSelection.Description&&($scope.selectedSelection.Description=_.filter($scope.selections,{Guid:storedSelection.Guid})[0].Description)},function(error){$scope.totalCount=0,$scope.selections=[],repository.growl(error,"danger")})},$scope.getSelections(),$scope.addMoreData=function(){$scope.count+=100,$scope.getSelections()},$scope.changeSelection=function(selected){selected.Guid!==$scope.selectedSelection.Guid&&(commonService.setSelectedSelection(selected),commonService.setEmptyBuilding(),$rootScope.$broadcast($rootScope.events.newSelection,!0))},$scope.setEmptySelection=function(){$scope.filter.searchString="",$scope.selectedSelection.Guid&&(commonService.setEmptySelection(),$rootScope.$broadcast($rootScope.events.newSelection,!0))},$scope.$on($scope.events.newSelection,function(){$scope.selectedSelection=commonService.getFilterData().selectedSelection}),$scope.$on($scope.events.updatedAccess,function(){$scope.changeSelectionAccess=$scope.hasReadAccess(repository.commonService.prefix.BuildingSelection),$scope.changeSelectionAccess||(commonService.setSelectedSelection({Guid:repository.authService.getUserData().defaultSelection,Description:repository.authService.getUserData().defaultSelectionDescription}),$rootScope.$broadcast($rootScope.events.newSelection,!0)),""===$scope.selectedSelection.Guid&&$scope.getSelections()})}angular.module("Plania").controller("SelectedSelectionController",["$scope","$rootScope","Repository","CommonService","TranslationService",controller])}(),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("windowslogin"))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.isExternalUser=!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.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.canOverridePermissions="1"===data.CanOverridePermissions,userData.isExternalUser="1"===data.IsExternalUser,userData.useTwoFactor="1"===data.UseTwoFactor,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.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.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.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()}),searchParam.PropertyFilter.push({Property:"DisabledFromDate",Operator:"=",Value:null,Operand:"OR"}),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"];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)})},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.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)})},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.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.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={INDEX_POSITION:"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||(searchParam={}),searchParam.PropertyFilter||(searchParam.PropertyFilter=[]),searchParam.PropertyFilter.unshift({Property:"DisabledFromDate",Operator:"=",Value:null,Operand:"OR"}),searchParam.PropertyFilter.unshift({Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()}),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}angular.module("Plania").factory("AutoCompleteService",["genericRepository","$q","CommonService",autoCompleteService])}(),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.setEmptyBuilding(),service.setEmptyDataOwner(),service.setEmptySelection()},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.Id+" - "+building.Description,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,owner.GuidDefaultDocumentType&&owner.DocumentType?(service.filterData.selectedDataOwner.GuidDefaultDocumentType=owner.GuidDefaultDocumentType,service.filterData.selectedDataOwner.DefaultDocumentTypeId=owner.DocumentType.Id):(service.filterData.selectedDataOwner.GuidDefaultDocumentType="",service.filterData.selectedDataOwner.DefaultDocumentTypeId=""),owner.GuidWoXEqDocumentCategory&&(owner.DocumentCategory1||owner.WoXEqDocumentCategory)?(service.filterData.selectedDataOwner.GuidWoXEqDocumentCategory=owner.GuidWoXEqDocumentCategory,service.filterData.selectedDataOwner.WoXEqDocumentCategory=owner.DocumentCategory1?owner.DocumentCategory1.Description:owner.WoXEqDocumentCategory):(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.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",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",ContractRevision:"ContractRevision",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",EntityMailList:"EntityMailList",EntityPermission:"EntityPermission",EntityPermissionProfile:"EntityPermissionProfile",Equipment:"Equipment",EquipmentCategory:"EquipmentCategory",EquipmentDowntime:"EquipmentDowntime",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",IfcFile:"IfcFile",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",Meter:"Meter",MeterReading:"MeterReading",MeterXArea:"MeterXArea",MobileMenuProfile:"MobileMenuProfile",NamedSelection:"NamedSelection",NamedSelectionValue:"NamedSelectionValue",OpcAlarm:"OpcAlarm",OperationalMessage:"OperationalMessage",Organization:"Organization",OrganizationSection:"OrganizationSection",OrganizationUnit:"OrganizationUnit",OrganizationXArea:"OrganizationXArea",PasswordHistory:"PasswordHistory",PaymentOrder:"PaymentOrder",PaymentOrderDistribution:"PaymentOrderDistribution",PaymentOrderForm:"PaymentOrderForm",PaymentOrderItem:"PaymentOrderItem",PaymentOrderItemService:"PaymentOrderItemService",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",VideoXEntity:"VideoXEntity",WebCustomer:"WebCustomer",WebDashboard:"WebDashboard",WebListView:"WebListView",WebListViewColumn:"WebListViewColumn",WebMenu:"WebMenu",WebProfile:"WebProfile",WebProfileXWebMenu:"WebProfileXWebMenu",WebUserToken:"WebUserToken",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 enumService(translationService,$q,repository){var service={},enumValues={};return service.unit=[{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},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/x-www-form-urlencoded; charset=UTF-8"},data:jQuery.param(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 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",Id:"i",inMemory:"m",EntityName:"n",IsPublicView:"p",Sorting:"s",EntityType:"t",GroupBy:"b"},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","$state","Constants","$sce",function($filter,$q,repository,ngTableParams,translationService,$localStorage,listCompressionService,$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&&"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.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("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.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.Description"))){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)return $sce.trustAsHtml(''+temp+"")}return temp=sanitize(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.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]),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.Id=listSetup.Id,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)),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 console.log(contextId),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:"Description",PropertyType:"enum.PreFix"},{Position:3,Title:translationService.translate("web-webListView-IsPublicView","Felles"),Property:"Description",PropertyType:"string"},{Position:4,Title:translationService.translate("web-webListView-ContextId","Kontekst"),Property:"ContextId",PropertyType:"string"},{Position:5,Title:translationService.translate("web-webListView-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}]};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:return{Sorting:{ClosedDate:"desc"},Filter:{PropertyFilter:[{Property:"ClosedDate",Operator:"<>",Value:null}]},Columns:[{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-User","Fullført av"),Property:"User.RealName",PropertyType:"string"}]};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"}]};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","Epost"),Property:"Email",PropertyType:"string"}]};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:{Description:"asc"},Columns:[{Position:1,Title:translationService.translate("web-conditionType-description","Tilstand"),Property:"Description",PropertyType:"string"},{Position:2,Title:translationService.translate("web-conditionType-IsApproved","Godkjent"),Property:"IsApproved",PropertyType:"bool"},{Position:3,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-Id","ID"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-entityPermissionprofile-description","Description"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-entityPermissionprofile-UpdatedDate","Oppdatert Dato"),Property:"UpdatedDate",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:1,Title:translationService.translate("web-priority-EntityType","Entitetstype"),Property:"EntityType",PropertyType:"enum.prefix"},{Position:2,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.contract.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-contract-Id","Id"),Property:"Id",PropertyType:"string"},{Position:1,Title:translationService.translate("web-contract-Description","Beskrivelse"),Property:"Description",PropertyType:"string"}]};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-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}]};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-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:3,Title:translationService.translate("web-equipmentCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"}]};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-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:3,Title:translationService.translate("web-buildingCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"}]};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-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:3, Title:translationService.translate("web-estateCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"}]};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-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:3,Title:translationService.translate("web-componentCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"}]};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"}]};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-UpdatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"},{Position:3,Title:translationService.translate("web-projectCategory-IsAbstract","Mal"),Property:"IsAbstract",PropertyType:"bool"}]};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","Navn"),Property:"Id",PropertyType:"string"},{Position:2,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","Navn"),Property:"Id",PropertyType:"string"},{Position:2,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-value","Verdi"),Property:"Value",PropertyType:"string"},{Position:2,Title:translationService.translate("web-namedSelection-updatedDate","Oppdatert dato"),Property:"UpdatedDate",PropertyType:"date"}]};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-updateDate","Oppdatert dato","UpdatedDate","date")]};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"}]};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","User1.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.ifcFile.prefix:return{Sorting:{Id:"asc"},Columns:[{Position:1,Title:translationService.translate("web-ifcfile-Id","Id"),Property:"Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-ifcfile-Description","Beskrivelse"),Property:"Description",PropertyType:"string"},{Position:3,Title:translationService.translate("web-ifcfile-building-id","Byggnr."),Property:"Building.Id",PropertyType:"string"},{Position:4,Title:translationService.translate("web-ifcfile-building-description","Byggnavn"),Property:"Building.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"}]};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","User.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",Id:"asc"},Columns:[addColumn(1,"web-scheduledJob-Description","Navn","Description","string"),addColumn(2,"web-scheduledJob-JobType","Type","Type","enum.ScheduledJobType"),addColumn(3,"web-scheduledJob-IsActive","Aktiv","IsActive","bool")]};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:"User.Username",PropertyType:"string"}]};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:{Id:"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:"User.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"}]};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","TranslationService","$q",function(repository,translationService,$q){var publicMember={},createObjects=[];return publicMember.getCreateObjects=function(){return createObjects=[],repository.authService.hasCreateAccess(repository.commonService.prefix.Equipment)&&createObjects.push({text:translationService.translate("shortcut-new-equipment","Anlegg"),state:"equipment.create"}),repository.authService.hasCreateAccess(repository.commonService.prefix.WorkOrder)&&createObjects.push({text:translationService.translate("shortcut-new-workOrder","Arbeidsordre"),state:"workOrder.create"}),repository.authService.hasCreateAccess(repository.commonService.prefix.Building)&&createObjects.push({text:translationService.translate("shortcut-new-building","Bygg"),state:"building.create"}),repository.authService.hasCreateAccess(repository.commonService.prefix.Document)&&createObjects.push({text:translationService.translate("shortcut-new-document","Dokument"),state:"document.create"}),repository.authService.hasCreateAccess(repository.commonService.prefix.Estate)&&createObjects.push({text:translationService.translate("shortcut-new-estate","Eiendom"),state:"estate.create"}),repository.authService.hasCreateAccess(repository.commonService.prefix.Supplier)&&createObjects.push({text:translationService.translate("shortcut-new-supplier","Leverandør"),state:"supplier.create"}),repository.authService.hasCreateAccess(repository.commonService.prefix.Request)&&createObjects.push({text:translationService.translate("shortcut-new-request","Meldinger"),state:"request.create"}),repository.authService.hasCreateAccess(repository.commonService.prefix.PeriodicTask)&&createObjects.push({text:translationService.translate("shortcut-new-periodicTask","Periodisk rutine"),state:"periodicTask.create"}),repository.authService.hasCreateAccess(repository.commonService.prefix.Person)&&createObjects.push({text:translationService.translate("shortcut-new-person","Person"),state:"person.create"}),repository.authService.hasCreateAccess(repository.commonService.prefix.Area)&&createObjects.push({text:translationService.translate("shortcut-new-area","Rom"),state:"area.create"}),createObjects},publicMember.getShortcuts=function(){return repository.getShortcuts()},publicMember}])}(),function(){function moduleService($localStorage){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:"zmdi-block",Core:"zmdi-power",Activity:"zmdi-assignment",Budget:"zmdi-money-box",SparePart:"zmdi-input-power",Document:"zmdi-library",Energy:"zmdi-flash",Area:"zmdi-layers",Cleaning:"zmdi-flower",Key:"zmdi-key",Rent:"zmdi-city",Invoice:"zmdi-receipt",InternalRent:"zmdi-store",Housing:"zmdi-home",DutyLog:"zmdi-shield-security",Alarm:"zmdi-alarm",Deviation:"zmdi-alert-octagon",Mobile:"zmdi-smartphone",Map:"zmdi-map",CleaningWeb:"zmdi-flower-alt",FireManual:"zmdi-fire",HSEManual:"zmdi-local-hospital",ElectroManual:"zmdi-battery-flash",DataAcquisition:"zmdi-download",Booking:"zmdi-hotel",EntityComment:"zmdi-comments",InventoryControl:"zmdi-storage",ExtendedConditionControl:"zmdi-assignment-o",ControlList:"zmdi-format-list-bulleted",Api:"zmdi-share",ProjectManagement:"zmdi-collection-bookmark",EntityLink:"zmdi-link",Sms:"zmdi-smartphone-portrait-lock",IFCBimsyncHosting:"zmdi-camera-alt",DataImport:"zmdi-upload",Elhub:"zmdi-input-power",Brand:"zmdi-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},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]}}}angular.module("Plania").factory("ModuleService",["$localStorage",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 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,service.enableWebNavigation=!1;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="",!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),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;void 0!==result.EnableWebNavigation&&(service.enableWebNavigation=result.EnableWebNavigation),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;void 0!==result.EnableWebNavigation&&(service.enableWebNavigation=result.EnableWebNavigation),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.getSingleWithNoParameter=function(serviceUrl){var deferred=$q.defer(),url=serviceUrl+service.getUrlParameters();return genericRepository.get(url,{}).then(function(apiResponse){var result=apiResponse.data;void 0!==result.EnableWebNavigation&&(service.enableWebNavigation=result.EnableWebNavigation),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"],service.prefillKeyWords=["@LoggedInPerson","@User","@CurrentBuilding","@UserSupplier","@UserCustomer"],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",""))};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;void 0!==result.EnableWebNavigation&&"InternalWeb"!==result.EntityName&&(service.enableWebNavigation=result.EnableWebNavigation),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?(updateAccess({EntityName:result.EntityName,Access:result.Access,AccessOtherDataOwner:result.AccessOtherDataOwner}),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.updateSingleDictionary=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,{"":JSON.stringify(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,useRawBodyParams){var deferred=$q.defer(),url=serviceUrl+service.getUrlParameters();return urlParams&&(url=url+"&"+urlParams),genericRepository.put(url,useRawBodyParams?bodyParameters:{"":bodyParameters}).then(function(apiResponse){var result=apiResponse.data;200===apiResponse.status?"string"==typeof result?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.createSingleDictionary=function(serviceUrl,model,urlParams){validationService.validateModel(model);var dictModel={"":JSON.stringify(model)};return service.createSingle(serviceUrl,dictModel,urlParams)},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+service.getUrlParameters();return 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+service.getUrlParameters()+"&"+urlParams;return 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)};var userMenus=[];return service.getShortcuts=function(){var defer=$q.defer();return service.GetPaginated(service.apiData.userXWebProfile.url,0,100,{Index_position:"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){if(webMenu){var filter={};webMenu.Reference&&(filter=webMenu.Reference.replace(/(\r\n|\n|\r)/gm,"")),children.push({guid:webMenu.Guid,text:webMenu.Name,state:webMenu.Context,isBuildingDependent:webMenu.IsBuildingDependent,params:filter}),service.setMenuParameters(webMenu.Guid,filter,webMenu.IsBuildingDependent)}}),userMenus.push({guid:userWebProfile.WebProfile.Guid,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);$(element).parents().filter(function(){return"auto"===$(this).css("overflow")}).first()[0].scrollTop=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;i0&&menu.children.push(menuItem("web-topMenu-accounting","Dimensjoner","accounting.list")),canRead(repository.commonService.prefix.DocumentCategory)&&hasModule.document&&menu.children.push(menuItem("web-topMenu-documentCategory","Dokumentkategori","documentCategory.list")),canRead(repository.commonService.prefix.DocumentType)&&hasModule.document&&menu.children.push(menuItem("web-topMenu-documentType","Dokumenttype","documentType.list")),canRead(repository.commonService.prefix.Account)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-account","Kontoer","account.list")),canRead(repository.commonService.prefix.CostCenter)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-costCenter","Koststeder","costCenter.list")),canRead(repository.commonService.prefix.CustomerGroup)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-customerGroup","Kundegruppe","customerGroup.list")),canRead(repository.commonService.prefix.CustomerCategory)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-customerCategory","Kundekategori","customerCategory.list")),canRead(repository.commonService.prefix.NamedSelection)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-dropdowns","Nedtrekksfelter","namedSelection.list")),canRead(repository.commonService.prefix.Region)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-region","Områder","region.list")),canRead(repository.commonService.prefix.PersonRole)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-personRole","Personroller","personRole.list")),canRead(repository.commonService.prefix.ReferenceType)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-referenceType","Referanser","referenceType.list")),menu.children=_.sortBy(menu.children,"title"),menu):menu},createTemplatesMenu=function(){var menu=menuItem("web-topMenu-templates","Maler",null,"zmdi-hc-fw zmdi-tab-unselected");return $scope.userInfo.isSystemAdministrator?(canRead(repository.commonService.prefix.Building)&&hasModule.core&&$localStorage.generalOptions.UseBuildingTemplates&&menu.children.push(menuItem("web-topMenu-buildingTemplate","Byggmal","buildingTemplate.list")),canRead(repository.commonService.prefix.PeriodicTask)&&hasModule.activity&&$localStorage.generalOptions.UseBuildingTemplates&&menu.children.push(menuItem("web-topMenu-periodicTaskTemplate","Periodiske malrutiner","periodicTaskTemplate.list")),canRead(repository.commonService.prefix.Project)&&hasModule.projectManagement&&menu.children.push(menuItem("web-topMenu-projectTemplate","Prosjektmaler","projectTemplate.list")),canRead(repository.commonService.prefix.EmailTemplate)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-emailTemplate","Epost-maler","emailTemplate.list")),canRead(repository.commonService.prefix.ControlList)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-controlList","Kontrollister","controlList.list")),canRead(repository.commonService.prefix.PeriodicTask)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-workOrderTemplate","Aktivitetsmaler","workOrderTemplate.list")),menu):menu},createBasicFvdAdminMenu=function(){var menu=menuItem("web-topMenu-basicFDV","Basisdata FDV",null,"zmdi-receipt zmdi-hc-fw");return $scope.userInfo.isSystemAdministrator?(canRead(repository.commonService.prefix.ActivityCategory)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-activityCategory","Aktivitetskategori","activityCategory.list")),canRead(repository.commonService.prefix.ActivityGroup)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-activityGroup","Aktivitetsgrupper","activityGroup.list")),canRead(repository.commonService.prefix.Deviation)&&hasModule.deviation&&menu.children.push(menuItem("web-topMenu-deviationType","Avvikstype","deviationType.list")),canRead(repository.commonService.prefix.PurchaseOrderForm)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-purchaseOrderForm","Bestillingsskjema","purchaseOrderForm.list")),canRead(repository.commonService.prefix.PaymentTerm)&&(hasModule.activity||hasModule.rent||hasModule.internalRent||hasModule.housing||hasModule.invoice)&&menu.children.push(menuItem("web-topMenu-paymentTerm","Betalingsbetingelser","paymentTerm.list")),canRead(repository.commonService.prefix.PaymentOrderForm)&&hasModule.invoice&&menu.children.push(menuItem("web-topMenu-paymentOrderForm","Fakturatyper","paymentOrderForm.list")),canRead(repository.commonService.prefix.InvoicingTerm)&&hasModule.invoice&&menu.children.push(menuItem("web-topMenu-invoicingTerm","Fakturering","invoicingTerm.list")),canRead(repository.commonService.prefix.ContractCategory)&&hasModule.invoice&&menu.children.push(menuItem("web-topMenu-contractCategory","Kontrakt kategori","contractCategory.list")),canRead(repository.commonService.prefix.ContractType)&&hasModule.invoice&&menu.children.push(menuItem("web-topMenu-contractType","Kontrakt type","contractType.list")),canRead(repository.commonService.prefix.Consequence)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-consequence","Konsekvens","consequence.list")),canRead(repository.commonService.prefix.ConsequenceType)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-consequenceType","Konsekvenstype","consequenceType.list")),canRead(repository.commonService.prefix.Priority)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-priority","Prioritet","priority.list")),canRead(repository.commonService.prefix.ProjectCategory)&&hasModule.projectManagement&&menu.children.push(menuItem("web-topMenu-projectCategory","Prosjektkategori","projectCategory.list")),canRead(repository.commonService.prefix.ProjectType)&&hasModule.projectManagement&&menu.children.push(menuItem("web-topMenu-projectType","Prosjekttype","projectType.list")),canRead(repository.commonService.prefix.ResourceGroup)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-resourceGroup","Ressursgrupper","resourceGroup.list")),canRead(repository.commonService.prefix.StandardText)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-standardText","Standardtekster","standardText.list")),canRead(repository.commonService.prefix.CylinderType)&&hasModule.key&&menu.children.push(menuItem("web-topMenu-cylinderType","Sylindertype","cylinderType.list")),canRead(repository.commonService.prefix.ConditionType)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-conditionType","Tilstandstyper","conditionType.list")),canRead(repository.commonService.prefix.HourType)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-hourType","Time typer","hourType.list")),canRead(repository.commonService.prefix.Cause)&&hasModule.activity&&menu.children.push(menuItem("web-topMenu-cause","Årsak","cause.list")),menu.children=_.sortBy(menu.children,"title"),menu):menu},createUserAdministrationMenu=function(){var menu=menuItem("web-topMenu-userAdministration","Brukeradministrasjon",null,"zmdi-accounts zmdi-hc-fw");return $scope.userInfo.isUserAdministrator?(canRead(repository.commonService.prefix.ApiClient)&&hasModule.api&&menu.children.push(menuItem("web-topMenu-apiClient","API klienter","apiClient.list")),canRead(repository.commonService.prefix.User)&&hasModule.core&&(menu.children.push(menuItem("web-topMenu-user","Brukere","user.list")),menu.children.push(menuItem("web-topMenu-usergroup","Brukergrupper","usergroup.list"))),menu.children=_.sortBy(menu.children,function(ch){return ch.title.toLowerCase()}),menu):menu},createUserAdministrationExperienceMenu=function(){var menu=menuItem("web-topMenu-userAdministrationExperience","Brukeropplevelse",null,"zmdi-view-quilt zmdi-hc-fw");return $scope.userInfo.isUserAdministrator?(canRead(repository.commonService.prefix.WebDashboard)&&menu.children.push(menuItem("web-topMenu-dashboard","Dashbord","dashboard.list")),canRead(repository.commonService.prefix.MobileMenuProfile)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-mobileMenuProfile","Mobilmenyprofiler","mobileMenuProfile.list")),canRead(repository.commonService.prefix.EntityLink)&&hasModule.entityLink&&menu.children.push(menuItem("web-topMenu-entityLink","Navigasjonslenker","entityLink.list")),canRead(repository.commonService.prefix.BuildingSelection)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-buildingSelection","Utvalg","buildingSelection.list")),canRead(repository.commonService.prefix.WebMenu)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-webMenu","Webmenyer","webMenu.list")),canRead(repository.commonService.prefix.WebProfile)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-webProfile","Webprofiler","webProfile.list")),hasModule.brand&&menu.children.push(menuItem("web-topMenu-bradning","Administrasjon av merkevare","branding")),menu.children=_.sortBy(menu.children,function(ch){return ch.title.toLowerCase()}),menu):menu},createSystemOperationsMenu=function(){var menu=menuItem("web-topMenu-systemOperation","Systemdrift",null,"zmdi-notifications-none zmdi-hc-fw");return $scope.userInfo.isSystemAdministrator?(canRead(repository.commonService.prefix.ApiRequestLog)&&hasModule.api&&menu.children.push(menuItem("web-topMenu-apiRequestLog","API log","apiRequestLog.list")),(canRead(repository.commonService.prefix.Area)&&hasModule.housing||canRead(repository.commonService.prefix.Customer)&&hasModule.housing||canRead(repository.commonService.prefix.Contract)&&(hasModule.internalRent||hasModule.rent||hasModule.invoice)||canRead(repository.commonService.prefix.Contract)&&hasModule.housing&&$localStorage.generalOptions.ShowContractHousingInWeb)&&menu.children.push(menuItem("web-topMenu-anonymization","Anonymisering av leietakere","customer.anonymizationDashboard")),canRead(repository.commonService.prefix.Document)&&hasModule.document&&menu.children.push(menuItem("web-topMenu-documentArchiveList","Arkivbehandling","documentXEntity.archiveList")),canRead(repository.commonService.prefix.ScheduledJob)&&menu.children.push(menuItem("web-topMenu-scheduledJobs","Bakgrunnsjobber","scheduledJob.list")),menu.children.push(menuItem("web-topMenu-cacheInfo","Cacheoversikt","cacheInfo.list")),canRead(repository.commonService.prefix.ChangeSet)&&menu.children.push(menuItem("web-topMenu-changeSet","Endringssett","changeSet.list")),canRead(repository.commonService.prefix.EntityTask)&&hasModule.entityLink&&menu.children.push(menuItem("web-topMenu-entityTask","Handlinger","entityTask.list")),canRead(repository.commonService.prefix.WebUserToken)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-loggedInUsers","Innloggede brukere","webUserToken.list")),canRead(repository.commonService.prefix.IntegrationData)&&menu.children.push(menuItem("web-topMenu-integrationData","Integrasjonsdata","integrationData.list")),menu.children.push(menuItem("web-topMenu-log","Logg","log.list")),canRead(repository.commonService.prefix.AlarmLog)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-alarmLog","Sendte elementer","alarmLog.list")),canRead(repository.commonService.prefix.DataImport)&&(hasModule.dataAcquisition||hasModule.dataImport)&&menu.children.push(menuItem("web-topMenu-dataImport","Dataimport","dataImport.list")),menu.children=_.sortBy(menu.children,function(ch){return ch.title.toLowerCase()}),menu):menu},createSystemConfigurationAndLicenseMenu=function(){var menu=menuItem("web-topMenu-systemConfigurationAndLicense","Systemkonfigurasjon",null,"zmdi-settings zmdi-hc-fw");return $scope.userInfo.isSystemAdministrator?(canRead(repository.commonService.prefix.FieldInfoOverride)&&menu.children.push(menuItem("web-topMenu-registeredFields","Definering av felter","registeredFields")),canRead(repository.commonService.prefix.DataOwner)&&menu.children.push(menuItem("web-topMenu-dataOwner","Klienter","dataOwner.list")),canRead(repository.commonService.prefix.GeneralOptions)&&hasModule.core&&menu.children.push(menuItem("web-topMenu-generalOptions","Kundeprofil","generalOptions")),canRead(repository.commonService.prefix.LanguageXWebText)&&menu.children.push(menuItem("web-topMenu-translation","Oversettelser","translation.list")),canRead(repository.commonService.prefix.Report)&&menu.children.push(menuItem("web-topMenu-report","Rapporter","report.list")),menu.children.push(menuItem("web-topMenu-planiaSystem","System- og lisensinformasjon","planiasystem.ps")),menu.children=_.sortBy(menu.children,function(ch){return ch.title.toLowerCase()}),menu):menu},createDataInsightMenu=function(){var menu=menuItem("web-topMenu-dataInsight","Innsikt",null,"zmdi-graduation-cap zmdi-hc-fw");return $scope.userInfo.isSystemAdministrator&&hasModule.elhub?(canRead(repository.commonService.prefix.EquipmentOperatingHours)&&menu.children.push(menuItem("web-topMenu-equipmentOperatingHoursDashboard","Forbruk (driftstimer)","equipmentOperatingHours.dashboard")),menu.children=_.sortBy(menu.children,function(ch){return ch.title.toLowerCase()}),menu):menu},createMapMenu=function(){var menu=menuItem("web-topMenu-map","Kart",null,"zmdi-map");return hasModule.map&&menu.children.push(menuItem("web-topMenu-map","Vis kart","map.view","zmdi-pin zmdi-hc-fw")),menu},createAdminMenu=function(){var menu=menuItem("web-topMenu-admin","Admin",null,"zmdi-settings"),basicDataAdminMenu=createBasicDataAdminMenu();basicDataAdminMenu.children.length&&menu.children.push(basicDataAdminMenu);var basicFvdAdminMenu=createBasicFvdAdminMenu();basicFvdAdminMenu.children.length&&menu.children.push(basicFvdAdminMenu);var userAdministrationMenu=createUserAdministrationMenu();userAdministrationMenu.children.length&&menu.children.push(userAdministrationMenu);var userAdministrationExperienceMenu=createUserAdministrationExperienceMenu();userAdministrationExperienceMenu.children.length&&menu.children.push(userAdministrationExperienceMenu);var templatesAdminMenu=createTemplatesMenu();templatesAdminMenu.children.length&&menu.children.push(templatesAdminMenu) ;var systemOperationsMenu=createSystemOperationsMenu();systemOperationsMenu.children.length&&menu.children.push(systemOperationsMenu);var systemConfigurationAndLicenseMenu=createSystemConfigurationAndLicenseMenu();systemConfigurationAndLicenseMenu.children.length&&menu.children.push(systemConfigurationAndLicenseMenu);var dataInsightMenu=createDataInsightMenu();return dataInsightMenu.children.length&&menu.children.push(dataInsightMenu),menu},updateMenu=function(){index=0;var mainMenu=[],basicMenu=createBasicMenu(),maintenanceMenu=createMaintenanceMenu(),managementMenu=createManagementMenu(),cleaningMenu=createCleaningMenu(),mapMenu=createMapMenu(),adminMenu=createAdminMenu();basicMenu.children.length&&mainMenu.push(basicMenu),maintenanceMenu.children.length&&mainMenu.push(maintenanceMenu),managementMenu.children.length&&mainMenu.push(managementMenu),cleaningMenu.children.length&&mainMenu.push(cleaningMenu),mapMenu.children.length&&mainMenu.push(mapMenu),($scope.userInfo.isSystemAdministrator||$scope.userInfo.isUserAdministrator)&&adminMenu.children.length&&mainMenu.push(adminMenu),$scope.mainMenu=mainMenu};updateMenu(),$scope.clickSidebarItem=function(event,menuItem){$scope.mainctrl&&$scope.mainctrl.sidebarStat&&$scope.mainctrl.sidebarStat(event);var state=_.find(states.list,function(state){return state.name===menuItem.sref});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}},$scope.$on($scope.events.updateMenu,function(){$scope.guidDataOwner=commonService.getFilterData().selectedDataOwner.Guid,$scope.hasImageLogo=!!$localStorage.generalOptions.GuidImageLogo||commonService.getFilterData().selectedDataOwner.GuidImageLogo,updateAccess()})}angular.module("Plania").controller("SidebarController",["$scope","Repository","$localStorage","$rootScope","TranslationService","states","CommonService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,$rootScope){$scope.model={};var routeEntity="";routeEntity=$scope.navigation.current.name.indexOf(".edit")>-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.propertyLabels={Id:{systemName:"web-"+routeEntity+"-id",defaultName:"Id"}};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.updateSingleDictionary(repository.apiData[routeEntity].url,$scope.model).then(success,error):repository.createSingleDictionary(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}),$scope.itemTable=new ngTableParams({page:1,count:10,sorting:modalParams.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)},$scope.createEntity=function(){if(!$scope.createHandler)return!1;var templateUrl=$scope.createHandler.templateUrl,controller=$scope.createHandler.controller?$scope.createHandler.controller:$scope.onType.capitalizeFirstLetter()+"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,$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,authService,repository,$timeout,signalR){$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=response.Data.DoesCleaningTasks,$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.updateSingleDictionary(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})},$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,null,JSON.stringify({Guid: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","authService","Repository","$timeout","SignalR",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},{Property:"Deactivated",Operator:"=",Value:"0"}]}},{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"];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.updateSingleDictionary(repository.apiData.component.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(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:{PropertyFilter:[{Property:"IsTemplate",Operator:"=",Value:!1}]}}}}}).result.then(function(equipmentGuids){var model=[];equipmentGuids.forEach(function(guid){model.push({GuidEquipment:guid,GuidComponent:$scope.model.Guid})}),repository.createMultipleWithGuid(repository.apiData.componentEquipment.url,$scope.model.Guid,JSON.stringify(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:{}}}}}).result.then(function(areaGuids){var model=[];areaGuids.forEach(function(guid){model.push({GuidArea:guid,GuidComponent:$scope.model.Guid})}),repository.createMultipleWithGuid(repository.apiData.componentArea.url,$scope.model.Guid,JSON.stringify(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.updateSingleDictionary(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.$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.createMultipleWithGuid(repository.apiData.componentEquipment.url,$scope.model.Guid,JSON.stringify(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,$scope.deliveryTimeUnits=[{text:"Ingen",value:-1},{text:"Dag",value:0},{text:"Uke",value:1},{text:"Måned",value:2},{text:"År",value:3},{text:"Timer",value:7}],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;var selectedDeliveryTimeUnit=_.filter($scope.deliveryTimeUnits,{value:$scope.model.DeliveryTimePeriodUnit});selectedDeliveryTimeUnit.length>0&&($scope.selectedDeliveryTimeUnit=selectedDeliveryTimeUnit[0]),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")})}else $scope.model={GuidComponent:params.guidComponent},$scope.selectedDeliveryTimeUnit=$scope.deliveryTimeUnits[0],setTimeout(function(){$scope.activateAutocomplete=!0},250);$scope.saveAction=function(){$scope.selectedDeliveryTimeUnit&&($scope.model.DeliveryTimePeriodUnit=$scope.selectedDeliveryTimeUnit.value),$scope.isUpdate?repository.updateSingleDictionary(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.createSingleDictionary(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.updateSingleDictionary(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.updateSingleDictionary(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,JSON.stringify(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,null,!0).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){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,$scope.model.RequestAction="Close",repository.updateSingleDictionary(repository.apiData.condition.url,$scope.model).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.model.RequestAction=null})},$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=["Description","LikertScale"];repository.GetPaginated(repository.apiData.conditionType.url,0,-1,{Description:"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","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"];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.Description",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.updateSingleDictionary(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.LikertScale","ConditionType.Description","Consequence.Id","Consequence.LikertScale","ConsequenceType.Id","ConstructionType.Id","Priority.Description","UserCreatedBy.RealName","UserUpdatedBy.RealName","WorkOrder1.Id","WorkOrder1.Description","WorkOrder1.DueDate","WorkOrder1.GuidProject","WorkOrder1.EndDate","WorkOrder1.Status","WorkOrder1.GuidPeriodicTask","WorkOrder1.Project.Id","WorkOrder1.Project.Description","WorkOrder2.Id","WorkOrder2.Description","WorkOrder2.DueDate","WorkOrder2.GuidProject","WorkOrder2.EndDate","WorkOrder2.Status","WorkOrder2.GuidPeriodicTask","WorkOrder2.Project.Id","WorkOrder2.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.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,getCondition()):(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,getCondition()):$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.updateSingleDictionary(repository.apiData.condition.url,$scope.model).then(success,error):repository.createSingleDictionary(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&&repository.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.WorkOrder1&&$scope.model.WorkOrder1.GuidProject&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("project.edit",{guid:$scope.model.WorkOrder1.GuidProject}),translationService.translate("web-condition-originContextMenu-viewInspectionProject","Gå til prosjekt"))),$scope.hasReadAccess("PeriodicTask")&&$scope.model.GuidInspectionWorkOrder&&$scope.model.WorkOrder1&&$scope.model.WorkOrder1.GuidPeriodicTask&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:$scope.model.WorkOrder1.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.WorkOrder2&&!$scope.model.WorkOrder2.EndDate&&$scope.canCloseCorrectiveAction($scope.model,$scope.model.GuidCorrectiveWorkOrder)&&options.push({html:' '+translationService.translate("web-condition-followUpContextMenu-closeCorrectiveActionFromCorrective","Lukk tiltak via")+" "+$scope.model.WorkOrder2.Caption+"",click:function($itemScope,$event,modelValue,text,$li){$scope.closeCorrectiveAction()}}),$scope.hasEditAccess("Condition")&&!$scope.model.GuidCorrectiveWorkOrder&&$scope.model.GuidInspectionWorkOrder&&$scope.model.WorkOrder1&&!$scope.model.WorkOrder1.EndDate&&$scope.canCloseCorrectiveAction($scope.model,$scope.model.GuidInspectionWorkOrder)&&options.push({html:' '+translationService.translate("web-condition-followUpContextMenu-closeCorrectiveActionFromInspection","Lukk tiltak via")+" "+$scope.model.WorkOrder1.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&&repository.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.WorkOrder2&&$scope.model.WorkOrder2.GuidProject&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("project.edit",{guid:$scope.model.WorkOrder2.GuidProject}),translationService.translate("web-condition-followUpContextMenu-viewCorrectiveProject","Gå til prosjekt"))),$scope.hasReadAccess("PeriodicTask")&&$scope.model.GuidCorrectiveWorkOrder&&$scope.model.WorkOrder2&&$scope.model.WorkOrder2.GuidPeriodicTask&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:$scope.model.WorkOrder2.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.WorkOrder2.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,workOrder.estate=$scope.model.Estate.Caption),$scope.model.GuidBuilding&&(workOrder.guidBuilding=$scope.model.GuidBuilding,workOrder.building=$scope.model.Building.Caption),$scope.model.GuidEquipment&&(workOrder.guidEquipment=$scope.model.GuidEquipment,workOrder.equipment=$scope.model.Equipment.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()})}angular.module("Plania").controller("ConditionController",["$scope","Repository","$stateParams","$modalInstance","$localStorage","TranslationService","$modal","$rootScope","ngTableParams","ListService","Constants","$q","RegisteredFieldService",controller])}(),function(){function controller($scope,$modal,ngTableParams,repository,$rootScope,translationService,$localStorage,listService,constants,$q,commonService){var isSVV="10088"===$localStorage.generalOptions.CustomerId||"12258"===$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-description"),Property:"ConditionType.Description",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.Condition1&&!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)};repository.GetPaginated(repository.apiData.webListView.url,0,10,{},{Prefix:repository.apiData.condition.prefix,ContextId:contextId}).then(function(result){if(result.List.length>0){var guidCurrentDataOwner=commonService.getFilterData().selectedDataOwner.Guid,webListCurrentDataOwner=_.find(result.List,function(x){return x.GuidDataOwner===guidCurrentDataOwner});!webListCurrentDataOwner&&hasAccessToCreateNewWebList()?repository.createSingle(repository.apiData.webListView.url,$scope.defaultListSetup).then(function(result){$scope.defaultListSetup.Guid=result}):$scope.defaultListSetup=webListCurrentDataOwner||result.List[0]}getTable()});var getTable=function(){$scope.conditionTable=new ngTableParams({page:1,count:10,sorting:{Id:"desc"}},{total:0,counts:[5,10,20],filterDelay:50,paginationMaxBlocks:$scope.useList?6:8,getData:function($defer,params){$scope.conditionTable.filter().PropertyFilter||($scope.conditionTable.filter().PropertyFilter=[{Property:"Guid"+$scope.parentEntity,Operator:"=",Value:$scope.guid}],"WorkOrder"===$scope.parentEntity&&$scope.conditionTable.filter().PropertyFilter.push({Operand:"or",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"),$scope.conditions)for(;$scope.conditions.length>0;)$scope.conditions.pop();repository.GetPaginated(repository.apiData.condition.url,params.page()-1,params.count(),params.sorting(),params.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=["Description","IsApproved"];repository.GetPaginated(repository.apiData.conditionType.url,0,20,{Description:"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?"zmdi-settings c-bluegray":deviation.Area?"zmdi-layers c-lightblue":deviation.Building?"zmdi-balance c-brown":deviation.Estate?"zmdi-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&&($scope.conditionTable.reload(),swal(nrOfCalls-nrSuccessCalls+" "+translationService.translate("web-condition-approveSelectedConditions-failed","ble ikke satt som standardtilstand"),_.uniq(errors).join("\r\n"),"error"))},function(error){nrOfCalls++,errors.push(error),nrOfCalls===$scope.selectedConditions.length&&errors.length>0&&($scope.conditionTable.reload(),swal(nrOfCalls-nrSuccessCalls+" "+translationService.translate("web-condition-approveSelectedConditions-failed","ble ikke satt som standardtilstand"),_.uniq(errors).join("\r\n"),"error"))})}},$scope.deleteSelectedConditions=function(){var notDeletedConditions=[];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(){$scope.selectedConditions.forEach(function(condition){var fullCondition=_.find($scope.conditionTable.data,{Guid:condition});fullCondition.Condition1||fullCondition.ActionComment?notDeletedConditions.push(fullCondition):deleteCondition({Guid:condition})}),$scope.selectedConditions.length===notDeletedConditions.length&&swal("Kunne ikke slette tilstandene","Ikke slettet: "+_.map(notDeletedConditions,"Id"),"info")});var nrSuccessCalls=0,deleteCondition=function(condition){repository.deleteSingle(repository.apiData.condition.url,condition.Guid).then(function(result){nrSuccessCalls++,nrSuccessCalls===$scope.selectedConditions.length?(swal(translationService.translate("web-swal-conditions-delete-success","Tilstandene ble slettet!"),"","success"),$scope.selectedConditions=[],$scope.conditionTable.reload()):nrSuccessCalls>0?(swal("Kunne ikke slette alle tilstandene","Ikke slettet: "+_.map(notDeletedConditions,"Id"),"info"),$scope.selectedConditions=_.map(notDeletedConditions,"Guid"),$scope.conditionTable.reload()):swal("Kunne ikke slette tilstandene","Ikke slettet: "+_.map(notDeletedConditions,"Id"),"danger")})}},$scope.remove=function(condition){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-equipment-message","Anlegget vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-equipment-button-confirm","Ja, fjern anlegget!"),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-equipment-success","Anlegget 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="10088"===$localStorage.generalOptions.CustomerId||"12258"===$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:[]};return params.guidBuilding?filter.PropertyFilter.push({Property:"GuidBuilding",Operator:"=",Value:params.guidBuilding}):params.guidEstate&&filter.PropertyFilter.push({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: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:"Undefined"};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.createMultipleWithGuid(repository.apiData.condition.url,params.guidWorkOrder,JSON.stringify(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.updateSingleDictionary(repository.apiData.conditionType.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(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()})}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.updateSingleDictionary(repository.apiData.consequence.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(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()})}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.updateSingleDictionary(repository.apiData.contactPerson.url,$scope.model).then(function(result){repository.growl("Kontakt har blitt oppdatert","success"),$modalInstance.close()}):repository.createSingleDictionary(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:"GUID_CONTRACT",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.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),"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.updateSingleDictionary(repository.apiData.contract.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(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.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.updateSingleDictionary(repository.apiData.contractItem.url,$scope.model).then(success,error):repository.createSingleDictionary(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.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","ContractAdjustment1.ExplanatoryText","ContractAdjustment1.PeriodicityNumber","ContractAdjustment1.PeriodicityUnit","ContractAdjustment1.AdjustmentDate","ContractAdjustment1.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.updateSingleDictionary(repository.apiData.contract.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(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.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.updateSingleDictionary(repository.apiData.contractCategory.url,$scope.model).then(success,error):repository.createSingleDictionary(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.updateSingleDictionary(repository.apiData.contractType.url,$scope.model).then(success,error):repository.createSingleDictionary(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="10088"===$localStorage.generalOptions.CustomerId||"12258"===$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={PropertyFilter:[{Property:"UseWithArea",Operator:"=",Value:"true"},{Operand:"OR",Property:"UseWithWorkOrder",Operator:"=",Value:"true"},{Operand:"OR",Property:"UseWithEquipment",Operator:"=",Value:"true"}]};$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.createSingleDictionary(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){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="10088"===$localStorage.generalOptions.CustomerId||"12258"===$localStorage.generalOptions.CustomerId;$scope.isBBY=$localStorage.generalOptions.IsBBY;var answerColumns=["Value","ValueInt","ValueDate","ValueBool","ValueString","ValueDouble","User.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=repository.enableWebNavigation,$scope.equipmentNavigationState=repository.apiData.equipment.navigationState,$scope.housingNavigationState=repository.apiData.housing.navigationState,$scope.areaNavigationState=repository.apiData.area.navigationState,$scope.forms={},$scope.activeTabs={controlListItems:!0,images:!1,notExecutedInfo:!1},$scope.isPreview=params.isPreview,$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.User?item.User.RealName:"Server",$scope.lastUpdatedDate=item.UpdatedDate):($scope.lastUpdatedBy=item.User?item.User.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(JSON.stringify(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.updateSingleDictionary(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.updateSingleDictionary(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.updateSingleDictionary(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.PropertyFilter=[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null,Operand:"OR"},{Property:"GuidReferenceType",Operator:"=",Value:$scope.controlListXEntity.ControlList.GuidReferenceTypeNotExecuted}],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 onIsDefaultChange=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.Image&&(imgXEntity.Image.IsDefault=image.IsDefault))}),$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,onIsDefaultChange:onIsDefaultChange}}}}).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",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,translationService,$location,$timeout){$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.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.updateSingleDictionary(repository.apiData.controlList.url,modelCopy).then(success).catch(error):repository.createSingleDictionary(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:"lg",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.updateSingleDictionary(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.createSingleDictionary(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&&swal({title:translationService.translate("web-controlList-publishDraft-title","Vil du publisere utkastet?"),text:translationService.translate("web-controlList-publishDraft-text","Utkastet vil bli tilgjengelig til bruk."),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-controlList-publishDraft-confirm","Ja"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){var dto={Guid:$scope.model.Guid,GuidDataOwner:$scope.model.GuidDataOwner,UpdatedDate:$scope.model.UpdatedDate,GuidUserUpdatedBy:$scope.model.GuidUserUpdatedBy,CreationDate:$scope.model.CreationDate,GuidUserCreatedBy:$scope.model.GuidUserCreatedBy,GuidMasterRecord:$scope.model.GuidMasterRecord,IsCurrentVersion:$scope.model.IsCurrentVersion,Version:$scope.model.Version,GuidPreviousVersion:$scope.model.GuidPreviousVersion,GuidDraftVersion:$scope.model.GuidDraftVersion,Id:$scope.model.Id,Description:$scope.model.Description,Name:$scope.model.Name,IsMandatory:$scope.model.IsMandatory,UseImage:$scope.model.UseImage,Color:$scope.model.Color,Icon:$scope.model.Icon,UseWithArea:$scope.model.UseWithArea,UseWithEquipment:$scope.model.UseWithEquipment,UseWithWorkOrder:$scope.model.UseWithWorkOrder,Conditions:$scope.model.Conditions,IsDeactivated:$scope.model.IsDeactivated,VersionStatus:$scope.model.VersionStatus,VersionComment:$scope.model.VersionComment,GuidReferenceTypeNotExecuted:$scope.model.GuidReferenceTypeNotExecuted};repository.runAction(repository.apiData.controlList.endpoint.publish+$scope.model.Guid,dto,null,!0).then(function(response){repository.growl(translationService.translate("web-controlList-publishDraft-success","Utkastet er publisert"),"success"),$scope.goBack("controlList.edit",{guid:$scope.model.Guid}),swal.close()},function(error){repository.showError(error),swal.close()})})},$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",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},$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,ngTableParams,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.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.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()}]}:{};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(JSON.stringify(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.ImageXEntity=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","ngTableParams","$modalInstance","TranslationService","$localStorage",controller])}(),function(){function controller($scope,$modal,ngTableParams,repository,$rootScope,translationService,$localStorage,signalR,$timeout){$scope.controlListsIsLoading=!1,$scope.addingControlListSignalR=!1,$scope.search={},$scope.isSVV="10088"===$localStorage.generalOptions.CustomerId||"12258"===$localStorage.generalOptions.CustomerId,$scope.isBBY=$localStorage.generalOptions.IsBBY,$scope.customization=$rootScope.customization,$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){if($scope.reload&&!0===$scope.reload){$scope.controlListTable.filter().PropertyFilter?$scope.controlListTable.filter().PropertyFilter.push({Property:"Guid"+$scope.parentEntity,Operator:"=",Value:$scope.guid}):$scope.controlListTable.filter().PropertyFilter=[{Property:"Guid"+$scope.parentEntity,Operator:"=",Value:$scope.guid}],"Area"!==$scope.parentEntity&&"Equipment"!==$scope.parentEntity||$scope.controlListTable.filter().PropertyFilter.push({Property:"GuidWorkOrder",Operator:"<>",Value:null}),$scope.controlListTable.filter().ExcludeSelectionFilter=!0,$scope.controlListTable.reload(),$scope.reload=!1}}),$scope.columns=[{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-controllist-ismandatory"),Property:"ControlList.IsMandatory",PropertyType:"bool"},{Position:10,Title:translationService.translate("web-controllist-id"),Property:"ControlList.Id",PropertyType:"string"},{Position:10,Title:translationService.translate("web-controllist-description"),Property:"ControlList.Description",PropertyType:"string"},{Position:10,Title:translationService.translate("web-controllist-name"),Property:"ControlList.Name",PropertyType:"string"},{Position:10,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?"zmdi-settings c-bluegray":controlList.Area?"zmdi-layers c-lightblue":controlList.Building?"zmdi-balance c-brown":controlList.Estate?"zmdi-city c-teal":void 0};var sorting={ClosedDate:"asc","Area.Id":"asc","Equipment.Id":"asc",CreationDate:"desc"};$scope.controlListTable=new ngTableParams({page:1,count:5,sorting:sorting},{total:0,counts:[5,10,20],filterDelay:50,paginationMaxBlocks:6,getData:function($defer,params){if($scope.controlListTable.filter().PropertyFilter&&_.find($scope.controlListTable.filter().PropertyFilter,function(filter){return-1!==filter.Property.indexOf("Guid")})){$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("User.RealName"), columns.push("User1.RealName"),columns.push("WorkOrder.Id","WorkOrder.Description"),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"),"12235"===$localStorage.generalOptions.CustomerId&&columns.push("Equipment.AlternateId"),"Area"!==$scope.parentEntity&&"Equipment"!==$scope.parentEntity||columns.push("WorkOrder.EndDate","WorkOrder.Stage"),repository.GetPaginated(repository.apiData.controlListXEntity.url,params.page()-1,params.count(),params.sorting(),params.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){$scope.controlLists.push(controlList)}),$defer.resolve(result.List)},function(error){$scope.controlListsIsLoading=!1,repository.growl(error,"danger")})}}});var filterTypes=[{value:"all",name:translationService.translate("web-controlListXEntity-filterType-all","Alle")},{value:"new",name:translationService.translate("web-controlListXEntity-filterType-new","Nye")},{value:"active",name:translationService.translate("web-controlListXEntity-filterType-open","Aktive")},{value:"completed",name:translationService.translate("web-controlListXEntity-filterType-completed","Fullførte")}];$scope.setFilter=function(filterType){$scope.selectedFilterName=_.find(filterTypes,{value:filterType}).name,$localStorage.selectedControlListXEntityFilterType=filterType;var existingStatusFilterIndex=_.findIndex($scope.controlListTable.filter().PropertyFilter,function(o){return"Status"===o.Property});existingStatusFilterIndex>-1&&$scope.controlListTable.filter().PropertyFilter.splice(existingStatusFilterIndex,1);var propertyFilter=$scope.controlListTable.filter().PropertyFilter;switch(filterType){case"all":break;case"new":propertyFilter?propertyFilter.push({Property:"Status",Operator:"=",Value:"0"}):$scope.controlListTable.filter().PropertyFilter=[{Property:"Status",Operator:"=",Value:"0"}];break;case"active":propertyFilter?propertyFilter.push({Property:"Status",Operator:"=",Value:"1"}):$scope.controlListTable.filter().PropertyFilter=[{Property:"Status",Operator:"=",Value:"1"}];break;case"completed":propertyFilter?propertyFilter.push({Property:"Status",Operator:"=",Value:"2"}):$scope.controlListTable.filter().PropertyFilter=[{Property:"Status",Operator:"=",Value:"2"}]}},$localStorage.selectedControlListXEntityFilterType?($scope.selectedFilterName=_.find(filterTypes,{value:$localStorage.selectedControlListXEntityFilterType}).name,$scope.setFilter($localStorage.selectedControlListXEntityFilterType)):$scope.selectedFilterName=_.find(filterTypes,{value:"all"}).name,$scope.create=function(){$modal.open({templateUrl:"app/controlList/views/addControlListModal.html",controller:"AddControlListModalController",size:"lg",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:"lg",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","$localStorage","SignalR","$timeout",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.updateSingleDictionary:repository.createSingleDictionary)(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],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(JSON.stringify(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,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.selectedRequestDto={},$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(JSON.stringify(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.ImageXEntity=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.zmdi");icon.hasClass("zmdi-chevron-up")?(icon.removeClass("zmdi-chevron-up"),icon.addClass("zmdi-chevron-down")):(icon.addClass("zmdi-chevron-up"),icon.removeClass("zmdi-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","User.RealName"],getData=function(){$scope.controlListTable=new ngTableParams({page:1,count:10,sorting:{"WorkOrder.DueDate":"desc"},filter:{PropertyFilter:[{Property:"WorkOrder.StartDate",Operator:"<=",Value:moment().endOf("day").toISOString()},{Operand:"OR",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:"lg",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,ngTableParams,repository,translationService,$rootScope,listService,$timeout,$modal){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasModule=$rootScope.hasModule,$scope.controlListItemAnswersSearch={focus:!1,toggle:!1},$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)});var filterTypes=[{value:"current",name:translationService.translate("web-controlList-answersTab-controlListItemAnswers-current","Gjeldende")},{value:"all",name:translationService.translate("web-controlList-answersTab-controlListItemAnswers-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.controlListItemAnswers.reload())};var sorting={"ControlListItem.Name":"asc"};$scope.controlListItemAnswersColumns=[{Position:1,Title:translationService.translate("web-controlList-answerTab-workOrder-caption","Arbeidsordre"),Property:"ControlListXEntity.WorkOrder.Id",PropertyType:"string",isCaption:!0},{Position:2,Title:translationService.translate("web-controlList-answerTab-relatedEntity-caption","Tilknyttet objekt"),PropertyType:"string",isComplex:!0,SortingDisabled:!0},{Position:3,Title:translationService.translate("web-controlList-answerTab-controlListItem-name","Kontrollpunkt"),Property:"ControlListItem.Name",PropertyType:"string"},{Position:4,Title:translationService.translate("web-controlList-answerTab-controlListItemAnswer-value","Svar"),Property:"Value",PropertyType:"string"},{Position:5,Title:translationService.translate("web-controlList-answerTab-controlList-version","Versjon"),Property:"ControlListXEntity.ControlList.Version",PropertyType:"string"}],$scope.isUpdate&&($scope.controlListItemAnswers=new ngTableParams({page:1,count:10,sorting:sorting},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[],filter={};switch($scope.controlListItemAnswersColumns.forEach(function(col){col.Property&&columns.push(col.Property)}),columns.push("ControlListXEntity.WorkOrder.Description"),columns.push("ControlListXEntity.GuidWorkOrder"),columns.push("ControlListXEntity.GuidArea"),columns.push("ControlListXEntity.Area.Id"),columns.push("ControlListXEntity.Area.Description"),columns.push("ControlListXEntity.Area.IsHousing"),columns.push("ControlListXEntity.GuidEquipment"),columns.push("ControlListXEntity.Equipment.Id"),columns.push("ControlListXEntity.Equipment.Description"),columns.push("ControlListXEntity.GuidPeriodicTask"),columns.push("ControlListXEntity.PeriodicTask.Id"),columns.push("ControlListXEntity.PeriodicTask.Description"),$scope.currentSelectedFilterType.value){case"current":filter.PropertyFilter=[{Property:"ControlListXEntity.GuidControlList",Operator:"=",Value:$scope.model.Guid}];break;case"all":$scope.model.GuidMasterRecord?filter.PropertyFilter=[{Property:"ControlListXEntity.ControlList.GuidMasterRecord",Operator:"=",Value:$scope.model.GuidMasterRecord}]:filter.PropertyFilter=[{Property:"ControlListXEntity.GuidControlList",Operator:"=",Value:$scope.model.Guid}];break;default:filter.PropertyFilter=[{Property:"ControlListXEntity.GuidControlList",Operator:"=",Value:$scope.model.Guid}]}repository.GetPaginated(repository.apiData.controlListItemAnswer.url,params.page()-1,params.count(),params.sorting(),filter,"",JSON.stringify(columns)).then(function(result){$scope.controlListItemAnswers.settings().total=result.TotalCount,$scope.controlListItemAnswers.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})),$scope.openControlList=function(item){$modal.open({templateUrl:"app/controlList/views/controlListCompletionModal.html",size:"lg",controller:"ControlListCompletionModalController",resolve:{params:function(){return{workOrderCaption:item.WorkOrder.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.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.ControlListXEntity)}}),$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};var getLowestEntityCaption=function(entity){return entity.ControlListXEntity.Equipment?entity.ControlListXEntity.Equipment.Caption:entity.ControlListXEntity.Area?entity.ControlListXEntity.Area.Caption:entity.ControlListXEntity.PeriodicTask?translationService.translate("web-controlListXEntity-directConnectionPeriodicTask","Direkte tilkoblet rutine"):translationService.translate("web-controlListXEntity-directConnectionWorkOrder","Direkte tilkoblet arbeidsordre")},getEntityIcon=function(entity){return entity.ControlListXEntity.Equipment?"zmdi-settings c-bluegray":entity.ControlListXEntity.Area?"zmdi-layers c-lightblue":void 0};$scope.getPropertyValue=function(item,column){if(column.isComplex){return""+(' ')+(""+getLowestEntityCaption(item)+"")+""}if(column.isCaption){var newColumn={Position:column.Position,Property:column.Property.replace(".Id",".Caption"),PropertyType:column.PropertyType,Title:column.Title};return listService.GetPropertyValue(item,newColumn)}return listService.GetPropertyValue(item,column)}}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","ngTableParams","Repository","TranslationService","$rootScope","ListService","$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;var filter={PropertyFilter:[{Property:"GuidPeriodicTask",Operator:"<>",Value:null},{Property:"GuidControlList",Operator:"=",Value:$scope.model.Guid},{Property:"PeriodicTask.IsDeactivated",Operator:"=",Value:!1}]};$scope.controlListXEntityColumns=[{Position:1,Title:"Periodisk rutine",Property:"PeriodicTask.Id",PropertyType:"string",isCaption:!0},{Position:2,Title:"Eiendom",Property:"PeriodicTask.Estate.Id",PropertyType:"string",isCaption:!0},{Position:3,Title:"Bygg",Property:"PeriodicTask.Building.Id",PropertyType:"string",isCaption:!0},{Position:4,Title:"Tilknyttet objekt",PropertyType:"string",isComplex:!0,SortingDisabled:!0},{Position:5,Title:"Forfallsdato",Property:"PeriodicTask.DueDate",PropertyType:"date"},{Position:6,Title:"Sist utført",Property:"PeriodicTask.LastExecutedDate",PropertyType:"date"}],$scope.isUpdate&&($scope.controlListXEntityTable=new ngTableParams({page:1,count:10,sorting:{"PeriodicTask.Id":"desc"},filter:filter},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];$scope.controlListXEntityColumns.forEach(function(col){col.Property&&columns.push(col.Property)}),columns.push("PeriodicTask.Description"),columns.push("PeriodicTask.GuidBuilding"),columns.push("PeriodicTask.GuidEstate"),columns.push("Equipment.Id"),columns.push("Equipment.Description"),columns.push("Area.Id"),columns.push("Area.Description"),columns.push("Area.IsHousing"),columns.push("PeriodicTask.Building.Description"),columns.push("PeriodicTask.Estate.Description"),repository.GetPaginated(repository.apiData.controlListXEntity.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.controlListXEntityTable.settings().total=result.TotalCount,$scope.controlListXEntityTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}));var getEntityIcon=function(entity){return entity.Equipment?"zmdi-settings c-bluegray":entity.Area?"zmdi-layers c-lightblue":void 0},getLowestEntityCaption=function(entity){return entity.Equipment?entity.Equipment.Caption:entity.Area?entity.Area.Caption:entity.PeriodicTask?translationService.translate("web-controlListXEntity-directConnectionPeriodicTask","Direkte tilkoblet rutine"):translationService.translate("web-controlListXEntity-directConnectionWorkOrder","Direkte tilkoblet arbeidsordre")};$scope.getPropertyValue=function(item,column){if(column.isComplex){return""+(' ')+(""+getLowestEntityCaption(item)+"")+""}if(column.isCaption){var newColumn={Position:column.Position,Property:column.Property.replace(".Id",".Caption"),PropertyType:column.PropertyType,Title:column.Title};return listService.GetPropertyValue(item,newColumn)}return listService.GetPropertyValue(item,column)},$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.controlListXEntityTable.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.controlListXEntityTable.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})}}}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)});var filterTypes=[{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.currentSelectedFilterType=filterTypes[0],$scope.setFilter=function(filterTypeValue){var selectedFilterType=_.find(filterTypes,{value:filterTypeValue});selectedFilterType&&filterTypeValue!==$scope.currentSelectedFilterType.value&&($scope.currentSelectedFilterType=selectedFilterType,$scope.controlListXEntityTable.reload())},$scope.controlListXEntityColumns=[{Position:1,Title:translationService.translate("web-controlList-historyTab-workOrder-caption","Arbeidsordre"),Property:"WorkOrder.Id",PropertyType:"string",isCaption:!0},{Position:2,Title:translationService.translate("web-controlList-historyTab-relatedEntity-caption","Tilknyttet objekt"),PropertyType:"string",isComplex:!0,SortingDisabled:!0},{Position:3,Title:translationService.translate("web-controlList-historyTab-status","Status"),Property:"Status",PropertyType:"enum.ControlListXEntityStatus"},{Position:4,Title:translationService.translate("web-controlList-historyTab-user-realName","Fullført av"),Property:"User.RealName",PropertyType:"string"},{Position:5,Title:translationService.translate("web-controlList-historyTab-controlListXEntity-closedDate","Fullført"),Property:"ClosedDate",PropertyType:"date"},{Position:6,Title:translationService.translate("web-controlList-historyTab-controlList-version","Versjon"),Property:"ControlList.Version",PropertyType:"string"}],$scope.isUpdate&&($scope.controlListXEntityTable=new ngTableParams({page:1,count:10,sorting:{ClosedDate:"desc"},filter:{PropertyFilter:[{Property:"ControlList.GuidMasterRecord",Operator:"=",Value:$scope.model.Guid,Operand:"OR"},{Property:"ControlList.Guid",Operator:"=",Value:$scope.model.Guid,Operand:"OR"}]}},{total:0,counts:[10,20,50],filterDelay:10,getData:function($defer,params){var columns=[];$scope.controlListXEntityColumns.forEach(function(col){col.Property&&columns.push(col.Property)}),columns.push("WorkOrder.Description"),columns.push("Equipment.Id"),columns.push("Equipment.Description"),columns.push("Area.Id"),columns.push("Area.Description"),columns.push("Area.IsHousing"),columns.push("PeriodicTask.Id"),columns.push("PeriodicTask.Description");var filter=angular.copy(params.filter());switch($scope.currentSelectedFilterType.value){case"all":break;case"new":filter.PropertyFilter.push({Property:"Status",Operator:"=",Value:"0"});break;case"active":filter.PropertyFilter.push({Property:"Status",Operator:"=",Value:"1"});break;case"completed":filter.PropertyFilter.push({Property:"Status",Operator:"=",Value:"2"});break;case"notexecuted":filter.PropertyFilter.push({Property:"Status",Operator:"=",Value:"3"})}repository.GetPaginated(repository.apiData.controlListXEntity.url,params.page()-1,params.count(),params.sorting(),filter,"",JSON.stringify(columns)).then(function(result){$scope.controlListXEntityTable.settings().total=result.TotalCount,$scope.controlListXEntityTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}));var getLowestEntityCaption=function(entity){return entity.Equipment?entity.Equipment.Caption:entity.Area?entity.Area.Caption:entity.PeriodicTask?translationService.translate("web-controlListXEntity-directConnectionPeriodicTask","Direkte tilkoblet rutine"):translationService.translate("web-controlListXEntity-directConnectionWorkOrder","Direkte tilkoblet arbeidsordre")},getEntityIcon=function(entity){return entity.Equipment?"zmdi-settings c-bluegray":entity.Area?"zmdi-layers c-lightblue":void 0};$scope.getPropertyValue=function(item,column){if(column.isComplex){return""+(' ')+(""+getLowestEntityCaption(item)+"")+""}if(column.isCaption){var newColumn={Position:column.Position,Property:column.Property.replace(".Id",".Caption"),PropertyType:column.PropertyType,Title:column.Title};return listService.GetPropertyValue(item,newColumn)}return listService.GetPropertyValue(item,column)},$scope.openControlList=function(item){$modal.open({templateUrl:"app/controlList/views/controlListCompletionModal.html",size:"lg",controller:"ControlListCompletionModalController",resolve:{params:function(){return{workOrderCaption:item.WorkOrder.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,$modal,$rootScope,listService,$timeout){if($scope.hasReadAccess=$rootScope.hasReadAccess,$scope.hasDeleteAccess=$rootScope.hasDeleteAccess,$scope.hasCreateAccess=$rootScope.hasCreateAccess,$scope.hasEditAccess=$rootScope.hasEditAccess,$scope.hasModule=$rootScope.hasModule,$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.availableColors=["#2196F3","#673AB7","#009688","#4caf50","#ff9800","#00bcd4","#9E9E9E","#607D8B","#000000","#f44336"],$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:{GetAllVersions:!0,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","$modal","$rootScope","ListService","$timeout",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.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:"format-list-bulleted",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:"caret-down-circle",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-Text","Kort svar"),Type:"Text",icon:"text-format",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-TextArea","Utfyllende svar"),Type:"TextArea",icon:"text-format",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-Numeric","Nummer"),Type:"Numeric",icon:"collection-item-1",disabled:!$scope.hasModule("ControlList")},{Guid:null,Name:translationService.translate("web-enum-controllistitemtype-CheckBox","Sjekkboks"),Type:"CheckBox",icon:"check-square",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(event.dest.index,$scope.model.ControlListItems.length-1)},function(error){})}else{var draggedDown=event.source.index>event.dest.index,startIndex=draggedDown?event.dest.index:event.source.index,endIndex=draggedDown?event.source.index:event.dest.index;setTimeout(function(){updateIndexPositions(startIndex,endIndex)},0)}}};var createControlListItem=function(postData){if("Draft"===$scope.model.VersionStatus){var deferred=$q.defer();return repository.createSingleDictionary(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.createSingleDictionary(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(index+1,$scope.model.ControlListItems.length-1)},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:!0},function(){repository.deleteSingle(repository.apiData.controlListItem.url,item.Guid).then(function(response){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(index,$scope.model.ControlListItems.length-1)}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 updateControlListItem=function(item){var deferred=$q.defer();return item.Data&&(item.Data=JSON.stringify(item.Data)),repository.updateSingleDictionary(repository.apiData.controlListItem.url,item).then(function(response){deferred.resolve(response)},function(error){deferred.reject(error)}),item.Data&&(item.Data=JSON.parse(item.Data)),deferred.promise},updateIndexPositions=function(startIndex,endIndex){if("Draft"===$scope.model.VersionStatus){for(var promises=[],i=startIndex;i<=endIndex;i++){var item=$scope.model.ControlListItems[i];item.IndexPosition=i,promises.push(updateControlListItem(item))}$q.all(promises).then(function(result){},function(error){swal("Error",error,"error")})}};$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.updateSingleDictionary(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.createSingleDictionary(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}))})}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-off"}],repository.moduleService.hasModule(repository.moduleService.moduleFlags.Deviation)&&($scope.availableActions.push({Value:"Deviation",icon:"alert-octagon"}),$scope.availableActions.push({Value:"ClosedDeviation",icon:"alert-octagon"})),repository.moduleService.hasModule(repository.moduleService.moduleFlags.Activity)&&$scope.availableActions.push({Value:"Request",icon:"email"});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")}}angular.module("Plania").controller("RuleModalController",["$scope","$modalInstance","Repository","params","TranslationService","$modal",controller])}(),function(){function controller($scope,repository,$q,$stateParams,translationService,$modal,$localStorage){$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)};$scope.getValidityRules=function(fieldName){if(!$scope.baseFieldrules)return null;var fieldrule=_.filter($scope.baseFieldrules,{DomainFieldName:fieldName})[0];return $scope.onGetValidityRules(fieldrule)},updateAccess(),$scope.isAccountingMandatory=function(accountingColumn){if(!$scope.modelDto.dataOwner)return!1;if("GuidDepartment"===accountingColumn)return $scope.modelDto.dataOwner.DepartmentCost;var lastDimensionCost=$scope.modelDto.dataOwner.LastDimensionCost;return!(!angular.isDefined(lastDimensionCost)||!accountingColumn.startsWith("GuidAccounting"))&&lastDimensionCost>=parseInt(accountingColumn.slice(-1))},$scope.onGetValidityRules=function(originalValidityRules){if(!$scope.isAccountingMandatory(originalValidityRules.DomainFieldName))return originalValidityRules;var validityRules=_.clone(originalValidityRules);return validityRules.Mandatory=!0,validityRules},$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},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]}),($scope.isUpdate||payloadEntity.RequestAction?repository.updateSingleDictionary:repository.createSingleDictionary)(repository.apiData.cost.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){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:"PURCHASE_ORDER_ITEM.GUID_WORK_ORDER",Operator:"=",Value:$scope.model.GuidWorkOrder}),$scope.model.GuidProject&&filter.PropertyFilter.push({Property:"PURCHASE_ORDER_ITEM.WORK_ORDER.GUID_PROJECT",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;case"accounting0":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:0,Operator:"="}],filter;case"accounting1":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:1,Operator:"="}],filter;case"accounting2":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:2,Operator:"="}],filter;case"accounting3":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:3,Operator:"="}],filter;case"accounting4":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:4,Operator:"="}],filter}},$scope.update=function(destination){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)},$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},run=function(action,parameter1){var defer=$q.defer();return $scope.model.RequestAction=action,$scope.model.RequestActionParameter1=parameter1,updateEntity().then(function(response){defer.resolve(response)}).catch(function(error){defer.reject()}),delete $scope.model.RequestAction,delete $scope.model.RequestActionParameter1,defer.promise};$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":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);$scope.model[parentPropertyName]&&$scope.model[parentPropertyName].Guid===parent.Guid||($scope.model["Guid"+parentPropertyName]=parent.Guid,$scope.activateAutocomplete=!1,run("SynchronizeWith"+parentPropertyName,JSON.stringify(columns)).finally(function(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",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.updateSingleDictionary(repository.apiData.costCenter.url,$scope.model).then(success,error):repository.createSingleDictionary(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,null,!0).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,null,!0).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||payloadEntity.RequestAction?repository.updateSingleDictionary:repository.createSingleDictionary)(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(){return this.GuidInvoiceCustomer?this.InvoiceCustomer&&this.InvoiceCustomer.Guid===this.GuidInvoiceCustomer?this.InvoiceCustomer:(this.InvoiceCustomer=new Customer,this.InvoiceCustomer.Guid=this.GuidInvoiceCustomer,this.InvoiceCustomer.load(this.GuidInvoiceCustomer).then(function(customer){$scope.invoiceCustomerCaption=customer.Caption},function(error){this.InvoiceCustomer.Guid=null,repository.growl(error,"danger")}),this.InvoiceCustomer):this.InvoiceCustomer=null},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.MailingAddressType;case"MailingPostalArea":case"MailingCountry":return!this.MailingAddress.GuidPostalData&&(!($scope.generalOptions.IsBBY&&this.ExternalId)||"Undefined"===this.MailingAddressType);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.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+"bby/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":filter.PropertyFilter=[{Property:"InvoiceCustomers",Operator:"=",Value:!0}]}return filter},$scope.load=function(guid){var columns=["CustomerCategory.Id","CustomerGroup.Id","CustomerLineOfBusiness.Id","Department.Id"];$scope.model.load(guid,columns).then(function(customer){$scope.setHtmlTitleByModel(customer),customer.CustomerLineOfBusiness&&($scope.lineOfBusiness=customer.CustomerLineOfBusiness.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.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(){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"}],this.initTable=function(){me.table||(me.table=new ngTableParams({page:1,count:10,sorting:{Id:"desc"},filter:{PropertyFilter:[{Property:"GuidCustomer",Operator:"=",Value:$stateParams.guid},{Property:"Status",Operator:"<>",Value:"3"},{Property:"Status",Operator:"<>",Value:"7"}]}},{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 newRequest={model:{GuidCustomer:$scope.model.Guid},customer:$scope.model.Caption};repository.persistedData.setPersistedData("request.create",newRequest),$scope.navigation.go("request.create",{showPersistantData:!0},{reload:!0})},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[0],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={RentalType:"Housing",GuidCustomer:$scope.model.Guid,GuidArea:item.Guid};repository.createSingleDictionary(repository.apiData.contract.url,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:"User1.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.updateSingleDictionary(repository.apiData.customerLog.url,$scope.model).then(function(result){repository.growl("Log har blitt oppdatert","success"),$modalInstance.close()}):repository.createSingleDictionary(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 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(){console.log("deliveryadress run"),$scope.isUpdate?repository.updateSingleDictionary(repository.apiData.customerDeliveryAddress.url,$scope.model).then(function(result){repository.growl("Leveringsadresse har blitt oppdatert","success"),$modalInstance.close()}):repository.createSingleDictionary(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,listService,widget,dwgThemeService,$timeout){function encodeHtml(html){html||(html="");var tmpElement=document.createElement("div");return $(tmpElement).text(html).html()}function decodeHtml(html){html||(html="");var tmpElement=document.createElement("textarea");return tmpElement.innerHTML=html,tmpElement.value}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.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"}],$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.colors=["bluegray","lightblue","cyan","teal","green","yellow","lightorange","orange","blue","purple","deeppurple","red","black"],$scope.limitedColors=["lightblue","teal","green","yellow","lightorange","orange","red","black"],$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="bluegray",$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";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},$scope.model.WidgetData.color="blue";break;case"pl-html-text-widget":$scope.model.WidgetData.color="bluegray",$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="bluegray",$scope.model.WidgetData.columns=[],$scope.model.WidgetData.thresholds=[],$scope.model.WidgetData.chartType="column",$scope.model.WidgetData.kpiGroupTable={valueColumns:[],sortingColumn:{},sortingProperty:null}}"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(),$scope.model.WidgetData.htmlTextBody&&($scope.model.WidgetData.htmlTextBody=decodeHtml($scope.model.WidgetData.htmlTextBody));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":case"pl-report-widget":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-html-text-widget"===$scope.model.WidgetType&&($scope.model.WidgetData.htmlTextBody=encodeHtml($scope.model.WidgetData.htmlTextBody)),"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","ListService","widget","DwgThemeService","$timeout",controller])}(),function(){function controller($scope,repository,$stateParams,$modal,translationService,$q,$state){$scope.edit=$stateParams.editMode,$scope.model={},$scope.restrictEdit=!0;var parseWidgetData=function(){$scope.model.WebDashboardWidgets.forEach(function(widget){widget.WidgetData&&"string"==typeof widget.WidgetData&&(widget.WidgetData=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.WebDashboardWidgets=[],$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.WebDashboardWidgets.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,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",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){$scope.isUpdate=!!link,$scope.model=link||{},$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",controller])}(),function(){angular.module("Plania").directive("plCalendarWidget",["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-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)})}},templateUrl:"app/dashboard/directives/widgets/calendarWidget.html",controller:["$scope","TranslationService","Repository","$modal","$timeout",function($scope,translationService,repository,modal,$timeout){$scope.model=$scope.widget,$scope.eventSource=repository.apiData.workOrder.url,$scope.sharedController={},$(".grid-stack").on("resizestop",function(event,ui){$(event.target).find("#calendar-widget").length>0&&$timeout(function(){$scope.sharedController.resizeCalendar(ui.element.height())},350)}),$timeout(function(){var height=$(".grid-stack").find("[data-gs-id='"+$scope.model.Guid+"']").height();$scope.sharedController.resizeCalendar(height)}),$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(){})}}]}}])}(),function(){angular.module("Plania").directive("plChartWidget",["TranslationService","$timeout","$rootScope",function(translationService,$timeout,$rootScope){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)})},$(".grid-stack").on("resizestop",function(event,ui){$(event.target).find(".chart-widget").length>0&&$timeout(function(){scope.setHeight()},350)}),scope.setHeight=function(){var bodyHeight=element.height()-(element.find(".card-header").height()+40);element.find(".card-body").height(bodyHeight),element.find(".chart-widget-container").height(bodyHeight)},$timeout(function(){scope.setHeight()},10)},templateUrl:"app/dashboard/directives/widgets/chartWidget.html",controller:["$scope","TranslationService","Repository","NgTableParams","$modal","$rootScope","$filter","$interval","$localStorage","ListCompressionService",function($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(),$rootScope.$on($rootScope.events.newSelection,function(){getChartData()})}]}}])}(),function(){angular.module("Plania").directive("plDrawingWidget",["TranslationService","$rootScope",function(translationService,$rootScope){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",function($scope,translationService,repository,modal,$interval,sharedDataService){$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}}]}}])}(),function(){angular.module("Plania").directive("plHtmlTextWidget",["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)})},scope.updateCardBodyHeight=function(hasHeader){var bodyHeight=element.height();scope.model&&scope.model.WidgetData&&"string"!=typeof scope.model.WidgetData&&scope.model.WidgetData.showWidgetHeader&&(bodyHeight-=element.find(".card-header").height()+40),element.find(".card-body").height(bodyHeight)},scope.updateCardBodyHeight()},templateUrl:"app/dashboard/directives/widgets/htmlTextWidget.html",controller:["$scope","CommonService","Repository","$rootScope","$sce","$modal","$filter",function($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&&$timeout(function(){scope.setHeight()},350)}),scope.setHeight=function(){var bodyHeight=element.height()-(element.find(".card-header").height()+40);element.find(".card-body").height(bodyHeight)},$timeout(function(){scope.setHeight()},10)},templateUrl:"app/dashboard/directives/widgets/kpiGroupTableWidget.html",controller:["$scope","TranslationService","Repository","NgTableParams","$modal","$rootScope","$filter","$interval","$localStorage",function($scope,translationService,repository,ngTableParams,modal,$rootScope,$filter,$interval,$localStorage){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 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)},$rootScope.$on($rootScope.events.newSelection,function(){getKpiData()})}}]}}])}(),function(){angular.module("Plania").directive("plKpiWidget",["TranslationService","ListCompressionService","$state","$rootScope",function(translationService,listCompressionService,$state,$rootScope){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-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)})}},templateUrl:"app/dashboard/directives/widgets/kpiWidget.html",controller:["$scope","TranslationService","Repository","$modal","$rootScope",function($scope,translationService,repository,modal,$rootScope){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.hasReadAccess=!1,$scope.color="black",$scope.errorMessage="",$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(){if($scope.model.WidgetData&&$scope.model.WidgetData.prefix?$scope.hasReadAccess=$rootScope.hasReadAccess($scope.model.WidgetData.prefix):$scope.hasReadAccess=!1,!$scope.hasReadAccess)return $scope.kpiPrefixState=null,void($scope.color="gray");$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},$rootScope.$on($rootScope.events.newSelection,function(){$scope.model.WidgetData&&getKpi()})}]}}])}(),function(){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)})};var bodyHeight=element.height()-(element.find(".card-header").height()+40);element.find(".lv-body").height(bodyHeight)},templateUrl:"app/dashboard/directives/widgets/linkWidget.html",controller:["$scope","TranslationService","Repository","$modal",function($scope,translationService,repository,modal){$scope.model=$scope.widget,$scope.navigate=function(item){$rootScope.navigation.go("",{guid:item.Guid},{reload:!0})},$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(){})}}]}}]),app.directive("linkTarget",function(){return{restrict:"A",link:function(scope,element,attrs){element.href;scope.link.IsExternalLink&&element.attr("target","_blank")}}})}(),function(){angular.module("Plania").directive("plListWidget",["TranslationService","ListService","$timeout","$modal",function(translationService,listService,$timeout,$modal){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)})},$(".grid-stack").on("resizestop",function(event,ui){$(event.target).find(".list-widget").length>0&&$timeout(function(){scope.setHeight()},350)}),scope.setHeight=function(){var bodyHeight=element.height()-(element.find(".card-header").height()+40);element.find(".card-body .lv-body").height(bodyHeight)},$timeout(function(){scope.setHeight()},10)},templateUrl:"app/dashboard/directives/widgets/listWidget.html",controller:["$scope","TranslationService","Repository","OperationalMessageService","$modal","$rootScope","states","$interval","DashboardSharedDataService",function($scope,translationService,repository,operationalMessageService,modal,$rootScope,states,$interval,sharedDataService){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:""},{Operand:"and",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","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","Person.FirstName","Person.LastName","WorkOrder.Id","WorkOrder.Description");var commonFilter=operationalMessageService.getCommonPropertyFilter($scope.selectedFilter.value);commonFilter&&Array.isArray(commonFilter)&&commonFilter.forEach(function(f){filter.PropertyFilter.push(f)})}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.state=operationalMessageService.getCurrentStateEnum(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()},$rootScope.$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}}]}}])}(),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","TranslationService","Repository","$modal",function($scope,translationService,repository,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(){})}}]}}])}(),function(){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=result.selectedListSetup;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)}),$scope.hideTable||repository.GetPaginated($scope.widget.WidgetData.ServiceUrl,params.page()-1,params.count(),params.sorting(),filter,"",JSON.stringify(columns)).then(function(result){params.total(result.TotalCount),$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})})}};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:"lg",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})},$rootScope.$on($rootScope.events.newSelection,function(){$scope.widgetTable&&$scope.widgetTable.reload(),setCreateNavState()})}angular.module("Plania").directive("plTableWidget",["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-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)})},$(".grid-stack").on("resizestop",function(event,ui){$(event.target).find(".table-widget").length>0&&$timeout(function(){scope.setHeight()},350)}),scope.setHeight=function(){var bodyHeight=element.height()-(element.find(".card-header").height()+40);element.find(".card-body").height(bodyHeight)},$timeout(function(){scope.setHeight()},10)},controller:["$scope","Repository","NgTableParams","$modal","$rootScope","states","$interval","$localStorage","$modal","ListService","TranslationService",controller],templateUrl:"app/dashboard/directives/widgets/tableWidget.html"}}])}(),function(){function controller($scope,translationService,repository,registeredFieldService,$q,$stateParams,$modal,$location,signalR,$timeout,config,$window){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));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.updateSingleDictionary(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.createSingleDictionary(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.updateSingleDictionary(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.updateSingleDictionary(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 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)})}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.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,FieldMapping:[]},$scope.showSelectFile=!0,$stateParams.guid&&getModel(),$stateParams.guidEntityToCopy&&repository.getSingle(repository.apiData.dataImport.url,$stateParams.guidEntityToCopy).then(function(result){delete result.Data.Guid,delete result.Data.GuidBinaryData,$scope.model=result.Data,$scope.model.Id+=" - kopi"}),$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.")},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)},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.importJobValidating=!0,$scope.importJobValidationProgress={Current:0,Total:100}},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.importJobProcessing=!0,$scope.importJobProgress={Current:0,Total:100}},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.create",{guidEntityToCopy:$scope.model.Guid})},$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(),$scope.intervalSelectOptions=[{text:"Dag",value:0},{text:"Uke",value:1},{text:"Måned",value:2},{text:"År",value:3},{text:"Timer",value:7},{text:"Gang",value:8}];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.updateSingleDictionary(repository.apiData.dataOwner.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(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.createMultiple(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)})}}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.updateSingleDictionary(repository.apiData.department.url,$scope.model).then(success,error):repository.createSingleDictionary(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.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)};$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,$scope.model.RequestAction="Close",repository.updateSingleDictionary(repository.apiData.deviation.url,$scope.model).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.model.RequestAction=null})},$scope.closeDeviationDirectly=function(){$modal.open({templateUrl:"app/deviation/views/closeDeviationDirectlyModal.html",controller:"CloseDeviationDirectlyModalController",resolve:{params:function(){return{guid:$scope.model.Guid,close:!0}}}}).result.then(function(result){getDeviation()})},$scope.postponeDeviation=function(){$modal.open({templateUrl:"app/deviation/views/closeDeviationDirectlyModal.html",controller:"CloseDeviationDirectlyModalController",resolve:{params:function(){return{guid:$scope.model.Guid,close:!1}}}}).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=["User2.RealName","User1.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"],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.growl(error,"danger")})};if($scope.isUpdate)getDeviation();else{if(!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.updateSingleDictionary(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.createSingleDictionary(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()}]}:{}}},$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:"lg",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&&repository.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&&repository.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&&repository.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&&repository.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&&repository.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&&repository.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,$scope.model.RequestAction="ResetCorrectiveWorkorder",repository.updateSingleDictionary(repository.apiData.deviation.url,$scope.model).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.closeDeviationDirectly()}}),!$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.postponeDeviation()}}),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,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.updateSingleDictionary(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","Repository",controller])}(),function(){function controller($scope,$modal,ngTableParams,repository,$rootScope,translationService,$localStorage,Constants,deviationService){$scope.deviationsIsLoading=!0,$scope.search={},function(){$scope.hasEditAccess=$rootScope.hasEditAccess("Deviation"),$scope.hasCreateAccess=$rootScope.hasCreateAccess("Deviation"),$scope.hasDeleteAccess=$rootScope.hasDeleteAccess("Deviation")}();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")}];if($scope.currentSelectedFilterType=filterTypes[0],$localStorage.selectedDeviationFilterType){var storedSelectedFilterType=_.find(filterTypes,{value:$localStorage.selectedDeviationFilterType});storedSelectedFilterType&&($scope.currentSelectedFilterType=storedSelectedFilterType)}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?"zmdi-settings c-bluegray":deviation.Area?"zmdi-layers c-lightblue":deviation.Building?"zmdi-balance c-brown":deviation.Estate?"zmdi-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"),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&&($localStorage.selectedDeviationFilterType=filterTypeValue,$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,deviation.RequestAction="Close",repository.updateSingleDictionary(repository.apiData.deviation.url,deviation).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")}),deviation.RequestAction=null})},$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(){deviation.RequestAction="ResetCorrectiveWorkorder",repository.updateSingleDictionary(repository.apiData.deviation.url,deviation).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:"GuidEquipment",Operator:"<>",Value:null}];$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(JSON.stringify(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()})}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:"";repository.persistedData.setPersistedData("workOrder.create",{guidEstate:deviation.GuidEstate,estate:estate,guidBuilding:deviation.GuidBuilding,building:building,guidEquipment:deviation.GuidEquipment,equipment:equipment,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.updateSingleDictionary(repository.apiData.deviationType.url,$scope.model).then(success,error):repository.createSingleDictionary(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){repository.GetPaginated(repository.apiData.document.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")})}}),$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(JSON.stringify({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)}}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,[JSON.stringify(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")}}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||"",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;i20)return void swal("For stor filstørrelse","Du kan ikke laste opp mer enn 20 MB om gangen. Nåværende filstørrelse: "+$filter("number")(totalSize/1048576,2)+" MB","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")}}angular.module("Plania").controller("CreateDocumentXEntityController",["$scope","Repository","$modalInstance","params","$filter","TranslationService",controller])}(),function(){function controller($scope,$rootScope,repository,ngTableParams,translationService,documentService,$modal,listService){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(JSON.stringify(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)})}},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",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",function($scope,repository,params,authService,translationService,documentService,ngTableParams,$modal,$window,$modalStack){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.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={};var supportsArchiving=function(documentCategory){return!!documentCategory&&("Archivable"===documentCategory.ArchiveType||"AutomaticArchiving"===documentCategory.ArchiveType)};$scope.openDocument=function(document){documentService.openDocument(document)},$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,console.log("document updated"))},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()};$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 postModel=angular.copy($scope.model);postModel.RequestAction="ApproveAllDocumentXEntity";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.updateSingleDictionary(repository.apiData.document.url,postModel).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 postModel=angular.copy(xref);postModel.RequestAction="setDataAcquisitionStatus",postModel.RequestActionParameter1=status;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.updateSingleDictionary(repository.apiData.documentXEntity.url,postModel).then(success,updateError)})},$scope.setArchiveStatus=function(xref,status,prefix){var properties={ArchiveStatus:status};repository.patch(repository.apiData.documentXEntity.url,xref.Guid,JSON.stringify(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)&&repository.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.updateSingleDictionary(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 addEquipmentModalParams={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={title:"Legg til periodisk rutine",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.periodicTask.url,sorting:{Id:"asc"}},addComponentModalParams={title:"Legg til Komponent",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.component.url,sorting:{Id:"asc"}},addBuildingModalParams={title:"Legg til Byggning",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.building.url,sorting:{Id:"asc"}},addAreaModalParams={title:"Legg til Rom",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.area.url,sorting:{Id:"asc"}},addEstateModalParams={title:"Legg til Eiendom",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.estate.url,sorting:{Id:"asc"}},addDeviationModalParams={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={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={title:"Legg til leverandør",columns:[{Title:"Id",Property:"Id"},{Title:"Beskrivelse",Property:"Description"}],url:repository.apiData.supplier.url,sorting:{Id:"desc"}};$scope.openDocumentInArchiveSystem=function(xRef){$window.open(xRef.JournalId,"_blank")},$scope.addXEntity=function(entity){$modal.open({templateUrl:"app/common/views/multipleSelectModal.html",controller:"MultipleSelectModalController",size:"Deviation"===entity||"Condition"===entity?"lg":"md",resolve:{modalParams:function(){return"Equipment"===entity?(addEquipmentModalParams.filter={},$scope.equipmentTable.data.length>0&&(addEquipmentModalParams.filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:_.map($scope.equipmentTable.data,"GuidEquipment").join(",")}]),addEquipmentModalParams):"PeriodicTask"===entity?(addPeriodicTaskModalParams.filter={},$scope.periodicTaskTable.data.length>0&&(addPeriodicTaskModalParams.filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:_.map($scope.periodicTaskTable.data,"GuidPeriodicTask").join(",")}]),addPeriodicTaskModalParams):"Component"===entity?(addComponentModalParams.filter={},$scope.componentTable.data.length>0&&(addComponentModalParams.filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:_.map($scope.componentTable.data,"GuidComponent").join(",")}]),addComponentModalParams):"Building"===entity?(addBuildingModalParams.filter={},$scope.buildingTable.data.length>0&&(addBuildingModalParams.filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:_.map($scope.buildingTable.data,"GuidBuilding").join(",")}]),addBuildingModalParams):"Area"===entity?(addAreaModalParams.filter={},$scope.areaTable.data.length>0&&(addAreaModalParams.filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:_.map($scope.areaTable.data,"GuidArea").join(",")}]),addAreaModalParams):"Estate"===entity?(addEstateModalParams.filter={},$scope.estateTable.data.length>0&&(addEstateModalParams.filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:_.map($scope.estateTable.data,"GuidEstate").join(",")}]),addEstateModalParams):"Deviation"===entity?(addDeviationModalParams.filter={},$scope.deviationTable.data.length>0&&(addDeviationModalParams.filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:_.map($scope.deviationTable.data,"GuidDeviation").join(",")}]),addDeviationModalParams):"Condition"===entity?(addConditionModalParams.filter={},$scope.conditionTable.data.length>0&&(addConditionModalParams.filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:_.map($scope.conditionTable.data,"GuidCondition").join(",")}]),addConditionModalParams):"Supplier"===entity?(addSupplierModalParams.filter={},$scope.supplierTable.data.length>0&&(addSupplierModalParams.filter.PropertyFilter=[{Property:"Guid",Operator:"notIn",Value:_.map($scope.supplierTable.data,"GuidSupplier").join(",")}]),addSupplierModalParams):void 0}}}).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),documentXEntities.push(JSON.stringify(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){$scope.model=angular.copy(params.image),$scope.imageXEntity={},$scope.imageApiUrl=config.baseUrlApi+repository.apiData.image.url,$scope.deleteAccess=params.deleteAccess,$scope.isRunningAction=!1,$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("image").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("image");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.onIsDefaultChange&&"function"==typeof params.onIsDefaultChange&¶ms.onIsDefaultChange($scope.model),$scope.isRunningAction=!1},function(error){$scope.isRunningAction=!1,$scope.model.IsStandard=!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("image").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",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(JSON.stringify({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,JSON.stringify(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",Operand:"AND"}),me.archiveStatusFilterList&&me.archiveStatusFilterList.length>0&¶ms.filter().PropertyFilter.push({Property:"ArchiveStatus",Operator:"IN",Value:me.archiveStatusFilterList.join(","),Operand:"AND"}),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.removeEquipmentCategoryLabels(areas);var filter={ActivityStatus:"Active",PropertyFilter:[{Property:"Area.GuidDrawing",Operator:"=",Value:guidDrawing}]},requestFilter={PropertyFilter:[{Property:"Status",Operator:"=",Value:"0"},{Operand:"OR",Property:"Status",Operator:"=",Value:"1"},{Operand:"AND",Property:"WorkOrder.EndDate",Operator:"=",Value:""},{Operand:"AND",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){var elements=$("#"+status.GuidArea).children();if(elements[0]){var path=elements[0];$(path).attr("stroke-dasharray",""),$(path).attr("stroke-linecap",""),status.HasCleaning&&($(path).attr("stroke",hasCleaning),$(path).attr("fill",hasCleaning),$(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("fill-opacity","0.3")),status.HasCleaningToday&&($(path).attr("stroke",hasCleaningToday),$(path).attr("fill",hasCleaningToday),$(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("fill-opacity","0.3")),status.IsCleaningTodayCompleted&&($(path).attr("stroke",isCleaningTodayCompleted),$(path).attr("fill",isCleaningTodayCompleted),$(path).attr("fill-opacity","0.4")),status.DelayedDate&&($(path).attr("stroke","#FF6700"),$(path).attr("fill","#FF6700"),$(path).attr("fill-opacity","0.4")),moment(status.DelayedDate).isBefore(moment().format("YYYY-MM-DD"))&&($(path).attr("stroke","#F44336"),$(path).attr("fill","#F44336"),$(path).attr("fill-opacity","0.4")),status.ExitGuidAreaXCleaningTask?($(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("stroke",hasExitCleaning),$(path).attr("fill",hasExitCleaning),"Discharged"===status.ExitCleaningRequestStatus?($(path).attr("fill","#008EA1"),$(path).attr("fill-opacity","0.8"),$(path).attr("stroke",exitCleaningDischarged)):"Confirmed"===status.ExitCleaningRequestStatus?$(path).attr("fill-opacity","0.5"):$(path).attr("fill-opacity","0.15"),$(path).data("exitGuidAreaXCleaningTask",status.ExitGuidAreaXCleaningTask)):$(path).removeData("exitGuidAreaXCleaningTask"),status.HasInfectionCleaning&&($(path).attr("stroke",hasInfectionCleaning),$(path).attr("fill",hasInfectionCleaning),$(path).attr("fill-opacity","0.4")),status.HasAdditionalCleaning&&($(path).attr("stroke-dasharray","250,250"),$(path).attr("stroke-linecap","square"));var today=moment().startOf("day");status.PausedFromDate&&today.isBetween(status.PausedFromDate,status.PausedToDate,"day","[]")&&($(path).attr("stroke",hasPausedCleaning),$(path).attr("stroke-width","200"),$(path).attr("stroke-dasharray","550,550"),$(path).attr("stroke-linecap","square")),status.PeriodicCleaningDueDate&&markerService.addPeriodicIcon(path,status.GuidArea,status.PeriodicCleaningCountdown)}})};service.getLegends=function(areas,showAll){var legends=[{label:"Rom med renholdsoppgaver",legendClass:"legend-gray"},{label:"Skal rengjøres i dag",legendClass:"legend-primary"},{label:"Rengjorte rom",legendClass:"legend-success"}];return showAll&&(legends.push({label:"Utsatt i dag",legendClass:"legend-warning-2"}),legends.push({label:"Tidligere utsatt",legendClass:"legend-danger"}),legends.push({label:"Klart utreisevask",legendClass:"legend-exitCleaning-discharged"}),legends.push({label:"Bekreftet utreisevask",legendClass:"legend-info"}),legends.push({label:"Mulig utreisevask",legendClass:"legend-info-2"}),legends.push({label:"Smittevask",legendClass:"legend-warning"}),legends.push({label:"Rom med tilleggsoppgaver",legendClass:"legend-dashed"}),legends.push({label:"Rom med pauset renhold",legendClass:"legend-dashed-warning"}),legends.push({label:"Periodisk renhold",imageSrc:"images/svg-periodicMarker.png"})),showAll||!areas||0===areas.length?legends:(_.some(areas,function(area){return area.DelayedDate})&&legends.push({label:"Utsatt i dag",legendClass:"legend-warning-2"}),_.some(areas,function(area){return moment(area.DelayedDate).isBefore(moment().format("YYYY-MM-DD"))})&&legends.push({label:"Tidligere utsatt",legendClass:"legend-danger"}),_.some(areas,function(area){return area.ExitGuidAreaXCleaningTask})&&(_.some(areas,function(area){return"Discharged"===area.ExitCleaningRequestStatus})&&legends.push({label:"Klart utreisevask",legendClass:"legend-exitCleaning-discharged"}),_.some(areas,function(area){return"Confirmed"===area.ExitCleaningRequestStatus})?legends.push({label:"Bekreftet utreisevask",legendClass:"legend-info"}):legends.push({label:"Mulig utreisevask",legendClass:"legend-info-2"})),_.some(areas,function(area){return area.HasInfectionCleaning})&&legends.push({label:"Smittevask",legendClass:"legend-warning"}),_.some(areas,function(area){return area.HasAdditionalCleaning})&&legends.push({label:"Rom med tilleggsoppgaver",legendClass:"legend-dashed"}),_.some(areas,function(area){return area.PausedFromDate&&area.PausedToDate&&moment().isBetween(area.PausedFromDate,area.PausedToDate,"day","[]")})&&legends.push({label:"Rom med pauset renhold",legendClass:"legend-dashed-warning"}),_.some(areas,function(area){return area.PeriodicCleaningDueDate})&&legends.push({label:"Periodisk renhold",imageSrc:"images/svg-periodicMarker.png"}),legends)},service.onClick=function(guid,type){var deferred=$q.defer();if("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()});else{var tabs={cleaningMaintenance:{visible:$rootScope.hasEditAccess(repository.apiData.areaXCleaningTask.prefix),active:!0},cleaningInfo:{visible:$rootScope.hasReadAccess(repository.apiData.areaXCleaningTask.prefix),active:!1}};$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({update:!0})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()})}return deferred.promise},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.getStatus=function(areas,guidDrawing){dwgThemeService.removeEquipmentCategoryLabels(areas);var filter={PropertyFilter:[{Property:"Status",Operator:"=",Value:"0"},{Operand:"OR",Property:"Status",Operator:"=",Value:"1"},{Operand:"AND",Property:"WorkOrder.EndDate",Operator:"=",Value:""},{Operand:"AND",Property:"Area.GuidDrawing",Operator:"=",Value:guidDrawing}]};return repository.GetPaginated(repository.apiData.request.url,0,1e3,{},filter,"",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.createMultiple(repository.apiData.cleaningStatus.url+"cleaningStatus",areas).then(function(result){return dwgThemeService.removeAreaIndicators(areas),updateIndicatorColours(result),result})},service.handleMultipleAreas=function(areas){var deferred=$q.defer();return $modal.open({templateUrl:"app/cleaning/views/multipleCleaningOnHold.html",size:"lg",controller:"MultipleCleaningOnHoldController",animation:!1,resolve:{params:function(){return{guids:areas}}}}).result.then(function(result){deferred.resolve({update:!0})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()}),deferred.promise},service}]),angular.module("Plania").factory("CleaningQualityControlThemeService",["$modal","Repository","$q","TranslationService","DwgThemeService",function($modal,repository,$q,translationService,dwgThemeService){var service={},areas=[],areaNotApproved="#d9534f",areaToBeApproved="#428bca",areaApproved="#5cb85c",updateIndicatorColours=function(){areas.forEach(function(area){var elements=$("#"+area.GuidArea).children();if(elements[0]){var path=elements[0];if("NotAvailable"===area.Status)return;$(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("fill-opacity","0.3"),$(path).attr("stroke-dasharray",""),$(path).attr("stroke-linecap",""),"New"===area.Status&&($(path).attr("stroke",areaToBeApproved),$(path).attr("fill",areaToBeApproved)),"Approved"===area.Status&&($(path).attr("stroke",areaApproved),$(path).attr("fill",areaApproved)),"Rejected"===area.Status&&($(path).attr("stroke",areaNotApproved),$(path).attr("fill",areaNotApproved))}})};return service.getLegends=function(){return[{label:"Rom til kontroll",legendClass:"legend-primary"},{label:"Ikke godkjent",legendClass:"legend-danger"},{label:"Godkjent",legendClass:"legend-success"}]},service.onClick=function(guidArea){var deferred=$q.defer(),cleaningQualityControlArea=_.find(areas,function(o){return o.GuidArea===guidArea});return cleaningQualityControlArea?($modal.open({templateUrl:"app/cleaningQualityControl/views/cleaningQualityControlAreaModal.html",controller:"CleaningQualityControlAreaModalController",animation:!1,size:"lg",resolve:{params:function(){return{cleaningQualityControlArea:cleaningQualityControlArea}}}}).result.then(function(){deferred.resolve({update:!0})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()}),deferred.promise):$.Deferred().reject().promise()},service.getStatus=function(guidQualityControl,oldAreas){return oldAreas&&Array.isArray(oldAreas)&&(dwgThemeService.removePeriodicMarkers(oldAreas),dwgThemeService.removeRequestMarkers(oldAreas),dwgThemeService.removeEquipmentCategoryLabels(oldAreas)),repository.GetPaginated(repository.apiData.cleaningQualityControlArea.url,0,500,{},{PropertyFilter:[{Property:"GuidCleaningQualityControl",Value:guidQualityControl,Operator:"="}]},"",JSON.stringify(["Status"])).then(function(result){return oldAreas&&Array.isArray(oldAreas)&&dwgThemeService.removeAreaIndicators(oldAreas),areas=result.List,updateIndicatorColours(),result})},service}]),angular.module("Plania").factory("CleaningThemeService",["$modal","Repository","$q","TranslationService","DwgMarkerService","DwgThemeService",function($modal,repository,$q,translationService,markerService,dwgThemeService){var service={},hasCleaningToday="#2196F3",hasCleaning="#9E9E9E",isCleaningTodayCompleted="#5cb85c",hasInfectionCleaning="#FFC107",hasExitCleaning="#00BCD4",exitCleaningDischarged="#000000",updateIndicatorColours=function(statuses){statuses.forEach(function(status){var elements=$("#"+status.GuidArea).children();if(elements[0]){var path=elements[0];$(path).attr("stroke-dasharray","0"),$(path).attr("stroke-linecap",""),$(path).attr("stroke",""),$(path).attr("fill",""),status.HasCleaning&&($(path).attr("stroke",hasCleaning),$(path).attr("fill",hasCleaning),$(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("fill-opacity","0.3")),status.HasCleaningToday&&($(path).attr("stroke",hasCleaningToday),$(path).attr("fill",hasCleaningToday),$(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("fill-opacity","0.3")),status.IsCleaningTodayCompleted&&($(path).attr("stroke",isCleaningTodayCompleted),$(path).attr("fill",isCleaningTodayCompleted),$(path).attr("fill-opacity","0.4")),status.DelayedDate&&($(path).attr("stroke","#FF6700"),$(path).attr("fill","#FF6700"),$(path).attr("fill-opacity","0.4")),moment(status.DelayedDate).isBefore(moment().format("YYYY-MM-DD"))&&($(path).attr("stroke","#F44336"),$(path).attr("fill","#F44336"),$(path).attr("fill-opacity","0.4")),status.ExitGuidAreaXCleaningTask?($(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("stroke",hasExitCleaning),$(path).attr("fill",hasExitCleaning),"Discharged"===status.ExitCleaningRequestStatus?($(path).attr("fill-opacity","0.8"),$(path).attr("fill","#008EA1"),$(path).attr("stroke",exitCleaningDischarged)):"Confirmed"===status.ExitCleaningRequestStatus?$(path).attr("fill-opacity","0.5"):$(path).attr("fill-opacity","0.15"),$(path).data("exitGuidAreaXCleaningTask",status.ExitGuidAreaXCleaningTask)):$(path).removeData("exitGuidAreaXCleaningTask"),status.HasInfectionCleaning&&($(path).attr("stroke",hasInfectionCleaning),$(path).attr("fill",hasInfectionCleaning),$(path).attr("fill-opacity","0.4")),status.HasAdditionalCleaning&&($(path).attr("stroke-dasharray","250,250"),$(path).attr("stroke-linecap","square")),status.PeriodicCleaningDueDate&&markerService.addPeriodicIcon(path,status.GuidArea,status.PeriodicCleaningCountdown)}})};service.getLegends=function(areas,showAll){var legends=[{label:"Rom med renholdsoppgaver",legendClass:"legend-gray"},{label:"Skal rengjøres i dag",legendClass:"legend-primary"},{label:"Rengjorte rom",legendClass:"legend-success"}];return showAll&&(legends.push({label:"Utsatt i dag",legendClass:"legend-warning-2"}),legends.push({label:"Tidligere utsatt",legendClass:"legend-danger"}),legends.push({label:"Klart utreisevask",legendClass:"legend-exitCleaning-discharged"}),legends.push({label:"Bekreftet utreisevask",legendClass:"legend-info"}),legends.push({label:"Mulig utreisevask",legendClass:"legend-info-2"}),legends.push({label:"Smittevask",legendClass:"legend-warning"}),legends.push({label:"Rom med tilleggsoppgaver",legendClass:"legend-dashed"}),legends.push({label:"Periodisk renhold",imageSrc:"images/svg-periodicMarker.png"})),showAll||!areas||0===areas.length?legends:(_.some(areas,function(area){return area.DelayedDate})&&legends.push({label:"Utsatt i dag",legendClass:"legend-warning-2"}),_.some(areas,function(area){return moment(area.DelayedDate).isBefore(moment().format("YYYY-MM-DD"))})&&legends.push({label:"Tidligere utsatt",legendClass:"legend-danger"}),_.some(areas,function(area){return area.ExitGuidAreaXCleaningTask})&&(_.some(areas,function(area){return"Discharged"===area.ExitCleaningRequestStatus})&&legends.push({label:"Klart utreisevask",legendClass:"legend-exitCleaning-discharged"}),_.some(areas,function(area){return"Confirmed"===area.ExitCleaningRequestStatus})?legends.push({label:"Bekreftet utreisevask",legendClass:"legend-info"}):legends.push({label:"Mulig utreisevask",legendClass:"legend-info-2"})),_.some(areas,function(area){return area.HasInfectionCleaning})&&legends.push({label:"Smittevask",legendClass:"legend-warning"}),_.some(areas,function(area){return area.HasAdditionalCleaning})&&legends.push({label:"Rom med tilleggsoppgaver",legendClass:"legend-dashed"}),_.some(areas,function(area){return area.PeriodicCleaningDueDate})&&legends.push({label:"Periodisk renhold",imageSrc:"images/svg-periodicMarker.png"}),legends)},service.onClick=function(guid,type,data){var deferred=$q.defer();if("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()});else{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}};$modal.open({templateUrl:"app/dwg/views/dwgSelectionModal.html",size:"lg",controller:"DwgSelectionModalController",animation:!1,resolve:{params:function(){return{guid:guid,tabInfo:tabs,data:data}}}}).result.then(function(result){deferred.resolve({update:!0})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()})}return deferred.promise},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.getStatus=function(areas,guidDrawing){dwgThemeService.removeEquipmentCategoryLabels(areas);var requestFilter=(_.uniq(_.map(areas,"GuidArea")),{PropertyFilter:[{Property:"Status",Operator:"=",Value:"0"},{Operand:"OR",Property:"Status",Operator:"=",Value:"1"},{Operand:"AND",Property:"WorkOrder.EndDate",Operator:"=",Value:""},{Operand:"AND",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.createMultiple(repository.apiData.cleaningStatus.url+"cleaningStatus",areas).then(function(result){return dwgThemeService.removeAreaIndicators(areas),updateIndicatorColours(result),result})},service.handleMultipleAreas=function(areas){var deferred=$q.defer();return $modal.open({templateUrl:"app/cleaning/views/multipleCleaningCompletions.html",size:"lg",controller:"MultipleCleaningCompletionsController",animation:!1,resolve:{params:function(){return{guids:areas}}}}).result.then(function(result){deferred.resolve({update:!0})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()}),deferred.promise},service}]),angular.module("Plania").factory("ControlListThemeService",["$modal","Repository","$q","$rootScope","TranslationService","DwgThemeService",function($modal,repository,$q,$rootScope,translationService,dwgThemeService){var service={},overDeadline="#ff9800",beforeDeadline="#ffc107",hasActiveWorkOrder="#428bca",alertDays=15,statuses=[];service.getLegends=function(){return[{label:translationService.translate("web-dwg-legend-controlList-overdeadline","Kontrolliste på arbeidsordre over tidsfrist"),legendClass:"legend-warning-2"},{label:translationService.translate("web-dwg-legend-controlList-beforedeadline","Kontrolliste på arbeidsordre nær tidsfrist"),legendClass:"legend-warning"},{label:translationService.translate("web-dwg-legend-controlList-activeworkorder","Kontrolliste på aktiv arbeidsordre"),legendClass:"legend-primary"}]};var updateIndicatorColours=function(){statuses&&statuses.forEach(function(status){var elements=$("#"+status.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(status.DueDate),timespan=24*alertDays*60*60*1e3,beforeDeadlineDate=new Date(overDeadlineDate.getTime()-timespan);new Date>beforeDeadlineDate&&($(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.removeEquipmentCategoryLabels(areas);var areaGuids=areas.map(function(area){return area.GuidArea}),payload={Guid:"00000000-0000-0000-0000-000000000000",RequestAction:"GetEarliestControlListDueDates",RequestActionParameter1:JSON.stringify(areaGuids)};return repository.updateSingleDictionary(repository.apiData.area.url,payload).then(function(result){return dwgThemeService.removeAreaIndicators(areas),statuses=result,updateIndicatorColours(),result})},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","$rootScope","$interval","Repository","DwgMarkerService","TranslationService",function($injector,$state,rootScope,$interval,repository,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"),title+=' '+result.Building.Caption+"
"),title+=' '+result.Id},getDrawing=function(){if(!scope.guidDrawing)return document.getElementById("dwgDrawing")&&(svgPanZoom("#dwgDrawing").destroy(),$("#dwgDrawing").svg("destroy")),void(scope.title="");var columns=["Svg","Id","Building.Id","Building.Description","Building.Estate.Id","Building.Estate.Description"];repository.getSingle(repository.apiData.drawing.url,scope.guidDrawing,JSON.stringify(columns)).then(function(result){document.getElementById("dwgDrawing")&&(svgPanZoom("#dwgDrawing").destroy(),$("#dwgDrawing").svg("destroy")),scope.title=getTitle(result.Data),result.Data.Svg&&(result=result.Data.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};return 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})},service.addEquipmentLabels=function(p,equipments,equipmentStyle){var coordinates=getCoordinatesFromElement(p),topLeft={x:0,y:0},scale=35,topLeftCorner=getCorner(coordinates,"topLeft");p.getBBox();topLeft.x=topLeftCorner.x/scale+7.5,topLeft.y=-1*(topLeftCorner.y/scale-15);var svg=$("#dwgDrawing").svg("get"),transformString="rotate(180) scale("+-1*scale+", "+scale+") translate("+topLeft.x+","+topLeft.y+")",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 canvas=document.createElement("canvas"),context=canvas.getContext("2d");context.font="x-small FontAwesome",context.scale=scale;var width=context.measureText(longestText).width+6,height=offset*equipmentsIdsText.length+4;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":"roboto",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":"roboto",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.$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){if(!drawingStates[drawing.Guid]){drawingStates[drawing.Guid]=!0;var columns=["Thumbnail"];repository.getSingle(repository.apiData.drawing.url,drawing.Guid,JSON.stringify(columns)).then(function(result){scope.svg[drawing.Guid]="data:image/png;base64,"+result.Data.Thumbnail})}})};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){if($scope.model={},$scope.showChecklistList=!0,$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={PropertyFilter:[{Property:"WorkOrder.StartDate",Operator:"<=",Value:moment().endOf("day").toISOString()},{Operand:"OR",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",controller])}(),angular.module("Plania").factory("DwgThemeService",["$modal","Repository","$rootScope","TranslationService",function($modal,repository,rootScope,translationService){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.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;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.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])}(),function(){function controller($scope,repository,$modalInstance,$localStorage,params,translationService){$scope.showUpload=$localStorage.generalOptions.CanSaveDrawingInDatabase;var columns=["Building.Id","Building.Description"],isNew=!0;params.Guid?(isNew=!1,repository.getSingle(repository.apiData.drawing.url,params.Guid,JSON.stringify(columns)).then(function(result){$scope.model=result.Data})):$scope.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")},error=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")})},success=function(result){repository.commonService.setLastRegisterGuid(destination,result),repository.growl("Tegningen har blitt lagret","info"),$scope.alreadyUploaded=!0,savedFiles=_.map(result.savedFiles,"guid"),$scope.saveFeedback=translationService.translate("web-drawing-edit-successFeedback-FileChanged","Tegningen har blitt lagret, videre behandling i desktop er nødvendig for å kunne vise tegningen i web (opprett svg i desktop)"),$scope.isUploading=!1};isNew?repository.createSingleWithBinary(repository.apiData.document.urlChunk,$scope.model,filesToUpload).then(success,error,updateFeedback):repository.updateSingleWithBinary(repository.apiData.document.urlChunk,$scope.model,filesToUpload[0]).then(success,error,updateFeedback)}},$scope.ok=function(){$modalInstance.close()},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("EditDrawingModalController",["$scope","Repository","$modalInstance","$localStorage","params","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){console.log("mouseenter")}),$(".equipmentLabel").on("mouseleave",function(e){console.log("mouseleave")})};return service.getStatus=function(areas,guidDrawing,selectedCategories,categoryColors){dwgThemeService.removeAreaIndicators(areas),dwgThemeService.removeRequestMarkers(areas),dwgThemeService.removePeriodicMarkers(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){var elements=$("#"+status.GuidArea).children();if(elements[0]){var path=elements[0];$(path).attr("stroke-width","0"),$(path).attr("stroke-opacity","0"),$(path).attr("stroke",""),$(path).attr("stroke-dasharray","0"),$(path).attr("stroke-linecap",""),$(path).attr("fill",""),$(path).attr("fill-opacity","0"),status.HasAdditionalCleaning&&($(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("stroke",hasExtraCleaningTask),$(path).attr("fill",hasExtraCleaningTask),$(path).attr("fill-opacity","0.3")),status.ExitGuidAreaXCleaningTask?($(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("stroke",hasExitCleaning),$(path).attr("fill",hasExitCleaning),"Discharged"===status.ExitCleaningRequestStatus?($(path).attr("fill","#008EA1"),$(path).attr("fill-opacity","0.8"),$(path).attr("stroke",exitCleaningDischarged)):"Confirmed"===status.ExitCleaningRequestStatus?$(path).attr("fill-opacity","0.5"):$(path).attr("fill-opacity","0.15"),$(path).data("exitGuidAreaXCleaningTask",status.ExitGuidAreaXCleaningTask)):$(path).removeData("exitGuidAreaXCleaningTask"),status.HasInfectionCleaning&&($(path).attr("stroke-width","100"),$(path).attr("stroke-opacity","1"),$(path).attr("stroke",hasInfectionCleaning),$(path).attr("fill",hasInfectionCleaning),$(path).attr("fill-opacity","0.4"))}})};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:"Aktive tilleggsoppgaver",legendClass:"legend-primary"},{label:"Smittevask",legendClass:"legend-warning"},{label:"Klart utreisevask",legendClass:"legend-exitCleaning-discharged"},{label:"Bekreftet utreisevask",legendClass:"legend-info"},{label:"Mulig utreisevask",legendClass:"legend-info-2"},{label:"Aktive meldinger",imageSrc:"images/svg-marker.png"}]},service.onClick=function(guid,type,data){var deferred=$q.defer();if("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()});else{var tabs={cleaningInfo:{visible:repository.authService.hasReadAccess(repository.apiData.areaXCleaningTask.prefix),active:!1},technicalRequest:{visible:repository.authService.hasCreateAccess(repository.apiData.request.prefix),active:!1},cleaningRequest:{visible:repository.authService.hasCreateAccess(repository.apiData.areaXCleaningTask.prefix),active:!0}},openDwgSelectionModal=function(){$modal.open({templateUrl:"app/dwg/views/dwgSelectionModal.html",size:"lg",controller:"DwgSelectionModalController",animation:!1,resolve:{params:function(){return{guid:guid,tabInfo:tabs,data:data}}}}).result.then(function(result){deferred.resolve({update:!0})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()})};data.exitGuidAreaXCleaningTask?$modal.open({templateUrl:"app/cleaning/views/editExitCleaning.html",controller:"ExitCleaningController",animation:!1,resolve:{params:function(){return{guidAreaXCleaningTask:data.exitGuidAreaXCleaningTask}}}}).result.then(function(result){deferred.resolve({update:!0})},function(error){"cancel"===error?deferred.resolve({}):"openDwgSelection"===error?$timeout(function(){openDwgSelectionModal()},50):deferred.reject()}):openDwgSelectionModal()}return deferred.promise},service.getStatus=function(areas,guidDrawing){dwgThemeService.removeEquipmentCategoryLabels(areas);var requestFilter={PropertyFilter:[{Property:"Status",Operator:"=",Value:"0"},{Operand:"OR",Property:"Status",Operator:"=",Value:"1"},{Operand:"AND",Property:"WorkOrder.EndDate",Operator:"=",Value:""},{Operand:"AND",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&&(result.List.forEach(function(request){_.contains(areaGuids,request.GuidArea)||areaGuids.push(request.GuidArea)}),updateMarkers(areaGuids))},function(error){repository.growl(error,"danger")}),repository.createMultiple(repository.apiData.cleaningStatus.url+"cleaningStatus",areas).then(function(result){return dwgThemeService.removeAreaIndicators(areas),updateIndicatorColours(result),result})},service.handleMultipleAreas=function(areas){var deferred=$q.defer();return $modal.open({templateUrl:"app/cleaning/views/multipleDwgRequests.html",size:"lg",controller:"MultipleDwgRequestController",animation:!1,resolve:{params:function(){return{guids:areas}}}}).result.then(function(result){deferred.resolve({update:!0})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()}),deferred.promise},service.editMultipleAreas=function(areas){var deferred=$q.defer();return $modal.open({templateUrl:"app/cleaning/views/editMultipleDwgRequests.html",size:"lg",controller:"EditMultipleDwgRequestController",animation:!1,resolve:{params:function(){return{guids:areas}}}}).result.then(function(result){deferred.resolve({update:!0})},function(error){"cancel"===error?deferred.resolve({}):deferred.reject()}),deferred.promise},service}]),angular.module("Plania").factory("StandardThemeService",["$modal","Repository","$q","DwgThemeService",function($modal,repository,$q,dwgThemeService){var service={};return 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},checklist:{visible:repository.authService.hasReadAccess(repository.apiData.WorkOrderXArea.prefix),active:!1}};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},service.getStatus=function(areas){dwgThemeService.removeAreaIndicators(areas),dwgThemeService.removePeriodicMarkers(areas),dwgThemeService.removeRequestMarkers(areas),dwgThemeService.removeEquipmentCategoryLabels(areas);var defer=$q.defer();return defer.resolve(),defer.promise},service}]),function(){function controller($scope,repository,$stateParams,translationService,$modal){$scope.isUpdate="emailTemplate.edit"===$scope.navigation.current.name,$scope.model={},$scope.modelDto={},$scope.activateAutocomplete=!1;var updateAccess=function(){if($scope.isUpdate){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictSave=!repository.authService.hasEditAccess(repository.commonService.prefix.EmailTemplate,checkOtherDo),$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.EmailTemplate,checkOtherDo),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.EmailTemplate,checkOtherDo)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.EmailTemplate)};updateAccess();var encodeHtml=function(html){var tmpElement=document.createElement("div");return $(tmpElement).text(html).html()},decodeHtml=function(html){var tmpElement=document.createElement("textarea");return tmpElement.innerHTML=html,tmpElement.value};$scope.entityTypes=[{prefix:"WorkOrder",translation:translationService.translate("web-enum-prefix-workorder")},{prefix:"PurchaseOrder",translation:translationService.translate("web-enum-prefix-purchaseOrder")},{prefix:"Request",translation:translationService.translate("web-enum-prefix-Request")},{prefix:"Project",translation:translationService.translate("web-enum-prefix-Project")}];var columns=[];$scope.isUpdate?repository.getSingle(repository.apiData.emailTemplate.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.model.TemplateBody=decodeHtml($scope.model.TemplateBody),updateAccess(),$scope.reload=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}):setTimeout(function(){$scope.activateAutocomplete=!0},250),$scope.update=function(destination){var updateModel=angular.copy($scope.model);updateModel.TemplateBody=encodeHtml(updateModel.TemplateBody);var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-emailTemplate-success","Epost-malen har blitt oppdatert."):translationService.translate("create-emailTemplate-success","Epost-malen 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.updateSingleDictionary(repository.apiData.emailTemplate.url,updateModel).then(success,error):repository.createSingleDictionary(repository.apiData.emailTemplate.url,updateModel).then(success,error)},$scope.delete=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-emailTemplate-message","Epost-malen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-emailTemplate-button-confirm","Ja, fjern Epost-malen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.emailTemplate.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-emailTemplate-success","Epost-malen ble fjernet!"),result,"success"),$scope.goBack("emailTemplate.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.preview=function(){$modal.open({templateUrl:"app/emailTemplate/views/emailTemplatePreviewModal.html",controller:"EmailTemplatePreviewModalController",size:"lg",resolve:{params:function(){return{prefix:_.find($scope.entityTypes,{prefix:$scope.model.EntityType}).prefix,body:$scope.model.TemplateBody}}}})},$scope.tinymceOptions={language:"nb_NO",branding:!1,plugins:["advlist autolink lists link image charmap print preview hr anchor pagebreak","searchreplace visualblocks visualchars code codesample lineheight","insertdatetime media nonbreaking save table contextmenu directionality","emoticons template paste textcolor colorpicker textpattern imagetools toc help autoresize"],toolbar:"undo redo | styleselect fontselect fontsizeselect | bold italic forecolor backcolor | alignleft aligncenter alignright lineheightselect | bullist numlist outdent indent | addProperty addUserProperty addLinkToCurrentObject",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",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){function getEntityTypePrefix(){var entityType=_.find($scope.entityTypes,{prefix:$scope.model.EntityType});return entityType?entityType.prefix:null}editor.addButton("addProperty",{icon:"plus",tooltip:"Sett inn et databasefelt",onclick:function(){var prefix=getEntityTypePrefix();if(!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:prefix,existingColumns:[]}}}}).result.then(function(selectedColumns){selectedColumns.forEach(function(column){editor.insertContent("{{"+column.Property+"}} ")})})}}),editor.addButton("addUserProperty",{icon:"user",tooltip:"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+"}} ")})})}}),editor.addButton("addLinkToCurrentObject",{icon:"newtab",tooltip:"Sett inn link til objektet",onclick:function(){if(!getEntityTypePrefix())return void swal("Ingen entitet valgt","Velg en entitet for å kunne legge til link i malen","warning");var url="{{#web_base_url}}/{{Prefix}}/edit/{{Guid}}";editor.insertContent(''+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;k0?$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.updateSingleDictionary(repository.apiData.entityLink.url,$scope.model).then(success,repository.showError):repository.createSingleDictionary(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","$localStorage",controller])}(),function(){function controller(scope,repository){scope.collapse={isEntitiesCollapsed:!1};var entityLinkFilter={GuidEntity:scope.guid,PropertyFilter:[{Property:"EntityType",Operator:"=",Value:scope.entity},{Property:"Type",Operator:"<=",Value:"0"}]},columns=["Name","Url","Description","Type","IndexPosition","EntityType","UseUrlEncoding","ActionRule","HttpHeaders","Filter"];repository.GetPaginated(repository.apiData.entityLink.url,0,1e4,{IndexPosition:"asc"},entityLinkFilter,null,JSON.stringify(columns)).then(function(result){scope.totalCount=result.TotalCount,scope.entityLinks=result.List.filter(function(link){return link.Visible})},function(error){repository.growl(error,"danger")})}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,$stateParams,repository){$scope.model={},$scope.update="entityPermission.edit"===$scope.navigation.current.name,$scope.activateAutocomplete=!1,$scope.update?repository.getSingle(repository.apiData.entityPermissionProfile.url,$stateParams.guid).then(function(result){$scope.permissionProfile=result.Data,$scope.fieldRules=result.FieldRules,$scope.reload=!0;var filter={PropertyFilter:[{Property:"GuidEntityPermissionProfile",Operator:"=",Value:$scope.permissionProfile.Guid}]},numberOfAwaitedReturns=2,returned=function(){--numberOfAwaitedReturns||($scope.buildEntityTypeTree(),setTimeout(function(){$scope.activateAutocomplete=!0},250))};repository.GetPaginated(repository.apiData.entityPermission.url,0,500,{},filter).then(function(result){$scope.permissions=result.List,$scope.mapOfPermissions={},$scope.permissions.forEach(function(permission){$scope.mapOfPermissions[permission.EntityType]=permission}),returned()}),repository.GetPaginated("entityTypeInfo/",0,500,{},filter).then(function(result){$scope.entityTypeGroups=result,returned()})}):repository.getSingle(repository.apiData.registeredField.url,repository.commonService.prefix.EntityPermissionProfile).then(function(result){$scope.fieldRules=result,$scope.reload=!0}),$scope.setRight=function(permission,property){permission[property]=!permission[property],"HasAllRights"===property&&(permission.HasOpenRights=permission[property],permission.HasApproveRights=permission[property],permission.HasDeactivateRights=permission[property],permission.HasDeleteRights=permission[property],permission.HasEditRights=permission[property],permission.HasInsertRights=permission[property],permission.HasLastRights=permission[property],permission.HasLinkRights=permission[property])},$scope.hasRight=function(permission,property){return permission[property]},$scope.setPropertyOnAll=function(property){var boolValue=$scope.allChecked(property);$scope.permissions.forEach(function(permission){permission[property]=!boolValue})},$scope.allChecked=function(property){return!!$scope.permissions&&!_.find($scope.permissions,function(o){return!o[property]})},$scope.save=function(destination){repository.updateSingle(repository.apiData.entityPermissionProfile.url,$scope.permissionProfile).then(function(result){repository.growl("Rettighetsprofilene har blitt oppdatert","success")},repository.showError)},$scope.cancel=function(){$scope.goBack("entityPermission.list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.enumEntityTypeGroup={SystemIntern:0,System:1,Administration:2,Core:3,Activity:4,Budget:5,SparePart:6,Document:7,Energy:8,Area:9,Cleaning:10,CleaningWeb:11,Key:12,Rent:13,Invoice:14,InternalRent:15,Housing:16,DutyLog:17},$scope.getModuleIcon=function(entityTypeGroupName){return repository.moduleService.getModuleIcon(entityTypeGroupName)},$scope.buildEntityTypeTree=function(){this.entityTypeGroups.forEach(function(entityTypeGroup){entityTypeGroup.permissions=[],entityTypeGroup.Prefixes.forEach(function(entityType){var permission=$scope.mapOfPermissions[entityType];permission&&entityTypeGroup.permissions.push(permission)})})}}angular.module("Plania").controller("EntityPermissionController",["$scope","$stateParams","Repository",controller])}(),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:"User.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,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 '+text+"",isHref:!0}};$scope.componentMenuOptions=function(componentXEquipment){var options=[];return $scope.hasReadAccess("Component")&&options.push(getMenuLink($rootScope.navigation.href("component.edit",{guid:componentXEquipment.GuidComponent}),"zmdi-arrow-right zmdi-hc-fw zmdi-hc-lg",translationService.translate("web-button-goTo","Gå til"))),$scope.hasEditAccess("ComponentXEquipment")&&options.push({html:' '+translationService.translate("web-button-edit","Rediger")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.editComponent(componentXEquipment)}}),$scope.hasDeleteAccess("ComponentXEquipment")&&options.push({html:' '+translationService.translate("web-button-delete","Slett")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.removeComponent(componentXEquipment)}}),options},$scope.getPropertyValue=function(item,column){return listService.GetPropertyValue(item,column)},$scope.selectedOperatingHourTypeFilter={Guid:void 0,Id:"Alle"},$scope.setOperatingHourTypeFilter=function(type){$scope.selectedOperatingHourTypeFilter=type,$scope.EquipmentOperatingHoursTable.reload()};var GetOperatingHourTypeFilters=function(){repository.GetPaginated(repository.apiData.equipmentOperatingHourType.url,0,100,{id:"asc"},{PropertyFilter:[{Property:"EquipmentOperatingHours.GuidEquipment",Operator:"=",Value:$scope.model.Guid}]},"",JSON.stringify(["Id"])).then(function(result){$scope.equipmentOperatingHourTypes=result.List,$scope.equipmentOperatingHourTypes.unshift({Guid:null,Id:"Uten type"}),$scope.equipmentOperatingHourTypes.unshift({Guid:void 0,Id:"Alle"})})},getCardTables=function(){$scope.componentTable=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=[];$scope.componentColumns.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){$scope.components=result.List,$scope.componentTable.settings().total=result.TotalCount,$scope.componentTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.conditionTable=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=[];$scope.conditionColumns.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){$scope.conditionTable.settings().total=result.TotalCount,$scope.conditionTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),GetOperatingHourTypeFilters(),$scope.EquipmentOperatingHoursTable=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=[];$scope.equipmentHourColumns.forEach(function(col){columns.push(col.Property)});var filter=params.filter();filter.PropertyFilter=[{Property:"GuidEquipment",Operator:"=",value:$scope.model.Guid}],void 0!==$scope.selectedOperatingHourTypeFilter.Guid&&filter.PropertyFilter.push({Property:"GuidEquipmentOperatingHourType",Operator:"=",value:$scope.selectedOperatingHourTypeFilter.Guid}),repository.GetPaginated(repository.apiData.equipmentOperatingHours.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.EquipmentOperatingHoursTable.settings().total=result.TotalCount,$scope.EquipmentOperatingHoursTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}});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.growl(error,"danger")})}})},columns=["Building.Id","Building.Description","Building.Guid","Building.GuidEstate","Building.Estate.Id","Building.Estate.Description","Building.Estate.Guid","CostCenter.Id","CostCenter.Description","EquipmentCategory.Description","Supplier.Description","Area.Id","Area.Description","Area.Guid","Account.Description","Person.Guid","Person.FirstName","Person.LastName"];if($scope.update)repository.getMainModel(repository.apiData.equipment.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){var eq=response.Data;$scope.model=eq,updateUserAccess(),$scope.reloads.deviations=!0,$scope.reloads.controlLists=!0,$scope.reloadDocumentTable=!0,$scope.reloadOperationalMessages=!0,$scope.equipmentOperatingHoursListSetup={VisibleColumns:$scope.equipmentHourColumns,Columns:$scope.equipmentHourColumns,Id:$scope.model.Caption},setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}),getCardTables();else{var getCategoryPrefill=function(guid){var guidCategory=guid||$scope.model.GuidEquipmentCategory;guidCategory&&repository.getSingle(repository.apiData.equipmentCategory.url,guidCategory).then(function(result){$scope.model.DynamicProperty=result.Data.DynamicProperty},function(error){repository.growl(error,"danger")})},selectedBuilding=repository.commonService.getFilterData().selectedBuilding;selectedBuilding.Guid&&($scope.model.GuidBuilding=selectedBuilding.Guid,$scope.model.Building={Caption:selectedBuilding.Name});var 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"Building":$scope.model.Building={Caption:prefill.Value.Label},$scope.model.GuidBuilding=prefill.Value.Guid;break;case"EquipmentCategory":$scope.model.EquipmentCategory={Guid:prefill.Value.Guid,Id:prefill.Value.Label,Caption:prefill.Value.Label},$scope.model.GuidEquipmentCategory=prefill.Value.Guid}else $scope.model[prefill.Property]=prefill.Value}),$stateParams.guidEntityToCopy&&repository.getSingle(repository.apiData.equipment.url,$stateParams.guidEntityToCopy).then(function(result){delete result.Data.Guid,delete result.Data.GuidGisEntity,$scope.model=result.Data,$scope.model.Id+="-N",$scope.activateAutocomplete=!1,$timeout(function(){$scope.activateAutocomplete=!0},100)}),$stateParams.showPersistantData){var persistentData=repository.persistedData.getPersistedData("equipment.create");if(persistentData){$scope.model.GuidBuilding=persistentData.GuidBuilding,$scope.model.Building="string"==typeof persistentData.Building?{Caption:persistentData.Building}:persistentData.Building,$scope.model.GuidArea=persistentData.guidArea?persistentData.guidArea:persistentData.GuidArea;var persistentArea=persistentData.area?persistentData.area:persistentData.Area;$scope.model.Area="string"==typeof persistentArea?{Caption:persistentArea}:persistentArea,$scope.model.GuidEquipmentGroup=persistentData.GuidEquipmentGroup,$scope.model.EquipmentGroup="string"==typeof persistentData.EquipmentGroup?{Caption:persistentData.EquipmentGroup}:persistentData.EquipmentGroup,persistentData.IsTemplate&&($scope.model.IsTemplate=!0)}}$stateParams.guidEntityToCopy||getCategoryPrefill(),$scope.activateAutocomplete=!0,$scope.model.IsMaintainable=!0}if($scope.sendApprovalRequest=function(){swal({title:translationService.translate("web-swal-equipment-approval-title","Vil du sende anlegget til godkjenning?"),text:translationService.translate("web-swal-equipment-approval-message",'Anlegget vil bli markert "avventer godkjenning"'),type:"info",showCancelButton:!0,confirmButtonColor:"#337ab7",confirmButtonText:translationService.translate("web-swal-equipment-button-confirm-approval","Ja, send til godkjenning!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null;var postModel=angular.copy($scope.model);postModel.RequestAction="SetPendingApproval";var success=function(result){repository.growl(translationService.translate("web-equipment-approval-sent-confirmation","Anlegg har blitt sendt til godkjenning!"),"success"),$scope.model.DataAcquisitionStatus=result.DataAcquisitionStatus},updateError=function(result){repository.growl(result,"danger")};repository.updateSingleDictionary(repository.apiData.equipment.url,postModel).then(success,updateError)})},$scope.updateEquipment=function(destination){var success=function(result){repository.growl($scope.update?translationService.translate("update-equipment-success","Anlegg har blitt oppdatert."):translationService.translate("create-equipment-success","Anlegg har blitt opprettet."),"success");var equipmentGuid=$scope.update?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,equipmentGuid),"equipment.create"===destination?(repository.persistedData.setPersistedData(destination,{guidBuilding:$scope.model.GuidBuilding,building:$scope.model.Building}),$scope.navigation.go(destination,{showPersistantData:!0,menuGuid:$scope.navigation.params.menuGuid},{reload:!0})):(repository.persistedData.clearPersistedData(),$scope.goBack(destination,{guid:equipmentGuid,menuGuid:$scope.navigation.params.menuGuid}))},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.update?repository.updateSingleDictionary(repository.apiData.equipment.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(repository.apiData.equipment.url,$scope.model).then(success).catch(error)},$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:"IS_EQUIPMENT_GROUP",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:"GUID_BUILDING",operator:"=",Value:$scope.model.GuidBuilding}]}:{};case"person":return{PropertyFilter:[{Property:"IsOperationsManager",Value:!0,Operator:"="}]}}return null},$scope.cancel=function(){repository.commonService.setLastRegisterGuid("equipment.list",$scope.model.Guid),$scope.goBack("equipment.list",{menuGuid:$scope.navigation.params.menuGuid})},$scope.removeEquipment=function(){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-equipment-message","Anlegget vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-equipment-button-confirm","Ja, slett anlegget!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.equipment.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-equipment-success","Anlegget ble fjernet!"),result,"success"),repository.growl(result,"success"),$scope.goBack("equipment.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.editComponent=function(component){$modal.open({templateUrl:"app/equipment/views/editComponentEquipment.html",controller:"EquipmentComponentController",resolve:{params:function(){return{component:component,AddComponents:!1}}}}).result.then(function(){$scope.componentTable.reload(),$scope.isComponentCollapsed=!1},function(){$scope.isComponentCollapsed=!1})},$scope.addOperatingHours=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(){$scope.EquipmentOperatingHoursTable.reload(),GetOperatingHourTypeFilters()},function(){})},$scope.editEquipmentOperatingHour=function(equipmentOperatingHour){$modal.open({templateUrl:"app/equipment/views/equipmentOperatingHoursModal.html",controller:"EquipmentOperatingHoursController",size:"sm",resolve:{params:function(){return equipmentOperatingHour}}}).result.then(function(){$scope.EquipmentOperatingHoursTable.reload(),GetOperatingHourTypeFilters()},function(){})},$scope.removeEquipmentOperatingHour=function(equipmentOperatingHour){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,equipmentOperatingHour.Guid).then(function(result){swal(translationService.translate("web-swal-equipment-equipmentOperatingHour-success","Driftstimene ble fjernet!"),result,"success"),$scope.EquipmentOperatingHoursTable.reload(),GetOperatingHourTypeFilters()})})},$scope.addComponents=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"}],useObjects:!1}}}}).result.then(function(guids){var model=[];guids.forEach(function(guid){model.push({GuidEquipment:$scope.model.Guid,GuidComponent:guid})}),repository.createMultipleWithGuid(repository.apiData.componentEquipment.url,$scope.model.Guid,JSON.stringify(model)).then(function(result){$scope.componentTable.reload()})},function(){})},$scope.removeComponent=function(component){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,component.Guid).then(function(result){swal(translationService.translate("web-swal-equipment-component-success","Komponenten ble fjernet!"),result,"success"),$scope.componentTable.reload()})})},$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})},$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.equipmentHoursMenuOptions=function(equipmentHours){var options=[];return $scope.hasEditAccess("EquipmentOperatingHours")&&options.push({html:' '+translationService.translate("web-button-edit","Rediger")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.editEquipmentOperatingHour(equipmentHours)}}),$scope.hasDeleteAccess("EquipmentOperatingHours")&&options.push({html:' '+translationService.translate("web-button-delete","Slett")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.removeEquipmentOperatingHour(equipmentHours)}}),options},$scope.$on($scope.events.newSelection,function(){updateUserAccess()}),$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")},function(){})}}}angular.module("Plania").controller("EquipmentController",["$scope","Repository","$stateParams","ngTableParams","$modal","RegisteredFieldService","authService","TranslationService","ListService","$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,$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.updateSingleDictionary(repository.apiData.equipmentOperatingHours.url,$scope.model).then(success,error):repository.createSingleDictionary(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,$localStorage,registeredFieldService,$modal,translationService){var defaultEquipmentOperatingHourType="Strøm";$scope.dropdown={EquipmentOperatingHourType:{Id:"Ikke valgt",Guid:null},EquipmentOperatingHourTypes:[{Id:"Ikke valgt",Guid:null}],BuildingCategory:{Description:"Ikke valgt",Guid:null},BuildingCategories:[{Description:"Ikke valgt",Guid:null}],EquipmentCategory:{Description:"Ikke valgt",Guid:null},EquipmentCategories:[{Description:"Ikke valgt",Guid:null}]},$scope.showEquipmentOperatingHourTypeDropdown=!1,$scope.availableYears=[],$scope.endYear=(new Date).getFullYear(),$scope.startYear=$scope.endYear-1;for(var i=$scope.endYear;i>$scope.endYear-100;i--)$scope.availableYears.push(i);var getDropdownData=function(){$scope.dropdown.EquipmentOperatingHourType={Id:"Ikke valgt",Guid:null},$scope.dropdown.BuildingCategory={Description:"Ikke valgt",Guid:null},$scope.dropdown.EquipmentCategory={Description:"Ikke valgt",Guid:null},registeredFieldService.getFieldRule(repository.commonService.prefix.EquipmentOperatingHours,"GuidEquipmentOperatingHourType").then(function(result){if(result.Hidden||result.ExternallyHidden&&$localStorage.userData.isExternalUser)return void $scope.getChartData();$scope.showEquipmentOperatingHourTypeDropdown=!0,repository.GetPaginated(repository.apiData.equipmentOperatingHourType.url,0,20,{Id:"asc"}).then(function(result){if($scope.dropdown.EquipmentOperatingHourTypes=[{Id:"Ikke valgt",Guid:null}].concat(result.List),$scope.dropdown.EquipmentOperatingHourTypes.length>1){var defaultEnergy=_.find($scope.dropdown.EquipmentOperatingHourTypes,{Id:defaultEquipmentOperatingHourType});$scope.dropdown.EquipmentOperatingHourType=defaultEnergy||$scope.dropdown.EquipmentOperatingHourTypes[1]}$scope.getChartData()})}),repository.GetPaginated(repository.apiData.buildingCategory.url,0,20,{Description:"asc"}).then(function(result){$scope.dropdown.BuildingCategories=[{Description:"Ikke valgt",Guid:null}].concat(result.List)}),repository.GetPaginated(repository.apiData.equipmentCategory.url,0,20,{Description:"asc"}).then(function(result){$scope.dropdown.EquipmentCategories=[{Description:"Ikke valgt",Guid:null}].concat(result.List)})};getDropdownData();var getMonthNameByIndex=function(monthIndex){var monthName="Jan";return"2"!==monthIndex&&2!==monthIndex||(monthName="Feb"),"3"!==monthIndex&&3!==monthIndex||(monthName="Mar"),"4"!==monthIndex&&4!==monthIndex||(monthName="Apr"),"5"!==monthIndex&&5!==monthIndex||(monthName="Mai"),"6"!==monthIndex&&6!==monthIndex||(monthName="Jun"),"7"!==monthIndex&&7!==monthIndex||(monthName="Jul"),"8"!==monthIndex&&8!==monthIndex||(monthName="Aug"),"9"!==monthIndex&&9!==monthIndex||(monthName="Sept"),"10"!==monthIndex&&10!==monthIndex||(monthName="Okt"),"11"!==monthIndex&&11!==monthIndex||(monthName="Nov"),"12"!==monthIndex&&12!==monthIndex||(monthName="Des"),monthName};$scope.formatLabel=function(sender){var labelText=sender.data.label.Text;labelText>=1e6?sender.data.label.Text=labelText/1e6+"M":labelText>=1e3&&(sender.data.label.Text=labelText/1e3+"K")},$scope.downloadClientside=function(id,type){var chart=$("#"+id).ejChart("instance"),exporting=chart.model.exportSettings;exporting.fileName=chart.model.title+(new Date).toISOString(),exporting.angle=0,exporting.type=type||"png",exporting.mode="client";var data=chart.export();if(window.navigator.msSaveOrOpenBlob){var blob;"png"===type?blob=data.msToBlob():"jpg"===type?blob=data.msToBlob(null,"image/jpeg"):"svg"===type&&(data=decodeURIComponent(data),blob=new Blob([data],{type:"image/svg-xml"})),window.navigator.msSaveOrOpenBlob(blob,exporting.fileName+"."+type)}else this.download=exporting.fileName+"."+type,this.href="png"===type?data.toDataURL():"jpg"===type?data.toDataURL("image/jpeg"):"data:text/plain;charset=utf-8,"+data};var getCommonParams=function(){var params="";params+="fromYear="+$scope.startYear,params+="&toYear="+$scope.endYear,$scope.dropdown.EquipmentOperatingHourType&&$scope.dropdown.EquipmentOperatingHourType.Guid&&(params+="&guidEquipmentOperatingHourType="+$scope.dropdown.EquipmentOperatingHourType.Guid),$scope.dropdown.BuildingCategory&&$scope.dropdown.BuildingCategory.Guid&&(params+="&guidBuildingCategory="+$scope.dropdown.BuildingCategory.Guid),$scope.dropdown.EquipmentCategory&&$scope.dropdown.EquipmentCategory.Guid&&(params+="&guidEquipmentCategory="+$scope.dropdown.BuildingCategory.Guid);var filter=repository.commonService.getFilterData();return filter.selectedBuilding&&filter.selectedBuilding.Guid&&(params+="&guidBuilding="+filter.selectedBuilding.Guid),filter.selectedEstate&&filter.selectedEstate.Guid&&(params+="&guidEstate="+filter.selectedEstate.Guid),filter.selectedSelection&&filter.selectedSelection.Guid&&(params+="&guidSelection="+filter.selectedSelection.Guid),params};$scope.monthlyConsumptionChart=new function(){var me=this;this.columnSeries=[],this.lineSeries=[],this.chartData=[],this.chartSettings={legend:{visible:!0,shape:"seriesType",position:"top",itemStyle:{width:15,height:15},font:{size:"15px"}},monthlyConsumptionChartTitle:{text:"Forbruk per måned"},monthlyConsumptionPerAreaChartTitle:{text:"Forbruk per måned fordelt på areal"},size:{height:"600",width:"100%"},commonSeriesOptions:{tooltip:{visible:!0}},primaryXAxis:{title:{text:"Måned"}},primaryYAxis:{title:{text:"Forbruk"}},axes:[{majorGridLines:{visible:!1},orientation:"Vertical",opposedPosition:!0,axisLine:{visible:!1},rangePadding:"normal",name:"yAxis",title:{text:"Akkumulert"}}],combinationmarker:{shape:"circle",size:{height:8,width:8},visible:!0},combinationborder:{width:2}},this.updateChart=function(){var chart=$("#monthlyConsumptionChart").ejChart("instance"),chart2=$("#monthlyConsumptionPerAreaChart").ejChart("instance");chart.model.legend.columnCount=me.columnSeries.length,chart2.model.legend.columnCount=me.columnSeries.length,chart.model.primaryYAxis.visibleLabels.forEach(function(label){label.displayText=label.displayText+"k",label.Text=label.Text+"k",label.Value=label.Value+"k",label.region.labelText=label.region.labelText+"k",label.region.trimText=label.region.trimText+"k"});var columnSeriesTitle=$scope.dropdown.EquipmentOperatingHourType.Guid?$scope.dropdown.EquipmentOperatingHourType.Id:"Forbruk";chart.model.primaryYAxis.title.text=columnSeriesTitle,chart2.model.primaryYAxis.title.text=columnSeriesTitle;var lineSeriesTitle="Akkumulert";chart.model.axes[0].title.text=lineSeriesTitle,chart2.model.axes[0].title.text=lineSeriesTitle,chart.model.series=[],chart2.model.series=[],me.columnSeries.forEach(function(series){chart.model.series.push({dataSource:me.chartData,name:series.name,xName:series.xName,yName:series.yName,type:"column",tooltip:{format:"#point.x# - #series.name#
"+columnSeriesTitle+" : ej.format(#point.y#,n0)
"}}),chart2.model.series.push({dataSource:me.chartData,name:series.name,xName:series.xName,yName:series.yName2,type:"column",tooltip:{format:"#point.x# - #series.name#
"+columnSeriesTitle+" : ej.format(#point.y#,n0)
"}})}),me.lineSeries.forEach(function(series){chart.model.series.push({dataSource:me.chartData,name:series.name,xName:series.xName,yName:series.yName,type:"line",tooltip:{format:"#point.x# - #series.name#
"+lineSeriesTitle+" : ej.format(#point.y#,n0)
"},yAxisName:"yAxis",marker:me.chartSettings.combinationmarker,border:me.chartSettings.combinationborder}),chart2.model.series.push({dataSource:me.chartData,name:series.name,xName:series.xName,yName:series.yName2,type:"line",tooltip:{format:"#point.x# - #series.name#
"+lineSeriesTitle+" : ej.format(#point.y#,n0)
"},yAxisName:"yAxis",marker:me.chartSettings.combinationmarker,border:me.chartSettings.combinationborder})}),chart.redraw(),chart2.redraw()},this.getChartData=function(){var params=getCommonParams();repository.getWithUrlParameter(repository.apiData.equipmentOperatingHours.endpoint.consumption,params).then(function(result){var chartData=[],grouped=_.groupBy(result,"Month");Object.keys(grouped).forEach(function(month){var newData={month:getMonthNameByIndex(month)};grouped[month].forEach(function(d){newData["value"+d.Year]=d.Value?d.Value:void 0,newData["accValue"+d.Year]=d.AccumulatedValue?d.AccumulatedValue:void 0,newData["valuePerArea"+d.Year]=d.ValuePerArea?d.ValuePerArea:void 0,newData["accValuePerArea"+d.Year]=d.AccumulatedValuePerArea?d.AccumulatedValuePerArea:void 0}),chartData.push(newData)});var yearlyGrouped=_.groupBy(result,"Year"),lineSeries=[],columnSeries=[];Object.keys(yearlyGrouped).forEach(function(year){lineSeries.push({name:year+" (Akk)",xName:"month",yName:"accValue"+year,yName2:"accValuePerArea"+year}),columnSeries.push({name:year,xName:"month",yName:"value"+year,yName2:"valuePerArea"+year})}),me.columnSeries=columnSeries,me.lineSeries=lineSeries,me.chartData=chartData,me.updateChart()})}},$scope.buildingSummaryChart=new function(){var me=this;this.chartData=[],this.chartSettings={legend:{visible:!1},buildingSummaryChartTitle:{text:"Forbruk per bygg"},buildingSummaryChartPerAreaChartTitle:{text:"Forbruk per bygg fordelt på areal"},size:{width:"100%"},commonSeriesOptions:{tooltip:{visible:!0}},primaryXAxis:{title:{text:"Bygg"}},primaryYAxis:{title:{text:"Forbruk"}}},this.updateChart=function(){var chart=$("#buildingSummaryChart").ejChart("instance"),chart2=$("#buildingSummaryChartPerAreaChart").ejChart("instance"),titleText=$scope.dropdown.EquipmentOperatingHourType.Guid?$scope.dropdown.EquipmentOperatingHourType.Id:"Forbruk";chart.model.primaryYAxis.title.text=titleText,chart2.model.primaryYAxis.title.text=titleText,chart.model.series=[{dataSource:_.sortBy(me.chartData,"Value"),name:"Bygg",xName:"Caption",yName:"Value",type:"bar",tooltip:{format:"#point.x#
"+titleText+" : ej.format(#point.y#,n0)
"}}],chart2.model.series=[{dataSource:_.sortBy(me.chartData,"ValuePerArea"),name:"Bygg",xName:"Caption",yName:"ValuePerArea",type:"bar",tooltip:{format:"#point.x#
"+titleText+" : ej.format(#point.y#,n0)
"}}],chart.model.size.height=100+40*(me.chartData.length+1),chart2.model.size.height=100+40*(me.chartData.length+1),chart.redraw(),chart2.redraw()},this.getChartData=function(){var params=getCommonParams();repository.getWithUrlParameter(repository.apiData.equipmentOperatingHours.endpoint.buildingSummary,params).then(function(result){result.forEach(function(r){r.Caption=[r.Id,r.Description].join(" - ")}),me.chartData=result,me.updateChart()})}},$scope.getChartData=function(){$scope.monthlyConsumptionChart.getChartData(),$scope.buildingSummaryChart.getChartData()},$scope.$on($scope.events.newSelection,function(){getDropdownData()})}angular.module("Plania").controller("EquipmentOperatingHoursDashboardController",["$scope","Repository","$localStorage","RegisteredFieldService","$modal","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,ngTableParams,$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.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","CostCenter.Id","CostCenter.Description"];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")})},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.updateSingleDictionary(repository.apiData.estate.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(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.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.onFileSelect=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,GuidEstate:$scope.model.Guid};files.push(newFile),onLoadEndHandler()},reader.readAsDataURL(file)}function onLoadEndHandler(image){$scope.model.GuidEstateImage&&repository.deleteSingle(repository.apiData.image.url,$scope.model.GuidEstateImage).then(function(result){console.log(result)}),repository.createMultiple(repository.apiData.image.url,files).then(function(result){$scope.model.GuidEstateImage=result[0].Guid},function(error){repository.growl(error)})}if(images&&0!==images.length){var files=[];handleFileUpload(images[0])}},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"person":return filter.PropertyFilter=[{Property:"IsOperationsManager",Value:1,Operator:"="}],filter}}}angular.module("Plania").controller("EstateController",["$scope","Repository","$stateParams","ngTableParams","$modal","TranslationService",controller])}(),function(){function controller($scope,$window,repository,$localStorage,constants,translationService,columnFormatService,$modal){$scope.model={UserAuthentication:0},$scope.times={},$scope.activateAutocomplete=!1,repository.getSingleWithNoParameter(repository.apiData.generalOptions.url).then(function(result){$scope.model=result.Data,$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.selectedMailServerConnectionType=_.find($scope.enumMailServerConnectionType,{value:$scope.model.MailServerConnectionType}),$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:"zmdi-email"},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:"zmdi-case"},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){Array.isArray(error)&&(error.forEach(function(err){"BarcodeEquipmentFormat"===err&&($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&&($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&&($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&&($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"))}),repository.growl("Feil i generering av QR-koder, fiks feilene før du kan lagre endringer på kundeprofilen","danger")),"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.createMultiple(repository.apiData.gisManagement.url+"gisManagement",{}).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;break;default:console.log("Not Implemented")}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.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:"zmdi-city"},iconAnchor:[10,33],popupAnchor:[0,-19],weight:8},building:{entity:"Building",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"zmdi-home"},iconAnchor:[10,33],popupAnchor:[0,-19],weight:8},equipment:{entity:"Equipment",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"zmdi-settings"},iconAnchor:[10,24],popupAnchor:[0,-10],weight:8},request:{entity:"Request",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"zmdi-email"},iconAnchor:[10,24],popupAnchor:[0,-10],weight:8},workOrder:{entity:"WorkOrder",displayType:"marker",marker:{shape:"circle",color:"blue",warningColor:"red",icon:"zmdi-case"},iconAnchor:[10,24],popupAnchor:[0,-10],weight:8}}};$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.enumMailServerConnectionType=[{value:0,text:translationService.translate("web-enum-mailserverconnection-standard","Standard")},{value:1,text:translationService.translate("web-enum-mailserverconnection-tls","TLS")},{value:2,text:translationService.translate("web-enum-mailserverconnection-ssl","SSL")}],$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})}}angular.module("Plania").controller("GeneralOptionsController",["$scope","$window","Repository","$localStorage","Constants","TranslationService","ColumnFormatService","$modal",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.updateSingleDictionary(repository.apiData.hourType.url,$scope.model).then(success,error):repository.createSingleDictionary(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.Area1&&($scope.area=areaXEntity.Area1.Id+" - "+areaXEntity.Area1.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=["Area1.Id","Area1.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.updateSingleDictionary(repository.apiData.areaXEntity.url,$scope.areaXEntity).then(success,error):repository.createSingleDictionary(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,$localStorage){$scope.isUpdate="housing.edit"===$scope.navigation.current.name,$scope.model=$stateParams.model||{Guid:$stateParams.guid},$scope.isBBY=$localStorage.generalOptions.IsBBY,$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","Leie pr. måned"),Property:"RentalPricePerMonth",PropertyType:"double"}],$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(){repository.persistedData.setPersistedData("workOrder.create",{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}),$scope.navigation.go("workOrder.create",{showPersistantData:!0},{reload:!0})};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.updateSingleDictionary(repository.apiData.area.url,$scope.model).then(success,error):repository.createSingleDictionary(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;i=file.total?"success":"info")})},$scope.ok=function(){$modalInstance.close()},$scope.cancel=function(){$modalInstance.dismiss()}}angular.module("Plania").controller("CreateIfcFileModalController",["$scope","$modalInstance","Repository",controller])}(),function(){function controller($scope,$stateParams,repository,translationService){$scope.isUpdate="ifcFile.edit"===$scope.navigation.current.name,$scope.activateAutocomplete=!1,$scope.model={Guid:$stateParams.guid},$scope.viewMode=!!$scope.isUpdate,$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.IfcFile,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.IfcFile,checkOtherDO)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.IfcFile),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.IfcFile)};updateAccess();var setProperties=function(){var ifcFile=$scope.model;ifcFile.Building&&($scope.building=$scope.getEntityCaption(ifcFile.Building))};if($scope.isUpdate){var columns=["Building.Id","Building.Description"];repository.getSingle(repository.apiData.ifcFile.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,updateAccess(),setProperties(),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?"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),$scope.goBack(destination,{guid:buildingGuid,menuGuid:$scope.navigation.params.menuGuid})},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.updateSingleDictionary(repository.apiData.building.url,$scope.model).then(success).catch(error)):($scope.model.BuildingXBuildingSelection=[{GuidBuildingSelection:repository.commonService.getFilterData().selectedSelection.Guid}],repository.createSingleDictionary(repository.apiData.building.url,$scope.model).then(success,error))},$scope.cancel=function(){$scope.goBack("ifcFile.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-ifcFile-message","IFC-filen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-ifcFile-button-confirm","Ja, fjern IFC-filen"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.ifcFile.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-ifcFile-success","IFC-filen ble fjernet!"),result,"success"),$scope.goBack("ifcFile.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.$on($scope.events.newSelection,function(){updateAccess()})}angular.module("Plania").controller("IfcEditController",["$scope","$stateParams","Repository","TranslationService",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,authService,$window,config){$scope.model={},$scope.extractedData=[],$scope.showExtractedJsonData=!0;var getJsonValue=function(property){for(var value=$scope.model.JsonData,splittedProperty=property.split("."),i=0;i0},$scope.showUsernamePasswordLogin=!1,$scope.showTwoFactor=!0}$scope.status=null,repository.getSingleWithNoParameter("/PlaniaStatus").then(function(result){$scope.status=result,$scope.showSamlLogin=result.ShowSamlLogin,$scope.showUsernamePasswordLogin=result.ShowUsernamePasswordLogin,$scope.showMobileApp=result.ShowMobileApp,$localStorage.planiaStatus=result}),$location.search().error&&($scope.alertMessage=$location.search().error),$stateParams.message&&($scope.alertMessage=$stateParams.message),$stateParams.refreshtoken&&($scope.hideLoginBox=!0,repository.authService.authenticateFederationRefresh($stateParams.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()}):repository.authService.authenticateSSO().then(function(result){result.success&&afterLogonNavigate()}),$scope.samlLogin=function(){repository.authService.authenticateSaml()},$scope.username="",$scope.password="",$scope.isLoginActive=!1;var afterLogonRememberTwoFactor=function(twoFactor){if(twoFactor&&twoFactor.rememberMe){var daysToRemember=$scope.status.TwoFactorExpirationPeriodInDays;if(daysToRemember>0){var rememberMeInfo={username:$scope.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.username)return repository.growl("Du må fylle ut brukernavn","danger"),void($scope.isLoginActive=!1);if(!$scope.password)return repository.growl("Du må fylle ut passord","danger"),void($scope.isLoginActive=!1);var logoutOtherLocation=!0===$scope.confirmLogout,twoFactorRemembered=getRememberedTwoFactorForUser($scope.username);twoFactorRemembered||$scope.twoFactor&&$scope.twoFactor.rememberMe&&($scope.twoFactor.newSecret=planiaUtils.randomString(100)),repository.authService.authenticate($scope.username,$scope.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.showUsernamePasswordLogin=!0,$scope.showTwoFactor=!1},$scope.reloadPage=function(){$state.reload()}}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.setQs({}),signalR.stop(),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])}(),angular.module("Plania").directive("gantt",function(){function controller(scope){var monthArray=["Januar","Februar","Mars","April","Mai","Juni","Juli","August","September","Oktober","November","Desember"],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){var state=data.GuidWorkOrder?"workOrder.edit":"periodicTask.edit",guid=data.GuidWorkOrder?data.GuidWorkOrder:data.GuidPeriodicTask;scope.$root.navigation.go(state,{guid:guid,menuGuid:scope.$root.navigation.params.menuGuid})},onAddClick:function(dt,rowId){},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.$watchGroup(["tasks"],function(newValues,oldValues,scope){newValues!==oldValues&&newValues&&renderGantt()})}return{restrict:"E",scope:{tasks:"=tasks",viewMode:"=viewMode",filters:"=filters",count:"=count",columnData:"=columnData"},controller:["$scope",controller],templateUrl:"/app/maintenancePlan/gantt.html"}}),function(){function controller($scope,repository,translationService,$filter){$scope.hasInitialized=!1,$scope.showFilters=!0,$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={},$scope.autocompleteModel={},$scope.filters={ActivityStatus:"Active",PropertyFilter:[]},$scope.loading=!1,$scope.count=100,$scope.totalCount=0,$scope.sortingProperties=[{value:"Description",label:"Beskrivelse",type:"string"},{value:"StartDate",label:"Startdato",type:"date"},{value:"EstimatedCost",label:"Estimert kostnad",type:"string"},{value:"EstimatedTime",label:"Estimert tid",type:"string"},{value:"Building.Id",label:"Bygning ID",typee:"string"},{value:"Building.Description",label:"Bygningsbeskrivelse",type:"string"},{value:"Equipment.Id",label:"Anlegg ID",type:"string"},{value:"Equipment.Description",label:"Anleggsbeskrivelse",type:"string"},{value:"Area.Id",label:"Areal ID",type:"string"},{value:"ResourceGroup.Id",label:"Ressurs"},{value:"Type",label:"Arbeidsordretype"},{value:"ActivityCategory.Description",label:"Kategori"},{value:"Supplier.Description",label:"Leverandør"},{value:"Person.LastName",label:"Ansvarlig person(Etternavn)"}],$scope.workOrderTypes=[{title:"KO",value:0},{title:"PR",value:1},{title:"FV",value:2},{title:"ME",value:3},{title:"Test",value:4},{title:"Kontroll",value:5},{title:"AV",value:6},{title:"Alarm",value:7},{title:"VL",value:8},{title:"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"}],$scope.filters.dueDateInterval="nextThreeMonths";var getDueDateFilters=function(filters){switch(filters.dueDateInterval){case"nextMonth":filters.PropertyFilter.push({Property:"DueDate",Operator:"<=",Value:moment().utc().startOf("day").add(1,"month").toISOString()});break;case"nextThreeMonths":filters.PropertyFilter.push({Property:"DueDate",Operator:"<=",Value:moment().utc().startOf("day").add(3,"month").toISOString()});break;case"nextHalfYear":filters.PropertyFilter.push({Property:"DueDate",Operator:"<=",Value:moment().utc().startOf("day").add(6,"month").toISOString()});break;case"nextYear":filters.PropertyFilter.push({Property:"DueDate",Operator:"<=",Value:moment().utc().startOf("day").add(1,"year").toISOString()})}delete filters.dueDateInterval};$scope.getData=function(){if($scope.hasInitialized){"months"===$scope.viewMode&&($scope.filters.NumberOfYearsToCalculate=3);var filters=angular.copy($scope.filters);switch(getDueDateFilters(filters),filters.Interval=1,$scope.viewMode){case"months":filters.Interval=3;break;case"weeks":filters.Interval=2;break;case"days":filters.Interval=1}$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={name:item.Title,filterValue:item.Subtitle,filterLabel:selectedSorting.label,detailProperties:[],dataObj:item,values:[]};item.Building&&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+=100,$scope.getData())},$scope.lessData=function(){$scope.loading||($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()};var findExistingFilter=function(key){return _.findIndex($scope.filters.PropertyFilter,function(p){return p.Property===key})};$scope.$watch("filterValues",function(newValue,oldValue){if(newValue!==oldValue){for(var key in newValue){var indexOfFilter=findExistingFilter(key),currentFilterValue=$scope.filterValues[key];-1!==indexOfFilter?0===currentFilterValue||currentFilterValue&&""!==currentFilterValue?$scope.filters.PropertyFilter[indexOfFilter].Value=currentFilterValue:$scope.filters.PropertyFilter.splice(indexOfFilter,1):$scope.filters.PropertyFilter.push({Property:key,Operator:"=",Value:currentFilterValue})}$scope.getData()}},!0),$scope.$watch("filters.showWorkordersWithoutStartDate",function(newValue,oldValue){newValue!==oldValue&&$scope.getData()}),$scope.$watch("filters.dueDateInterval",function(newValue,oldValue){newValue!==oldValue&&$scope.getData()}),$scope.$on($scope.events.newSelection,function(){$scope.getData()})}angular.module("Plania").controller("MaintenancePlanController",["$scope","Repository","TranslationService","$filter",controller])}(),function(){function controller($scope,ngTableParams,$filter){switch($scope.selectedTheme){case"basicData":$scope.title="Grunndata";break;case"workOrder":$scope.title="Arbeidsordre";break;case"request":$scope.title="Meldinger";break;default:$scope.title="Punkter"}$scope.mapClusterTableSmall=new ngTableParams({page:1,count:10},{total:$scope.clustermarkers.length,getData:function($defer,params){var data=params.sorting()?$filter("orderBy")($scope.clustermarkers,params.orderBy()):$scope.clustermarkers;data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$defer.resolve(data)}})}angular.module("Plania").directive("clusterPopup",function(){return{restrict:"E",controller:["$scope","ngTableParams","$filter",controller],templateUrl:"app/map/views/clusterMessage.html",link:function(scope,elements,attrs){}}})}(),function(){function controller($scope,ngTableParams,$filter,translationService){switch($scope.selectedTheme){case"basicData":$scope.title=translationService.translate("web-map-toolbar-selectTheme-Basicdata","Grunndata");break;case"workOrder":$scope.title=translationService.translate("web-map-toolbar-selectTheme-workOrder","Arbeidsordre");break;case"request":$scope.title=translationService.translate("web-map-toolbar-selectTheme-request","Meldinger");break;default:$scope.title="Punkter"}$scope.mapClusterTableSmall=new ngTableParams({page:1,count:10},{total:$scope.clustermarkers.length,getData:function($defer,params){var data=params.sorting()?$filter("orderBy")($scope.clustermarkers,params.orderBy()):$scope.clustermarkers;data=data.slice((params.page()-1)*params.count(),params.page()*params.count()),$defer.resolve(data)}})}angular.module("Plania").directive("mapClusterPopup",function(){return{restrict:"E",controller:["$scope","ngTableParams","$filter","TranslationService",controller],templateUrl:"app/map/views/mapClusterPopupDirective.html",link:function(scope,elements,attrs){}}})}(),function(){function controller($scope,repository,leafletData,translationService,$stateParams,$localStorage,constants,$compile,$window,$location){function addFilterWatcher(watch){basicDataWatcher=$scope.$watch(watch,function(newValue,oldValue){newValue!==oldValue&&onReloadData()},!0)}function getTotalBottomMargin(element){var margin=0;try{for(var elem=element.parent();elem&&elem.css;elem=elem.parent())margin+=parseInt(elem.css("padding-bottom")),margin+=parseInt(elem.css("margin-bottom")),margin+=parseInt(elem.css("border-bottom-width"))}catch(e){}return margin}function onReloadData(){leafletData.getMap("map").then(function(map){var filters={};for(var property in $scope.panelFilter)filters[property]=$scope.panelFilter[property];var sorting={};filters.PropertyFilter=repository.mapService.getPropertyFilter("gisEntity",$stateParams),$scope.mapData.markers={},$scope.mapData.paths={},repository.GetPaginated(repository.apiData.gisManagement.url,0,-1,sorting,filters,null,JSON.stringify([])).then(function(result){$scope.mapData.markers=result.markers,$scope.mapData.paths=result.paths}),$scope.$on("leafletDirectiveMarker.click",function(event,args){var marker=$scope.mapData.markers[args.modelName];"workOrder"===$scope.selectedTheme?marker.message="
':marker.message='

'+marker.caption+"

"}),$scope.urlParams.lat?map.setView({lat:$scope.urlParams.lat,lng:$scope.urlParams.lng},$scope.urlParams.zoom):centerOnMarkers(),$location.search("panelFilter",JSON.stringify($scope.panelFilter)),$scope.urlParams=$location.search()})}function centerOnMarkers(){_.isEmpty($scope.mapData.markers)&&_.isEmpty($scope.mapData.paths)||leafletData.getMap("map").then(function(map){var latLngs=[];for(var marker in $scope.mapData.markers)$scope.mapData.markers[marker].lat&&$scope.mapData.markers[marker].lng&&latLngs.push(new L.LatLng($scope.mapData.markers[marker].lat,$scope.mapData.markers[marker].lng));for(var path in $scope.mapData.paths)$scope.mapData.paths[path].latlngs[0].lat&&$scope.mapData.paths[path].latlngs[0].lng&&latLngs.push(new L.LatLng($scope.mapData.paths[path].latlngs[0].lat,$scope.mapData.paths[path].latlngs[0].lng));var bounds=new L.LatLngBounds(latLngs),existingZoom=map.getZoom();map.fitBounds(bounds,{padding:[50,50]}),0===map.getZoom()&&map.setZoom(existingZoom)})}$scope.entityInfos={},$scope.urlParams=$location.search(),$scope.navigation.params.menuGuid&&repository.getMenuParameters($scope.navigation.params.menuGuid),$scope.mapData={Norge:{lat:63.43,lng:10.4,zoom:5},layers:{overlays:{markercluster:{name:"MarkerCluster",type:"markercluster",layerOptions:{spiderfyDistanceMultiplier:1.5,showCoverageOnHover:!1,maxClusterRadius:60},visible:!0}}},defaults:{scrollWheelZoom:!1,zoom:1}},$scope.leafletData=leafletData,$scope.shouldCenterOnMarkers=!0,$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"}],$scope.requestFilterStatusChange=function(newValue){$scope.panelFilter.request.status=newValue,$scope.shouldCenterOnMarkers||($scope.shouldCenterOnMarkers=!0,onReloadData())};var filterWatcher=function(){};if($scope.themeChanged=function(panelFilter){filterWatcher(),"basicData"===$scope.selectedTheme&&($scope.panelFilter=panelFilter||{showBasicData:!0,basicData:{showEstate:!0,showBuilding:!0,showEquipment:!1}},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")),$location.search("theme",$scope.selectedTheme),$location.search("panelFilter",JSON.stringify($scope.panelFilter)),$scope.shouldCenterOnMarkers=!0,onReloadData()},$localStorage.generalOptions.MapSettings){var settings=JSON.parse($localStorage.generalOptions.MapSettings);settings.entityInfo&&($scope.entityInfos=settings.entityInfo),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},$scope.mapData.layers.baselayers={osm:{name:$scope.mapData.defaults.tileLayerOptions.attribution,type:"xyz",url:$scope.mapData.defaults.tileLayer}},settings.CrsCode&&settings.Proj4Def&&options&&($scope.mapData.defaults.crs=new L.Proj.CRS(settings.CrsCode,settings.Proj4Def,options))}$scope.mapData.paths={},$scope.showFilter=!1,$scope.panelFilter={showBasicData:!0};var resizeMap=function(){var map=$("#map"),currentHeight=map.height(),height=$(window).innerHeight()-map.offset().top-getTotalBottomMargin(map);currentHeight!==height&&(map.height(height),leafletData.getMap("map").then(function(map){map.invalidateSize(),map._resetView(map.getCenter(),map.getZoom(),!0)}))};leafletData.getMap("map").then(function(){setTimeout(function(){resizeMap()},500)}),$window.addEventListener("resize",resizeMap()),$scope.$on("$destroy",function(){$window.removeEventListener("resize",resizeMap())}),$scope.selectedTheme=$scope.urlParams.theme?$scope.urlParams.theme:"basicData";var panelFilter=$scope.urlParams.panelFilter?JSON.parse($scope.urlParams.panelFilter):null;$scope.themeChanged(panelFilter),leafletData.getMap("map").then(function(map){map.eachLayer(function(layer){layer.on("spiderfied",function(a){var message;if("workOrder"===$scope.selectedTheme){var guids={GuidBuilding:[],GuidEstate:[],GuidEquipment:[]};a.markers.forEach(function(mark){"Building"===mark.options.entity?guids.GuidBuilding.push(mark.options.entityGuid):"Estate"===mark.options.entity?guids.GuidEstate.push(mark.options.entityGuid):"Equipment"===mark.options.entity&&guids.GuidEquipment.push(mark.options.entityGuid)}),guids.GuidBuilding=guids.GuidBuilding.join(","),guids.GuidEstate=guids.GuidEstate.join(","),guids.GuidEquipment=guids.GuidEquipment.join(",");var caption=translationService.translate("web-map-toolbar-selectTheme-workOrder","Arbeidsordre");message=$compile("
')($scope)}else $scope.clustermarkers=a.markers.map(function(mark){return{entity:mark.options.entity,entityGuid:mark.options.entityGuid,caption:mark.options.caption}}),message=$compile("")($scope);a.cluster.closePopup(),a.cluster.bindPopup(message[0]),setTimeout(function(){a.cluster.openPopup()},100)})}),map.on("moveend",function(m){$location.search("zoom",map.getZoom()),$location.search("lat",map.getCenter().lat),$location.search("lng",map.getCenter().lng)})}),$scope.$on($scope.events.newSelection,function(){$scope.mapData.markers={},$scope.mapData.paths={},$scope.shouldCenterOnMarkers=!0,onReloadData()})}angular.module("Plania").controller("MapController",["$scope","Repository","leafletData","TranslationService","$stateParams","$localStorage","Constants","$compile","$window","$location",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,$modalInstance,params,repository,ngTableParams,$filter){$scope.availableMenus=params.menus,$scope.selectMenu=function(menu){$modalInstance.close(menu)},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("AddMobileMenuModalController",["$scope","$modalInstance","params",controller])}(),function(){function listController($scope,repository,$stateParams,ngTableParams,$modal,translationService,moduleService,listService,$state,$localStorage){$scope.isUpdate="mobileMenuProfile.edit"===$scope.navigation.current.name,$scope.model={},$scope.mobileVersion="new";var updateAccess=function(){$scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.MobileMenuProfile),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.MobileMenuProfile)};updateAccess(),$scope.activityPageItems=[{key:0,indexPosition:0,title:translationService.translate("web-enum-MobileMenuProfileItems-MyWorkOrders","Mine arbeidsordre"),available:moduleService.hasModule(moduleService.moduleFlags.Activity),visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-tasks","Oppgaver"),icon:"zmdi-account",popoverText:translationService.translate("web-mobilemenuprofile-myWorkOrder-popoverText",'Arbeidsordre hvor innlogget person står som ansvarlig. Dersom mobilmenyen "Mine rutiner" er aktiv for bruker, vil arbeidsordrer som er knyttet til en periodisk rutine ikke være tilgjengelig på dette menypunktet.')},{key:10,indexPosition:1,title:translationService.translate("web-enum-MobileMenuProfileItems-myFVWorkOrders","Mine rutiner"),available:moduleService.hasModule(moduleService.moduleFlags.Activity),visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-tasks","Oppgaver"),icon:"zmdi-account",popoverText:translationService.translate("web-mobilemenuprofile-myFVWorkOrders-popoverText","Arbeidsordre hvor innlogget person står som ansvarlig og filtert på arbeidsordre som kommer fra periodiske rutiner.")},{key:8,indexPosition:2,title:translationService.translate("web-enum-MobileMenuProfileItems-MyResourceResponsibleWorkOrders","Mitt fagansvar"),available:moduleService.hasModule(moduleService.moduleFlags.Activity),visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-tasks","Oppgaver"),icon:"zmdi-account",popoverText:translationService.translate("web-mobilemenuprofile-MyResourceResponsibleWorkOrders-popoverText","Arbeidsordre hvor innlogget person står som fagansvarlig.")},{key:2,indexPosition:3,title:translationService.translate("web-enum-MobileMenuProfileItems-MyResourceGroupWorkorders","Ressursgruppens arbeidsordre"),available:moduleService.hasModule(moduleService.moduleFlags.Activity),visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-tasks","Oppgaver"),icon:"zmdi-accounts",popoverText:translationService.translate("web-mobilemenuprofile-MyResourceGroupWorkorders-popoverText","Arbeidsordre som deler samme ressursgruppe som innlogget person.")},{key:1,indexPosition:4,title:translationService.translate("web-enum-MobileMenuProfileItems-AllWorkorders","Alle arbeidsordre"),available:moduleService.hasModule(moduleService.moduleFlags.Activity),visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-tasks","Oppgaver"),icon:"zmdi-case",popoverText:translationService.translate("web-mobilemenuprofile-AllWorkorders-popoverText","Alle arbeidsordre som innlogget bruker har tilgang til. Listen vil være filtrert om bruker er knyttet til en gitt leverandør, kunde eller er låst til et utvalg.")},{key:3,indexPosition:5,title:translationService.translate("web-enum-MobileMenuProfileItems-MySparePartCounting","Mine varetellinger"),available:moduleService.hasModule(moduleService.moduleFlags.InventoryControl),visible:!!moduleService.hasModule(moduleService.moduleFlags.InventoryControl)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-tasks","Oppgaver"),icon:"zmdi-shopping-cart",popoverText:translationService.translate("web-mobilemenuprofile-MySparePartCounting-popoverText","Tellelister som innlogget bruker er del av, og som ikke er knyttet til en fullført varetelling.")},{key:4,indexPosition:6,title:translationService.translate("web-enum-MobileMenuProfileItems-MyCreatedRequests","Mine innmeldte saker"),available:moduleService.hasModule(moduleService.moduleFlags.Activity),visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-requests","Innmelding"),icon:"zmdi-account",popoverText:translationService.translate("web-mobilemenuprofile-MyCreatedRequests-popoverText","Saker som er opprettet av innlogget bruker eller hvor innlogget person er satt som kontaktperson.")},{key:9,indexPosition:7,title:translationService.translate("web-enum-MobileMenuProfileItems-MyDepartmentCreatedRequests","Min avdelings innmeldte saker"),available:moduleService.hasModule(moduleService.moduleFlags.Activity),visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-requests","Innmelding"),icon:"zmdi-accounts",popoverText:translationService.translate("web-mobilemenuprofile-MyDepartmentCreatedRequests-popoverText","Innmeldte saker hvor meldingene er tilknyttet den samme avdelingen som innlogget person er del av.")},{key:6,indexPosition:8,title:translationService.translate("web-enum-MobileMenuProfileItems-MyResponsibleRequests","Mine meldinger"),available:moduleService.hasModule(moduleService.moduleFlags.Activity),visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-process","Behandle"),icon:"zmdi-account",popoverText:translationService.translate("web-mobilemenuprofile-MyResponsibleRequests-popoverText","Meldinger hvor innlogget person står som ansvarlig.")},{key:11,indexPosition:9,title:translationService.translate("web-enum-MobileMenuProfileItems-BBYMyResponsibleRequests","Mine meldinger (Tilpasset)"),available:moduleService.hasModule(moduleService.moduleFlags.Activity)&&$localStorage.generalOptions.IsBBY,visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-process","Behandle"),icon:"zmdi-account",popoverText:translationService.translate("web-mobilemenuprofile-BBYMyResponsibleRequests-popoverText","Viser meldinger hvor innlogget person står som hovedansvarlig, og meldinger som mangler hovedansvarlig, men hvor innlogget person er angitt som sekundæransvarlig.")},{key:7,indexPosition:10,title:translationService.translate("web-enum-MobileMenuProfileItems-MyResourceGroupRequests","Ressursgruppens meldinger"),available:moduleService.hasModule(moduleService.moduleFlags.Activity),visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-process","Behandle"),icon:"zmdi-accounts",popoverText:translationService.translate("web-mobilemenuprofile-MyResourceGroupRequests-popoverText","Meldinger som deler samme ressursgruppe som innlogget person.")},{key:5,indexPosition:11,title:translationService.translate("web-enum-MobileMenuProfileItems-AllRequests","Alle meldinger"),available:moduleService.hasModule(moduleService.moduleFlags.Activity),visible:!!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!$scope.isUpdate,group:translationService.translate("mobile-activityPage-section-process","Behandle"),icon:"zmdi-email",popoverText:translationService.translate("web-mobilemenuprofile-AllRequests-popoverText","Alle meldinger som innlogget bruker har tilgang til. Listen vil være filtrert om bruker er knyttet til en gitt leverandør, kunde eller er låst til et utvalg.")}],$scope.activityPageItems=_.sortBy($scope.activityPageItems,function(item){return item.indexPosition}).filter(function(item){return item.available}),$scope.newMobileTabs=[{key:0,title:translationService.translate("web-enum-MobileMenuProfileTabs-Activity","Aktiviteter"),available:moduleService.hasModule(moduleService.moduleFlags.Activity)||moduleService.hasModule(moduleService.moduleFlags.SparePart),visible:!(!moduleService.hasModule(moduleService.moduleFlags.Activity)&&!moduleService.hasModule(moduleService.moduleFlags.SparePart))&&!$scope.isUpdate,icon:"zmdi-case"},{key:1,title:translationService.translate("web-enum-MobileMenuProfileTabs-Objects","Objekter"),available:moduleService.hasModule(moduleService.hasModule(moduleService.moduleFlags.SparePart)),visible:!!moduleService.hasModule(moduleService.hasModule(moduleService.moduleFlags.SparePart))&&!$scope.isUpdate,icon:"zmdi-layers"},{key:2,title:translationService.translate("web-enum-MobileMenuProfileTabs-QrScan","Scan"),available:moduleService.hasModule(moduleService.moduleFlags.Core),visible:!!moduleService.hasModule(moduleService.moduleFlags.Core)&&!$scope.isUpdate,icon:"zmdi-fullscreen"}],$scope.newMobileTabs=$scope.newMobileTabs.filter(function(tab){return tab.available}),$scope.getVisibleTabs=function(){return $scope.newMobileTabs.filter(function(t){return t.visible})},$scope.oldMobileAvailableMenus=[{key:"MyWorkOrders",title:translationService.translate("mobile-menu-myWorkOrders","Mine Arbeidsordre"),featured:!0,available:moduleService.hasModule(moduleService.moduleFlags.Activity),imgSrc:"images/icons/ionicons/briefcase.png"},{key:"WorkOrders",title:translationService.translate("mobile-menu-allWorkOrders","Alle Arbeidsordre"),featured:!1,available:moduleService.hasModule(moduleService.moduleFlags.Activity),imgSrc:"images/icons/ionicons/list-outline.png"},{key:"WorkOrderHistory",title:translationService.translate("mobile-menu-workOrderHistory","Arbeidsordre Historikk"),featured:!1,available:moduleService.hasModule(moduleService.moduleFlags.Activity),imgSrc:"images/icons/ionicons/filing.png"},{key:"CreateWorkOrder",title:translationService.translate("mobile-menu-newWorkOrder","Ny Arbeidsordre"),featured:!1,available:moduleService.hasModule(moduleService.moduleFlags.Activity),imgSrc:"images/icons/ionicons/plus-circled.png"},{key:"CreateRequest",title:translationService.translate("mobile-menu-newRequest","Ny Melding"),featured:!1,available:moduleService.hasModule(moduleService.moduleFlags.Activity),imgSrc:"images/icons/ionicons/chatbubble.png"},{key:"Barcode",title:translationService.translate("mobile-menu-barcodes","QR-koder"),featured:!1,available:moduleService.hasModule(moduleService.moduleFlags.Core),imgSrc:"images/icons/ionicons/qr-scanner.png"},{key:"MyRequests",title:translationService.translate("mobile-menu-myMessages","Mine Meldinger"),featured:!1,available:moduleService.hasModule(moduleService.moduleFlags.Activity),imgSrc:"images/icons/ionicons/chatbubbles.png"},{key:"Inventory",title:translationService.translate("mobile-menu-inventory","Varelager"),featured:!1,available:moduleService.hasModule(moduleService.moduleFlags.SparePart),imgSrc:"images/icons/ionicons/box.png"},{key:"SparePartCounting",title:translationService.translate("mobile-menu-sparePartCounting","Varetelling"),featured:!1,available:moduleService.hasModule(moduleService.moduleFlags.InventoryControl),imgSrc:"images/icons/ionicons/clipboard.png"}],$scope.selectedMenus=[],$scope.isUpdate?repository.getSingle(repository.apiData.mobileMenuProfile.url,$stateParams.guid).then(function(result){$scope.model=result.Data,$scope.model.ActivityMenuList&&$scope.model.ActivityMenuList.split(";").map(Number).forEach(function(key){var menuItem=$scope.activityPageItems.find(function(item){return item.key===key});menuItem&&(menuItem.visible=!0)}),$scope.model.TabList&&$scope.model.TabList.split(";").map(Number).forEach(function(key){var tabItem=$scope.newMobileTabs.find(function(tab){return tab.key===key});tabItem&&(tabItem.visible=!0)});for(var menuIndexes=$scope.model.MenuList.split(";").map(Number),i=0;i",value:$stateParams.guid}]},useObjects:!1}}}}).result.then(function(selectedGuids){var selectedEntities=[];selectedGuids.forEach(function(guid){selectedEntities.push(JSON.stringify({Guid:guid,GuidMobileMenuProfile:$scope.model.Guid}))}),repository.createMultiple(repository.apiData.massUpdate.url,selectedEntities,"Prefix="+repository.apiData.user.prefix).then(function(result){repository.growl("Brukerene har blitt lagt til","success"),$scope.userTable.reload()})},function(error){})},$scope.removeUser=function(user){if(!user&&0===$scope.selectedUsers.length)return void swal("Ingen valg",translationService.translate("web-mobilemenuprofile-delete-selectedUsers-empty","Ingen valg. Velg en eller flere rader fra listen for å koble fra brukere fra mobilmenyen."),"error");swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:user?translationService.translate("web-swal-mobilemenuprofile-user-delete-message","Brukeren vil bli fjernet fra mobilmenyen!"):translationService.translate("web-swal-mobilemenuprofile-selectedUsers-delete-message","Brukerene vil bli fjernet fra mobilmenyen!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:user?translationService.translate("web-swal-mobilemenuprofile-user-delete-button-confirm","Ja, fjern brukeren"):translationService.translate("web-swal-mobilemenuprofile-selectedUsers-delete-button-confirm","Ja, fjern brukerene"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null;var users=[];user?users.push(JSON.stringify({Guid:user.Guid,GuidMobileMenuProfile:null})):$scope.selectedUsers.forEach(function(usr){users.push(JSON.stringify({Guid:usr.Guid,GuidMobileMenuProfile:null}))}),repository.createMultiple(repository.apiData.massUpdate.url,users,"Prefix="+repository.apiData.user.prefix).then(function(result){user?swal("Suksess!",translationService.translate("web-swal-mobilemenuprofile-user-delete-success","Brukeren ble fjernet!"),"success"):swal("Suksess!",translationService.translate("web-swal-mobilemenuprofile-selectedUsers-delete-success","Brukerene ble fjernet!"),"success"),$scope.userTable.reload()})})},$scope.userMenuOptions=function(user){var options=[];return $scope.restrictEdit||options.push({html:' '+translationService.translate("web-mobilemenuprofile-user-remove","Koble fra bruker")+"",click:function($itemScope,$event,modelValue,text,$li){$scope.removeUser(user)}}),options},$scope.goToUser=function(user){$state.go("user.edit",{guid:user.Guid})}),$scope.$on($scope.events.newSelection,function(){updateAccess()}),$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)}}angular.module("Plania").controller("MobileMenuProfileController",["$scope","Repository","$stateParams","ngTableParams","$modal","TranslationService","ModuleService","ListService","$state","$localStorage",listController])}(),function(){function controller($scope,repository,$stateParams,ngTableParams,$modal,$filter,authService,translationService,$q){$scope.isUpdate="namedSelection.edit"===$scope.navigation.current.name,$scope.activateAutocomplete=!1,$scope.model={Guid:$stateParams.guid},$scope.namedSelectionValues=[];var updateUserAccess=function(){if($scope.isUpdate){var checkOtherDo=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!authService.hasEditAccess(repository.commonService.prefix.NamedSelection,checkOtherDo),$scope.restrictDelete=!authService.hasDeleteAccess(repository.commonService.prefix.NamedSelection,checkOtherDo)}else $scope.restrictEdit=!authService.hasCreateAccess(repository.commonService.prefix.NamedSelection)};updateUserAccess();var getSelectionValues=function(){var columns=["Value","IndexPosition"];repository.GetPaginated(repository.apiData.namedSelectionValue.url,0,20,{IndexPosition:"asc"},{PropertyFilter:[{Property:"GuidNamedSelection",Operator:"=",Value:$stateParams.guid}]},"",JSON.stringify(columns)).then(function(result){$scope.namedSelectionValues=result.List})};$scope.isUpdate?(repository.getSingle(repository.apiData.namedSelection.url,$stateParams.guid).then(function(response){$scope.model=response.Data,updateUserAccess(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}),getSelectionValues()):$scope.activateAutocomplete=!0;var updateNamedSelectionValue=function(value){var deferred=$q.defer();return repository.updateSingleDictionary(repository.apiData.namedSelectionValue.url,value).then(function(result){deferred.resolve()},function(error){deferred.reject({value:value,error:error})}),deferred.promise},createNamedSelectionValue=function(value){var deferred=$q.defer();return repository.createSingleDictionary(repository.apiData.namedSelectionValue.url,value).then(function(result){deferred.resolve()},function(error){deferred.reject({value:value,error:error})}),deferred.promise};$scope.update=function(destination){var success=function(result){repository.growl($scope.isUpdate?translationService.translate("update-namedSelection-success","Nedtrekkslisten har blitt oppdatert."):translationService.translate("create-namedSelection-success","Nedtrekkslisten har blitt opprettet."),"success");var guid=$scope.isUpdate?$scope.model.Guid:result.Guid;repository.commonService.setLastRegisterGuid(destination,guid);for(var promises=[],i=0;i<$scope.namedSelectionValues.length;i++)$scope.namedSelectionValues[i].IndexPosition=i,delete $scope.namedSelectionValues[i].editMode,$scope.namedSelectionValues[i].GuidNamedSelection=guid,$scope.namedSelectionValues[i].Guid?promises.push(updateNamedSelectionValue($scope.namedSelectionValues[i])):promises.push(createNamedSelectionValue($scope.namedSelectionValues[i]));$q.all(promises).then(function(){$scope.goBack(destination,{guid:guid,menuGuid:$scope.navigation.params.menuGuid})}).catch(function(error){})},error=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.isUpdate?repository.updateSingleDictionary(repository.apiData.namedSelection.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(repository.apiData.namedSelection.url,$scope.model).then(success).catch(error)},$scope.removeValue=function(item,index){item.Guid?repository.deleteSingle(repository.apiData.namedSelectionValue.url,item.Guid).then(function(result){$scope.namedSelectionValues.splice(index,1),item.Guid===$scope.model.GuidDefaultNamedSelectionValue&&($scope.model.GuidDefaultNamedSelectionValue=null)}):$scope.namedSelectionValues.splice(index,1)},$scope.cancel=function(){repository.commonService.setLastRegisterGuid("namedSelection.list",$scope.model.Guid),$scope.goBack("namedSelection.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-namedSelection-message","Nedtrekkslisten vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-namedSelection-button-confirm","Ja, slett nedtrekkslisten!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.namedSelection.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-namedSelection-success","Nedtrekkslisten ble fjernet!"),result,"success"),$scope.goBack("namedSelection.list",{menuGuid:$scope.navigation.params.menuGuid})})})},$scope.addNewValue=function(){$scope.namedSelectionValues.push({IndexPosition:$scope.namedSelectionValues.length,editMode:!0})},$scope.$on($scope.events.newSelection,function(){updateUserAccess()})}angular.module("Plania").controller("NamedSelectionController",["$scope","Repository","$stateParams","ngTableParams","$modal","$filter","authService","TranslationService","$q",controller])}(),function(){function controller($scope,$modal,ngTableParams,repository,$rootScope,translationService,$localStorage,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 getPropertyFilter=function(){var propertyFilter=[],entityFilter={Operand:"or",SubFilters:[{Property:"Guid"+$scope.parentEntity,Operator:"=",Value:$scope.guid}]};propertyFilter.push(entityFilter);var commonFilter=operationalMessageService.getCommonPropertyFilter($localStorage.selectedOperationalMessageFilterType);return commonFilter&&Array.isArray(commonFilter)&&commonFilter.forEach(function(f){propertyFilter.push(f)}),propertyFilter};$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","Person.FirstName","Person.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 propertyFilter=getPropertyFilter();if(0!==propertyFilter.length){var filter=angular.copy(params.filter());filter.PropertyFilter=propertyFilter,$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.state=operationalMessageService.getCurrentStateEnum(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")})}}});var filterTypes=operationalMessageService.getCommonFilterTypes();$scope.setFilter=function(filterType){$scope.selectedFilterName=_.find(filterTypes,{value:filterType}).name,$localStorage.selectedOperationalMessageFilterType=filterType,$scope.operationalMessageTable.reload(),$scope.showFilterDropdown=!1},$localStorage.selectedOperationalMessageFilterType?($scope.selectedFilterName=_.find(filterTypes,{value:$localStorage.selectedOperationalMessageFilterType}).name,$scope.setFilter($localStorage.selectedOperationalMessageFilterType)):($scope.selectedFilterName=_.find(filterTypes,{value:"active"}).name,$scope.setFilter(_.find(filterTypes,{value:"active"}).value)),$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(JSON.stringify({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,JSON.stringify({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","$localStorage","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","Person.FirstName","Person.LastName","User.RealName","User1.RealName"],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),updateDateTexts(),updateAccess(),setTimeout(function(){$scope.activateAutocomplete=!0},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),updateAccess(),$scope.activateAutocomplete=!0),$scope.save=function(action){var saveDto=angular.copy($scope.model);saveDto.DueDate&&(saveDto.DueDate=new Date(saveDto.DueDate).toISOString()),saveDto.StartDate&&(saveDto.StartDate=new Date(saveDto.StartDate).toISOString()),params.guidEquipment&&(saveDto.GuidEquipment=params.guidEquipment),delete saveDto.Estate,delete saveDto.Building,delete saveDto.Area,delete saveDto.Equipment,delete saveDto.Person,delete saveDto.WorkOrder,params.guid?repository.updateSingleDictionary(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.createSingleDictionary(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;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.getCommonPropertyFilter=function(filterType){var propertyFilter=[];switch(filterType){case"active":propertyFilter.push({Property:"StartDate",Operator:"<=",Value:moment().startOf("day").toISOString()}),propertyFilter.push({Operand:"or",SubFilters:[{Property:"DueDate",Operator:">=",Value:moment().toISOString()},{Property:"DueDate",Operator:"=",Value:null}]});break;case"planned":propertyFilter.push({Property:"StartDate",Operator:">",Value:moment().startOf("day").toISOString()});break;case"history":propertyFilter.push({Property:"DueDate",Operator:"<",Value:moment().toISOString()})}return propertyFilter},service.getEntityIcon=function(operationalMessage){return operationalMessage.Equipment?"zmdi-settings c-bluegray":operationalMessage.Building?"zmdi-balance c-brown":operationalMessage.Estate?"zmdi-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.getCurrentStateEnum=function(message){var state="inactive",startDateMoment=null,dueDateMoment=null;message.StartDate&&(startDateMoment=moment(message.StartDate)),message.DueDate&&(dueDateMoment=moment(message.DueDate));var isStartDateInThePast=!!startDateMoment&&moment().isSameOrAfter(startDateMoment),isStartDateInTheFuture=!!startDateMoment&&moment().isBefore(startDateMoment),isDueDateInTheFuture=!!dueDateMoment&&moment().isBefore(dueDateMoment),isDueDateInThePast=!!dueDateMoment&&moment().isAfter(dueDateMoment);return!isStartDateInThePast||!isDueDateInTheFuture&&dueDateMoment?isStartDateInTheFuture?state="planned":isDueDateInThePast&&(state="historic"):state="active",state},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.updateSingleDictionary(repository.apiData.paymentOrderForm.url,$scope.model).then(success,error):repository.createSingleDictionary(repository.apiData.paymentOrderForm.url,$scope.model).then(success,error)},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"report":return filter.PropertyFilter=[{Property:"ReportType",Operator:"=",Value:"1"},{Property:"ReportType",Operator:"=",Value:"2",Operand:"Or"}],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.updateSingleDictionary(repository.apiData.paymentTerm.url,$scope.model).then(success,error):repository.createSingleDictionary(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"}],$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(10*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={};"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,JSON.stringify(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 createPropertyFilter=function(){var filter=[{Property:"HasConditionControl",Operator:"=",Value:1}];switch($localStorage.generalOptions.InspectedEntityLocation){case constants.inspectedEntityLocation.estate:params.guidEstate&&filter.push({Property:"Building.GuidEstate",Operator:"=",Value:params.guidEstate});break;case constants.inspectedEntityLocation.building:params.guidBuilding&&filter.push({Property:"GuidBuilding",Operator:"=",Value:params.guidBuilding})}return filter};$scope.equipmentTable=new ngTableParams({page:1,count:10,sorting:{Id:"asc"},filter:{PropertyFilter:createPropertyFilter()}},{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.growl(error,"danger")})}}),$scope.getPropertyValue=function(row,column){return listService.GetPropertyValue(row,column)},$scope.selectedEquipments=[],$scope.save=function(){var xRef=[];$scope.selectedEquipments.forEach(function(eq){xRef.push(JSON.stringify({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.createSingleDictionary(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,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.updateSingleDictionary(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.createSingleDictionary(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){$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.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=!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","Person.FirstName","Person.LastName","ResourceResponsible.FirstName","ResourceResponsible.LastName","User.RealName","User1.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.Person&&($scope.modelDto.personResponsible=periodicTask.Person.FirstName+" "+periodicTask.Person.LastName),periodicTask.ResourceResponsible&&($scope.modelDto.resourceResponsible=periodicTask.ResourceResponsible.FirstName+" "+periodicTask.ResourceResponsible.LastName)};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.updateSingleDictionary(repository.apiData.periodicTask.url,payloadEntity).then(success).catch(error):repository.createSingleDictionary(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.PropertyFilter.push({Property:"IsTemplate",Operator:"=",Value:!1}),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}},$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.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.createSingleDictionary(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.updateSingleDictionary(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:1,Title:translationService.translate("web-building-description"),Property:"Equipment.Building.Description",PropertyType:"string"},{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"}],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(){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(item){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 permanent fjernet!"),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 fjernet!"),result,"success"),me.table.reload()})})},this.canDelete=function(equipment){return equipment&&$scope.hasDeleteAccess("PeriodicTaskXEquipment")},this.contextMenuOptions=function(item){var options=[];return me.canDelete(item)&&options.push({html:' '+translationService.translate("web-periodicTask-periodicTaskXEquipment-delete","Slett anlegg")+"",click:function($itemScope,$event,modelValue,text,$li){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&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:item.GuidPurchaseOrder}),"zmdi-shopping-cart",translationService.translate("web-workorder-viewPurchaseOrder","Se bestilling"))),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.createSingleDictionary(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.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:"lg",resolve:{params:function(){return{GuidPeriodicTask:$scope.model.Guid,fieldRules:$scope.fieldRules}}}}).result.then(function(){},function(){})}}angular.module("Plania").controller("PeriodicTaskController",["$scope","Repository","$stateParams","ngTableParams","$modal","$modalStack","authService","TranslationService","ListService","$localStorage","$q","RegisteredFieldService",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=7*$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=7*$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.growl(error,"danger"),$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){$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(),$scope.personBuildingTableColumns=[{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-buildingcategory-description"),Property:"Building.BuildingCategory.Description",PropertyType:"autocomplete",AutocompleteProperty:"GuidBuildingCategory",AutocompleteService:"buildingCategory"},{Position:4,Title:translationService.translate("web-building-address"),Property:"Building.Address",PropertyType:"string"},{Position:5,Title:translationService.translate("web-building-postalcode"),Property:"Building.PostalCode",PropertyType:"string"},{Position:6,Title:translationService.translate("web-building-postalarea"),Property:"Building.PostalArea",PropertyType:"string"},{Position:7,Title:translationService.translate("web-costcenter-id"),Property:"Building.CostCenter.Id",PropertyType:"autocomplete",AutocompleteProperty:"GuidCostCenter",AutocompleteService:"costCenter"}];var getCardTables=function(){$scope.buildingXPersonTable=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=[];$scope.personBuildingTableColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.buildingPerson.url,params.page()-1,params.count(),params.sorting(),params.filter(),"",JSON.stringify(columns)).then(function(result){$scope.buildingXPersonTable.settings().total=result.TotalCount,$scope.buildingXPersonTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})},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=repository.enableWebNavigation,updateAccess(),setProperties(),setTimeout(function(){$scope.activateAutocomplete=!0},250)},function(error){repository.growl(error,"danger")}),getCardTables()}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.addBuilding=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($scope.buildingXPersonTable.data,function(row){return{GuidBuilding:row.GuidBuilding,GuidPerson:row.GuidPerson,GuidPersonRole:row.GuidPersonRole}}),isModal:!0}}}}).result.then(function(){$scope.buildingXPersonTable.reload(),$scope.isBuildingCollapsed=!1},function(){$scope.isBuildingCollapsed=!1})},$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.updateSingleDictionary(repository.apiData.person.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(repository.apiData.person.url,$scope.model).then(success).catch(error)},$scope.removeBuilding=function(item){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-person-building-message","Bygningen vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-person-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.buildingPerson.url,item.Guid).then(function(result){swal(translationService.translate("web-swal-person-building-success","Bygningen ble fjernet!"),result,"success"),$scope.buildingXPersonTable.reload()})})},$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}]:$scope.model.GuidOrganization&&(filter.PropertyFilter=[{Property:"OrganizationUnit.GuidOrganization",Operator:"=",Value:$scope.model.GuidOrganization}]),filter}return filter},$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",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.updateSingleDictionary(repository.apiData.personRole.url,$scope.model).then(success,error):repository.createSingleDictionary(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.update=!0,$scope.isClientCollapsed=!0,$scope.model={},$scope.modules={},repository.getSingleWithNoParameter(repository.apiData.planiaSystem.url).then(function(response){$scope.reload=!0,$scope.license=response.LicenseNumber,$scope.dbv=response.DataBaseVersion,$scope.webapiv=response.WebAPIVersion,$scope.licensedClients=response.LicenseInformation.NumberOfDataOwners,$scope.definedUsers=response.LicenseInformation.NumberOfDefinedUsers,$scope.databaseType=response.DatabaseType,$scope.webserver=response.WebServerName,$scope.databaserver=response.DataBaseServer,$scope.database=response.DataBaseName,$scope.databaseSize=response.DatabaseSize,$scope.simpleUsers=response.LicenseInformation.NumberOfSimpleUsers,$scope.modules=response.LicenseInformation.Modules,$scope.products=response.LicenseInformation.Packages,$scope.existingClient=response.UsedClients,$scope.existingDefinedUsers=response.UsedDefinedUsers,$scope.existingSimpleUsers=response.UsedSimpleUsers,$scope.packageArray=[],$scope.moduleArray=[];var str=$scope.products,strModules=$scope.modules;$scope.packageArray=str.split(", "),$scope.moduleArray=strModules.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,ngTableParams,$modal,listService){$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")}];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,updateAccess()},function(error){repository.growl(error,"danger")}),$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.updateSingleDictionary(repository.apiData.priority.url,$scope.model).then(success,error):repository.createSingleDictionary(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","ngTableParams","$modal","ListService",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};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.createSingleDictionary(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}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.updateSingleDictionary(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.createSingleDictionary(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),destination.includes(".list")?$state.go(destination,{},{reload:!0}):($scope.goBack(destination,{guid:$scope.model.Guid,menuGuid:$scope.navigation.params.menuGuid}),$scope.canChangePhase=$scope.userInfo.guidPerson===$scope.model.GuidManagerPerson||$scope.userInfo.guidPerson===$scope.model.GuidOwnerPerson||$scope.userInfo.isSystemAdministrator||$scope.userInfo.isProjectAdministrator)},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.updateSingleDictionary(repository.apiData.project.endpoint.updateTemplate,$scope.model).then(success).catch(error):repository.updateSingleDictionary(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",columns:columns,model:$scope.model,attachments:[],getAllDocuments:!0,documentFilter:filter,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(repository.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")&&repository.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")&&repository.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.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&&repository.enableWebNavigation&&(projectDocument.GuidWorkOrder?options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:projectDocument.GuidWorkOrder}),"zmdi-case",translationService.translate("web-project-open-workorder","Åpne arbeidsordre"))):projectDocument.GuidPurchaseOrder?options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:projectDocument.GuidPurchaseOrder}),"zmdi-shopping-cart",translationService.translate("web-project-open-purchaseorder","Åpne bestilling"))):projectDocument.GuidDeviation?options.push(getMenuLink($rootScope.navigation.href("deviation.edit",{guid:projectDocument.GuidDeviation}),"zmdi-alert-octagon",translationService.translate("web-project-open-deviation","Åpne avvik"))):projectDocument.GuidCondition&&options.push(getMenuLink($rootScope.navigation.href("condition.edit",{guid:projectDocument.GuidCondition}),"zmdi-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("purchaseOrderItemListSetup",function(newValue,oldValue){oldValue!==newValue&&$scope.purchaseOrderItemTable&&($scope.purchaseOrderItemTable.$params.sorting=$scope.purchaseOrderItemListSetup.Sorting,$scope.purchaseOrderItemListSetup.GroupBy?$scope.purchaseOrderItemTable.settings().groupBy=function(obj){return!!$scope.purchaseOrderItemListSetup.GroupBy&&($scope.purchaseOrderItemListSetup.GroupBy.split(".").forEach(function(attr){obj=obj?obj[attr]:""}),obj)}:$scope.purchaseOrderItemTable.settings().groupBy=null,$scope.purchaseOrderItemTable.reload())}),listService.getWebListViews(null,repository.apiData.purchaseOrderItem.prefix,!1,null,{}).then(function(result){$scope.purchaseOrderItemListOptions=result.listOptions,$scope.purchaseOrderItemListSetup=result.selectedListSetup,$scope.purchaseOrderItemTable||($scope.purchaseOrderItemTable=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=[];$scope.purchaseOrderItemListSetup.Columns.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.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.purchaseOrderItemTable.reload()},function(){})},$scope.showPurchaseOrder=function(item){$scope.rootScope.navigation.go("purchaseOrder.edit",{guid:item.GuidPurchaseOrder},{reload:!0})},$scope.showWorkOrder=function(item){$scope.rootScope.navigation.go("workOrder.edit",{guid:item.GuidWorkOrder},{reload:!0})};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&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:purchaseOrderItem.GuidPurchaseOrder}),"zmdi-shopping-cart",translationService.translate("web-project-open-purchaseorder","Åpne bestilling"))),purchaseOrderItem.GuidWorkOrder&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:purchaseOrderItem.GuidWorkOrder}),"zmdi-case",translationService.translate("web-project-open-workorder","Åpne arbeidsordre"))),purchaseOrderItem.GuidPeriodicTask&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("periodicTask.edit",{guid:purchaseOrderItem.GuidPeriodicTask}),"zmdi-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.progress=100*(dateProgress.now-dateProgress.start)/(dateProgress.end-dateProgress.start)}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}},$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={PropertyFilter:[{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"},{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"},{Property:"Guid",Operator:"<>",value:$scope.model.Guid,Operand:"AND"}]};user.isSystemAdministrator||user.isProjectAdministrator||(filter.PropertyFilter=[{Property:"GuidOwnerPerson",Operator:"=",value:user.guidPerson,Operand:"AND"},{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"},{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"},{Property:"Guid",Operator:"<>",value:$scope.model.Guid,Operand:"AND"},{Property:"GuidManagerPerson",Operator:"=",value:user.guidPerson,Operand:"OR"},{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"},{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"},{Property:"Guid",Operator:"<>",value:$scope.model.Guid,Operand:"AND"}]),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,JSON.stringify($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={PropertyFilter:[{Property:"GuidProject",Value:$scope.model.Guid,Operator:"<>",Operand:"AND"},{Property:"Stage",Value:2,Operator:"<>",Operand:"AND"}],ActivityStatus:"Undefined"};user.isSystemAdministrator||user.isProjectAdministrator||(filter.PropertyFilter=[{Property:"GuidProject",Value:null,Operator:"=",Operand:"AND"},{Property:"GuidProject",Value:$scope.model.Guid,Operator:"<>",Operand:"AND"},{Property:"Stage",Value:2,Operator:"<>",Operand:"AND"},{Property:"Project.GuidOwnerPerson",Operator:"=",value:user.guidPerson,Operand:"OR"},{Property:"GuidProject",Value:$scope.model.Guid,Operator:"<>",Operand:"AND"},{Property:"Stage",Value:2,Operator:"<>",Operand:"AND"},{Property:"Project.GuidManagerPerson",Operator:"=",value:user.guidPerson,Operand:"OR"},{Property:"GuidProject",Value:$scope.model.Guid,Operator:"<>",Operand:"AND"},{Property:"Stage",Value:2,Operator:"<>",Operand:"AND"}]),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,JSON.stringify(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,JSON.stringify($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 payload={Guid:workOrder.Guid,RequestAction:"SetCompletionRate",RequestActionParameter1:JSON.stringify(workOrder.CompletionRate/100)},updateCompletionRate=function(){repository.updateSingleDictionary(repository.apiData.workOrder.url,payload).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){$scope.workOrderTable.data.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}),"zmdi-case",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}),"zmdi-case",translationService.translate("web-open-project-template-workorder","Åpne arbeidsordre mal"))):options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:resourceGroup.GuidWorkOrder}),"zmdi-case",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,$stateParams,translationService,listService){$scope.isUpdate="projectCategory.edit"===$scope.navigation.current.name,$scope.model={Guid:$stateParams.guid,DynamicProperty:[]},$scope.activateAutocomplete=!1,$scope.viewMode=!!$scope.isUpdate,$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.ProjectCategory,checkOtherDo),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.ProjectCategory,checkOtherDo)}else $scope.restrictEdit=!repository.authService.hasCreateAccess(repository.commonService.prefix.ProjectCategory)};if(updateAccess(),$scope.isUpdate){var columns=[];repository.getSingle(repository.apiData.projectCategory.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"),$scope.activateAutocomplete=!0})}var updateSuccess=function(result,destination){repository.growl($scope.isUpdate?translationService.translate("update-projectCategory-success","Prosjekt kategori har blitt oppdatert."):translationService.translate("create-projectCategory-success","Prosjekt 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})},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.updateSingleDictionary(repository.apiData.projectCategory.url,$scope.model).then(success,updateError):repository.createSingleDictionary(repository.apiData.projectCategory.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-projectCategory-message","Prosjekt kategori vil bli permanent fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-projectCategory-button-confirm","Ja, fjern prosjekt kategori"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.projectCategory.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-projectCategory-success","Prosjekt kategori ble fjernet!"),result,"success"),$scope.goBack("projectCategory.list",{menuGuid:$scope.navigation.params.menuGuid})})})}}angular.module("Plania").controller("ProjectCategoryController",["$scope","Repository","$stateParams","TranslationService","ListService",controller])}(),function(){function controller($scope,repository,modalParams,modalInstance,translationService,$modal,ngTableParams,listService){$scope.model={},$scope.isUpdate=!1,$scope.isTemplate=modalParams.IsTemplate,modalParams.Milestone?($scope.model={Guid:modalParams.Milestone.Guid,Id:modalParams.Milestone.Id,Description:modalParams.Milestone.Description,DueDate:modalParams.Milestone.DueDate,EndDate:modalParams.Milestone.EndDate,GuidProject:modalParams.Milestone.GuidProject},$scope.isUpdate=!0):$scope.model.GuidProject=modalParams.GuidProject,$scope.saveMilestone=function(){$scope.isUpdate?repository.updateSingleDictionary(repository.apiData.projectMilestone.url,$scope.model).then(function(result){modalInstance.close()}).catch(function(error){swal("Feil ved lagring",error,"error")}):repository.createSingleDictionary(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.updateSingleDictionary(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.createSingleDictionary(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;$scope.model.RequestAction="canIssue",repository.updateSingleDictionary(repository.apiData.purchaseOrder.url,$scope.model).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.model.RequestAction=null,$scope.continue=function(sendEmail){if(!$scope.ValidationMessage&&!$scope.isSaving){var issueOrder=function(){$scope.isSaving=!0,repository.getSingle(repository.apiData.reportDownload.url,$scope.model.Guid).then(function(response){$scope.isSaving=!1,$modalInstance.close(sendEmail?response:"changeStatus")},function(error){$scope.isSaving=!1,repository.growl(error,"danger")})};$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.unit,$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(docXEntity,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",columns:columns,model:$scope.model,attachments:$scope.documents,preselectedAttachments:docXEntity?[docXEntity.Guid]:[],getAllDocuments:!0,email:emailPrefill,returnEmailObject:!0,onNewDocument:onNewDocument}}}}).result.then(function(alarmLog){$scope.reloadAlarmLogTable=!0;var postModel=angular.copy($scope.model);postModel.RequestAction="Issue",postModel.AlarmLog=alarmLog;var success=function(result){updateSuccess(result,"purchaseOrder.edit")};repository.updateSingleDictionary(repository.apiData.purchaseOrder.url,postModel).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.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({Guid:item,RequestAction:"ReceiveItem"})}),$scope.reloadMainEntity()});var updateItem=function(payload){repository.updateSingleDictionary(repository.apiData.purchaseOrderItem.url,payload).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(){var payload={Guid:item,RequestAction:"ReceiveItem"};repository.updateSingleDictionary(repository.apiData.purchaseOrderItem.url,payload).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.updateSingleDictionary(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),$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:"GUID_PURCHASE_ORDER",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","User.RealName","User1.RealName","User2.RealName","User3.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.User&&($scope.modelDto.userPrintedBy=purchaseOrder.User.RealName),purchaseOrder.User1&&($scope.modelDto.userReceivedBy=purchaseOrder.User1.RealName),purchaseOrder.User3&&($scope.modelDto.userCreatedBy=purchaseOrder.User3.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.modelGuidPurchaseOrderForm=$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.updateSingleDictionary(repository.apiData.purchaseOrder.url,$scope.model).then(success,updateError):repository.createSingleDictionary(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.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 postModel=angular.copy($scope.model);postModel.RequestAction="Issue";var success=function(result){updateSuccess(result,"purchaseOrder.edit")};repository.updateSingleDictionary(repository.apiData.purchaseOrder.url,postModel).then(success,updateError)}else startEmailDialogWithAttachedDocument(response)},function(error){error&&repository.growl(error,"danger")})})};var mailAddress=function(emailAddress){return{Name:emailAddress,Email:emailAddress,DisplayProperty:emailAddress+(new Date).valueOf(),isLocked:!1}},startEmailDialogWithAttachedDocument=function(docXEntity){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(docXEntity,result.List)},function(error){sendEmail(docXEntity,[]),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",columns:columns,model:$scope.model,attachments:$scope.documents,getAllDocuments:$scope.counts.documentTotalCount>10,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},$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&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("workOrder.edit",{guid:item.GuidWorkOrder}),"zmdi-case",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}}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.modelDto={},$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.unit,$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.isAccountingMandatory=function(accountingColumn){if(!$scope.modelDto.dataOwner)return!1;if("GuidDepartment"===accountingColumn)return $scope.modelDto.dataOwner.DepartmentCost;var lastDimensionCost=$scope.modelDto.dataOwner.LastDimensionCost;return!(!angular.isDefined(lastDimensionCost)||!accountingColumn.startsWith("GuidAccounting"))&&lastDimensionCost>=parseInt(accountingColumn.slice(-1))},$scope.onGetValidityRules=function(originalValidityRules){if(!$scope.isAccountingMandatory(originalValidityRules.DomainFieldName))return originalValidityRules;var validityRules=_.clone(originalValidityRules);return validityRules.Mandatory=!0,validityRules},$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:3,Title:translationService.translate("web-sparePart-inventory","Beholdning"),Property:"Inventory"}]),$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"})}$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")})}}});var setAccountingCaption=function(entity){entity.Account&&$scope.model.GuidAccount===entity.GuidAccount&&($scope.modelDto.accountCaption=entity.Account.Caption),entity.CostCenter&&$scope.model.GuidCostCenter===entity.GuidCostCenter&&!$scope.lockCostCenter&&($scope.modelDto.costCenterCaption=entity.CostCenter.Caption),entity.Department&&$scope.model.GuidDepartment===entity.GuidDepartment&&($scope.modelDto.departmentCaption=entity.Department.Caption),entity.Accounting0&&$scope.model.GuidAccounting0===entity.GuidAccounting0&&($scope.modelDto.accounting0Caption=entity.Accounting0.Caption),entity.Accounting1&&$scope.model.GuidAccounting1===entity.GuidAccounting1&&($scope.modelDto.accounting1Caption=entity.Accounting1.Caption),entity.Accounting2&&$scope.model.GuidAccounting2===entity.GuidAccounting2&&($scope.modelDto.accounting2Caption=entity.Accounting2.Caption),entity.Accounting3&&$scope.model.GuidAccounting3===entity.GuidAccounting3&&($scope.modelDto.accounting3Caption=entity.Accounting3.Caption),entity.Accounting4&&$scope.model.GuidAccounting4===entity.GuidAccounting4&&($scope.modelDto.accounting4Caption=entity.Accounting4.Caption)};$scope.selectEntity=function(entity){if(!$scope.isLoadingEntities){if(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,"Article"===$scope.info.selectedLinkedEntity&&($scope.model.GuidArticle=entity.Guid,$scope.model.Id=entity.Id,$scope.model.Description=entity.Description,$scope.model.UnitPrice=entity.UnitPrice,$scope.model.Unit=entity.Unit),"Component"===$scope.info.selectedLinkedEntity){$scope.model.GuidComponent=entity.Guid,$scope.model.Id=entity.Id,$scope.model.Description=entity.Description;var unit=_.find($scope.units,{translatedValue:entity.Unit});$scope.model.Unit=unit?unit.value:null,entity.ComponentXSupplier&&1===entity.ComponentXSupplier.length&&($scope.model.UnitPrice=entity.ComponentXSupplier[0].Price)}if("SparePart"===$scope.info.selectedLinkedEntity){$scope.model.GuidSparePart=entity.Guid,$scope.model.Id=entity.Component.Id,$scope.model.Description=entity.Component.Description;var sparepartUnit=_.find($scope.units,{translatedValue:entity.ComponentXSupplier.Unit});$scope.model.Unit=sparepartUnit?sparepartUnit.value:null,entity.ComponentXSupplier&&($scope.model.UnitPrice=entity.ComponentXSupplier.Price)}$scope.modelDto.dataOwner=entity.DataOwner,setAccountingCaption(entity),$scope.setCurrentStep(1)}},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName.toLowerCase()){case"component":case"sparepart":return params.purchaseOrderItem.GuidSupplier&&(filter.PropertyFilter=[{Property:"ComponentXSupplier.GuidSupplier",Value:params.purchaseOrderItem.GuidSupplier,Operator:"="}]),filter;case"accounting0":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:0,Operator:"="}],filter;case"accounting1":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:1,Operator:"="}],filter;case"accounting2":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:2,Operator:"="}],filter;case"accounting3":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:3,Operator:"="}],filter;case"accounting4":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:4,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.PropertyFilter=[{Property:"DisabledFromDate",Operator:">",Value:(new Date).toISOString()},{Property:"DisabledFromDate",Operator:"=",Value:null,Operand:"OR"}],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,$scope.modelDto.dataOwner=response.Data.DataOwner;var unit=_.find($scope.units,{translatedValue:$scope.model.Unit});unit&&($scope.model.Unit=unit.value),setAccountingCaption($scope.model),$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","User","User1","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.updateSingleDictionary(repository.apiData.purchaseOrderItem.url,$scope.getPayloadEntity()).then(success,error):repository.createSingleDictionary(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;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.updateSingleDictionary(repository.apiData.purchaseOrderForm.url,$scope.model).then(success,error):repository.createSingleDictionary(repository.apiData.purchaseOrderForm.url,$scope.model).then(success,error)},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"report":return filter.PropertyFilter=[{Property:"ReportType",Operator:"=",Value:"1"},{Property:"ReportType",Operator:"=",Value:"2",Operand:"Or"}],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))})),$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.updateSingleDictionary(repository.apiData.referenceType.url,$scope.model).then(success,error),null!==$scope.selectedReferenceData&&!$scope.selectedReferenceData.isNew&&$scope.hasEditAccess("ReferenceData")&&$scope.updateReferenceData($scope.selectedReferenceData)):repository.createSingleDictionary(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,null,!0).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.updateSingleDictionary(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];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,null,!0).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:"sm",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.updateSingleDictionary(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.printReport=!0,$scope.reportName=$stateParams.reportName,$scope.reportParams=JSON.parse(reportParams),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.updateSingleDictionary(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){$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","Person1.FirstName","Person1.LastName","Priority.HasDeadline"],workOrderColumns=["Building.Id","Building.Description","Person.FirstName","Person.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.Person1){var responsiblePersonFirstName=$scope.model.Person1.FirstName?$scope.model.Person1.FirstName+" ":"";$scope.responsiblePerson=responsiblePersonFirstName+($scope.model.Person1.LastName||"")}},getWorkOrder=function(){$scope.enableWebNavigation=repository.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.Person&&($scope.model.WorkOrderResponsible=$scope.model.WorkOrder.Person.FirstName+" "+$scope.model.WorkOrder.Person.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"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.updateSingleDictionary(repository.apiData.request.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(repository.apiData.request.url,$scope.model).then(success).catch(error)},$scope.canChangeDataOwner=$localStorage.generalOptions.EnableGlobalCounter&&$localStorage.userData.canChangeRequestStatus&&$scope.hasEditAccess("Request"),$scope.changeDataOwnerAction=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){var payload={Guid:$scope.model.Guid,RequestAction:"ChangeDataOwner",RequestActionParameter1:JSON.stringify(dataOwner.Guid)};repository.updateSingleDictionary(repository.apiData.request.url,payload).then(function(result){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(msg){})},$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(){$scope.changeDataOwnerAction()},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 attachments=$scope.documents.concat($scope.model.Images),onNewDocument=function(){$scope.forceReloadDocumentTable=!1,$timeout(function(){$scope.forceReloadDocumentTable=!0},250)},reloadImages=function(){return repository.getMainModel(repository.apiData.request.url,$stateParams.guid).then(function(response){return $scope.model.Images=response.Data.Images,$scope.model.Images})};$modal.open({templateUrl:"app/common/views/emailModal.html",controller:"EmailModalController",size:"lg",resolve:{params:function(){return{entity:"Request",columns:requestColumns,model:$scope.model,attachments:attachments,getAllDocuments:$scope.counts.documentTotalCount>10,prefillSubjectWithCaption:!0,onNewDocument:onNewDocument,reloadImages:reloadImages}}}}).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",controller])}(),function(){function controller($scope,repository,params,modalInstance,translationService){var columns=["Description","CreationDate","Status"],filter={};params.guidArea&&(filter.PropertyFilter=[{Operand:"AND",Property:"Status",Operator:"=",Value:"0"},{Operand:"OR",Property:"Status",Operator:"=",Value:"1"},{Operand:"AND",Property:"WorkOrder.EndDate",Operator:"=",Value:""},{Operand:"AND",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.updateSingleDictionary(repository.apiData.resourceGroup.url,$scope.model).then(success,error):repository.createSingleDictionary(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:"exposure",colour:"bluegray",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:"case-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-outline",colour:"lightblue",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}}},{icon:"refresh-sync",colour:"green",title:translationService.translate("web-scheduledJob-type-azureSync","Azure Synchronization"),description:translationService.translate("web-scheduledJob-type-azureSync-description","Synkroniser med Azure AD"),model:{Description:"Synkronisering av brukere i Azure Active Directory",Type:"AzureADSync",Params:{LdapGuid:"Id",Username:"OnPremisesSamAccountName",RealName:"DisplayName",UserEmail:"Mail",PhoneNumber:"BusinessPhones",LdapDn:"OnPremisesDistinguishedName",FirstName:"GivenName",LastName:"Surname",PersonEmail:"Mail",TelephoneWork:"BusinessPhones",Cellphone:"MobilePhone",UniqueAzureIdentifier:"OnPremisesSamAccountName",UniquePlaniaIdentifier:"Username",RecurrenceTime: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.activateAutocomplete=!1,$scope.viewModel={},$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var updateAccess=function(){if($scope.isUpdate){var checkOtherDo=!1;$scope.restrictEdit=!authService.hasEditAccess(repository.commonService.prefix.ScheduledJob,checkOtherDo),$scope.restrictDelete=!authService.hasDeleteAccess(repository.commonService.prefix.ScheduledJob,checkOtherDo)}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.reload=!0,setTimeout(function(){$scope.activateAutocomplete=!0},250)},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(),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.updateSingleDictionary(repository.apiData.scheduledJob.url,modelToSave).then(success).catch(error):repository.createSingleDictionary(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:2,Title:translationService.translate("web-scheduledJobExecution-updatedDate","Oppdatert"),Property:"UpdatedDate",PropertyType:"date"},{Position:3,Title:translationService.translate("web-scheduledJobExecution-status","Status"),Property:"Status",PropertyType:"string"},{Position:4,Title:translationService.translate("web-scheduledJobExecution-logOutput","Logg"),Property:"LogOutput",PropertyType:"string"}],$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){$scope.sparePart={},$scope.component={},$scope.componentSupplier={},$scope.generalOptions=$localStorage.generalOptions;var showError=function(error){"string"==typeof error?repository.growl(error,"danger"):repository.growl(error.Data.Message,"danger")};$scope.save=function(){$scope.componentSupplier.Price&&($scope.componentSupplier.Price=$scope.componentSupplier.Price.replace(",",".")),repository.createSingleDictionary(repository.apiData.component.url,$scope.component).then(function(result){$scope.component.Guid=result.Guid,$scope.sparePart.GuidComponent=result.Guid,$scope.componentSupplier.GuidComponent=result.Guid,repository.createSingleDictionary(repository.apiData.componentSupplier.url,$scope.componentSupplier).then(function(result){$scope.sparePart.GuidComponentXSupplier=result.Guid,repository.createSingleDictionary(repository.apiData.sparePart.url,$scope.sparePart).then(function(result){repository.growl("Reservedel har blitt opprettet","success"),repository.commonService.setLastRegisterGuid("sparePart.edit",result.Guid),$modalInstance.dismiss("saved"),$scope.goBack("sparePart.edit",{guid:result.Guid,menuGuid:$scope.navigation.params.menuGuid})},function(error){showError(error)})},function(error){showError(error)})},function(error){showError(error)})},$scope.cancel=function(){$modalInstance.dismiss("canceled")}}angular.module("Plania").controller("CreateSparePartModalController",["$scope","Repository","$modalInstance","$localStorage",controller])}(),function(){function controller($scope,repository,$stateParams,translationService,ngTableParams,$modal,listService){$scope.isUpdate="sparePart.edit"===$scope.navigation.current.name,$scope.viewMode=!!$scope.isUpdate,$scope.reloadQrCodes=!1,$scope.modelDto={},$scope.prefix=repository.commonService.prefix.SparePart,$scope.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0};var columns=["ComponentXSupplier.PartNumber","ComponentXSupplier.GuidSupplier","ComponentXSupplier.Supplier.Id","ComponentXSupplier.Supplier.Description","ComponentXSupplier.Supplier.Telephone","ComponentXSupplier.Supplier.Email","Component.Id","Component.Guid","Component.Description","Component.ExplanatoryText","Component.ComponentCategory.Description","Component.Unit","Component.GuidImage","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"],updateAccess=function(){var checkOtherDO=$scope.model.GuidDataOwner!==repository.commonService.getFilterData().selectedDataOwner.Guid;$scope.restrictEdit=!repository.authService.hasEditAccess(repository.commonService.prefix.SparePart,checkOtherDO),$scope.restrictDelete=!repository.authService.hasDeleteAccess(repository.commonService.prefix.SparePart,checkOtherDO)},getAccountingLabels=function(guidDataOwner){repository.getSingle(repository.apiData.dataOwner.url,guidDataOwner).then(function(response){$scope.modelDto.dataOwner=response.Data},function(error){repository.growl(error,"danger")})};$scope.isAccountingMandatory=function(accountingColumn){if(!$scope.modelDto.dataOwner)return!1;if("GuidDepartment"===accountingColumn)return $scope.modelDto.dataOwner.DepartmentCost;var lastDimensionCost=$scope.modelDto.dataOwner.LastDimensionCost;return!(!angular.isDefined(lastDimensionCost)||!accountingColumn.startsWith("GuidAccounting"))&&lastDimensionCost>=parseInt(accountingColumn.slice(-1))},$scope.onGetValidityRules=function(originalValidityRules){if(!$scope.isAccountingMandatory(originalValidityRules.DomainFieldName))return originalValidityRules;var validityRules=_.clone(originalValidityRules);return validityRules.Mandatory=!0,validityRules},$scope.autoCompleteFilter=function(filterName){var filter={};switch(filterName){case"accounting0":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:0,Operator:"="}],filter;case"accounting1":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:1,Operator:"="}],filter;case"accounting2":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:2,Operator:"="}],filter;case"accounting3":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:3,Operator:"="}],filter;case"accounting4":return filter.PropertyFilter=[{Property:"DimensionNumber",Value:4,Operator:"="}],filter}},$scope.purchaseOrderItemColumns=[{Position:1,Title:translationService.translate("web-purchaseOrder-Id"),Property:"PurchaseOrder.Id",PropertyType:"string"},{Position:2,Title:translationService.translate("web-supplier-Id","Leverandør navn"),Property:"Supplier.Id",PropertyType:"string"},{Position:3,Title:translationService.translate("web-purchaseOrderItem-OrderedQuantity","Bestilt antall"),Property:"OrderedQuantity",PropertyType:"number"},{Position:4,Title:translationService.translate("web-purchaseOrderItem-UnitPrice","Enhetspris"),Property:"UnitPrice",PropertyType:"number"},{Position:5,Title:translationService.translate("web-purchaseOrderItem-Status","Status"),Property:"Status",PropertyType:"string"}];var getCardTables=function(){$scope.purchaseOrderItemTable=new ngTableParams({page:1,count:10,sorting:{CreationDate:"desc"},filter:{PropertyFilter:[{Property:"GuidSparePart",Operator:"=",Value:$stateParams.guid}]}},{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)})}})},getSparePart=function(){repository.getMainModel(repository.apiData.sparePart.url,$stateParams.guid,JSON.stringify(columns)).then(function(response){$scope.model=response.Data,$scope.reload=!0,$scope.reloadQrCodes=!0,$scope.model.Account&&($scope.modelDto.accountCaption=$scope.getEntityCaption($scope.model.Account)),$scope.model.CostCenter&&($scope.modelDto.costCenterCaption=$scope.getEntityCaption($scope.model.CostCenter)),$scope.model.Department&&($scope.modelDto.departmentCaption=$scope.getEntityCaption($scope.model.Department)),$scope.model.Accounting0&&($scope.modelDto.accounting0Caption=$scope.getEntityCaption($scope.model.Accounting0)),$scope.model.Accounting1&&($scope.modelDto.accounting1Caption=$scope.getEntityCaption($scope.model.Accounting1)),$scope.model.Accounting2&&($scope.modelDto.accounting2Caption=$scope.getEntityCaption($scope.model.Accounting2)),$scope.model.Accounting3&&($scope.modelDto.accounting3Caption=$scope.getEntityCaption($scope.model.Accounting3)),$scope.model.Accounting4&&($scope.modelDto.accounting4Caption=$scope.getEntityCaption($scope.model.Accounting4)),updateAccess(),getAccountingLabels($scope.model.GuidDataOwner),getCardTables()},function(error){repository.growl(error,"danger")})};$scope.isUpdate&&(getSparePart(),getCardTables()),$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-sparePart-success","Reservedeler har blitt oppdatert."):translationService.translate("create-sparePart-success","Reservedelen 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.updateSingleDictionary(repository.apiData.sparePart.url,$scope.model).then(success,error)):repository.createSingleDictionary(repository.apiData.sparePart.url,$scope.model).then(success,error)},$scope.withdraw=function(){$modal.open({templateUrl:"app/sparePart/views/sparePartObjectWithdrawalModal.html",controller:"SparePartObjectWithdrawalModalController",resolve:{params:function(){return{GuidSparePart:$scope.model.Guid}}}}).result.then(function(item){repository.createSingleDictionary(repository.apiData.sparePartWithdrawal.url,item).then(function(result){repository.growl(translationService.translate("web-spare-part-withdrawn","Reservedel er tatt ut"),"success"),getSparePart()},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-sparePart-message","Reservedelen vil bli permanent fjernet!"),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.sparePart.url,$scope.model.Guid).then(function(result){swal(translationService.translate("web-swal-sparePart-success","Reservedelen ble fjernet!"),result,"success"),$scope.goBack("sparePart.list",{menuGuid:$scope.navigation.params.menuGuid})},function(error){swal({title:"Kunne ikke slette reservedelen!",text:error.Message+"

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.updateSingleDictionary(repository.apiData.sparePartCountingList.url,$scope.model).then(success,error):repository.createSingleDictionary(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.updateSingleDictionary(repository.apiData.sparePartCounting.url,$scope.model).then(success,error):repository.createSingleDictionary(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.updateSingleDictionary(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.updateSingleDictionary(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.createSingleDictionary(repository.apiData.sparePartCounting.url,{CopyCounting:!0,CopyFromGuid:$stateParams.guid}).then(function(result){console.log(result),$scope.goBack("sparePartCounting.edit",{guid:result.Guid})},function(error){swal("Error",result,"danger")})},$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",resolve:{modalParams:function(){return{title:"Legg til varetelling poster",columns:[{Title:translationService.translate("web-sparePart-PartNumber","Delenummer"),Property:"ComponentXSupplier.PartNumber"},{Title:translationService.translate("web-sparePart-ComponentName","Komponentnavn"),Property:"Component.Id"},{Title:translationService.translate("web-sparePart-storage","Hylleplass"),Property:"Location"},{Title:translationService.translate("web-sparePart-Count","Antall"),Property:"Inventory"},{Title:translationService.translate("web-sparePart-Supplier","Leverandør"),Property:"ComponentXSupplier.Supplier.Id"}],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(JSON.stringify({GuidSparePart:guid,GuidSparePartCountingList:$scope.selectedCountingList.Guid}))}),repository.createMultiple(repository.apiData.sparePartCountingItem.url,sparePartCountingItems,"Prefix="+repository.apiData.sparePartCountingItem.prefix).then(function(result){repository.growl("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(JSON.stringify({GuidUser:guid,GuidSparePartCountingList:$scope.selectedCountingList.Guid}))}),repository.createMultiple(repository.apiData.userXSparePartCountingList.url,userXSparePartCountingList,"Prefix="+repository.apiData.userXSparePartCountingList.prefix).then(function(result){repository.growl("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","User1.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.updateSingleDictionary(repository.apiData.sparePartWithdrawal.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(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.updateSingleDictionary(repository.apiData.standardText.url,$scope.model).then(success,error):repository.createSingleDictionary(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){$scope.update="supplier.edit"===$scope.navigation.current.name,$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.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)};if(updateAccess(),$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:{last_name:"asc",first_name:"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.updateSingleDictionary(repository.apiData.supplier.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(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",controller])}(),function(){function controller($scope,repository,params,$modalInstance){function decodeHtml(html){html||(html="");var tmpElement=document.createElement("textarea");return tmpElement.innerHTML=html,tmpElement.value}function encodeHtml(html){html||(html="");var tmpElement=document.createElement("div");return $(tmpElement).text(html).html()}$scope.model=angular.copy(params.languageXWebText),$scope.systemName=params.systemName,$scope.model.TranslatedHelpText?$scope.HelpTextHtml=decodeHtml($scope.model.TranslatedHelpText):$scope.HelpTextHtml=decodeHtml($scope.model.DefaultTranslatedHelpText),$scope.save=function(){$scope.model.TranslatedHelpText=encodeHtml($scope.HelpTextHtml),repository.updateSingleDictionary(repository.apiData.translate.url,$scope.model).then(function(result){repository.growl("Hjelpetekst oppdatert","success"),$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","params","$modalInstance",controller])}(),function(){function controller($scope,params,$modalInstance,translationService,$sce){function decodeHtml(html){var tmpElement=document.createElement("textarea");return tmpElement.innerHTML=html,tmpElement.value}$scope.model={translatedLabel:params.translatedLabel},translationService.getHelpText(params.systemName).then(function(result){var html=decodeHtml(result);$scope.model.helpText=$sce.trustAsHtml(html)}),$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].LanguageXWebText,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.LanguageXWebText)},repository.showError):($scope.model=angular.copy(params.webText),$scope.original=angular.copy($scope.model.LanguageXWebText));var updateTranslation=function(translation){var deferred=$q.defer();return repository.updateSingleDictionary(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.LanguageXWebText,{Guid:result.Guid});-1!==idx&&(setHelpTextFromResult($scope.model.LanguageXWebText[idx],result),setHelpTextFromResult($scope.original[idx],result))})},$scope.save=function(){for(var promises=[],i=0;i<$scope.model.LanguageXWebText.length;i++)$scope.model.LanguageXWebText[i].TranslatedValue!==$scope.original[i].TranslatedValue&&promises.push(updateTranslation($scope.model.LanguageXWebText[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){$scope.model={},$scope.model.GuidUser=params.guidUser,$scope.model.IsDefaultDataOwner=!!params.isFirst,$scope.save=function(){$modalInstance.close()},$scope.saveAction=function(){delete angular.copy($scope.model).User,repository.createSingleDictionary(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}}}}angular.module("Plania").controller("CreateUserDataOwnerController",["$scope","Repository","params","$modalInstance",controller])}(),function(){function controller($scope,$modalInstance,params,repository,ngTableParams,translationService){$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:"Anleggs gruppe",Property:"EquipmentGroup.Caption",PropertyType:"string"},{Position:4,Title:translationService.translate("web-equipment-id"),Property:"Id",PropertyType:"string"},{Position:5,Title:translationService.translate("web-equipment-description"),Property:"Description",PropertyType:"string"}],$scope.equipmentTable=new ngTableParams({page:1,count:10,sorting:{id:"asc"},filter:{propertyFilter:[{Property:"IS_EQUIPMENT_GROUP",Operator:"=",Value:"1"}]}},{total:0,counts:[10,25,50],paginationMaxBlocks:6,getData:function($defer,params){$scope.isLoading=!0;var columns=[];$scope.equipmentColumns.forEach(function(col){-1===col.Property.indexOf("EquipmentGroup")&&columns.push(col.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),$scope.isLoading=!1,$defer.resolve(result.List),console.log(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.selectedEquipments=[],$scope.saveEquipment=function(){var userXEquipments=[];$scope.selectedEquipments.forEach(function(eq){userXEquipments.push({GuidUser:params.guidUser,GuidEquipment:eq})}),repository.createMultiple(repository.apiData.userEquipment.url,userXEquipments).then(function(result){repository.growl("Anlegget har blitt lagt til brukeren","success"),$modalInstance.close("OK")})},$scope.addEquipment=function(guid){if(_.contains($scope.selectedEquipments,guid))for(var i=0;i<$scope.selectedEquipments.length;i++){var p=$scope.selectedEquipments[i];if(p===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("CreateUserEquipmentController",["$scope","$modalInstance","params","Repository","ngTableParams","TranslationService",controller])}(),function(){function controller($scope,repository,params,$modalInstance){$scope.isDocumentsCollapsed=!0,$scope.activateAutocomplete=!1,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.updateSingleDictionary(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")}}angular.module("Plania").controller("EditUserDataOwnerController",["$scope","Repository","params","$modalInstance",controller])}(),function(){function controller($scope,translationService,repository,$modal,$stateParams,ngTableParams,$localStorage,$rootScope){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.toggleViewMode=function(){$scope.viewMode=!$scope.viewMode,$scope.reload=!0},$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};$scope.userProfileColumns=[], $scope.userProfileColumns.addColumn=function(translationId,defaultText,property,propertyType){return this.push({Position:this.length,Title:translationService.translate(translationId,defaultText),Property:property,PropertyType:propertyType}),this},$scope.userProfileColumns.addColumn("user-clientTable-dataOwnerName","Klient","LinkedDataOwner.Description","string").addColumn("user-clientTable-userProfileName","Profil","EntityPermissionProfile.Id","string").addColumn("user-clientTable-userProfileDescription","Profilbeskrivelse","EntityPermissionProfile.Description","string").addColumn("user-clientTable-isDefaultDataOwner","Standard Klient","IsDefaultDataOwner","string");var getCardTables=function(){$scope.dataOwnerTable=new ngTableParams({page:1,count:-1,filter:{PropertyFilter:[{Property:"GuidUser",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:!1,getData:function($defer,params){var columns=[];$scope.userProfileColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.userProfile.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,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}}),$scope.userEquipmentTable=new ngTableParams({page:1,count:10,filter:{GuidUser:$scope.model.Guid}},{total:0,filterDelay:10,counts:[10,20,50],paginationMaxBlocks:6,getData:function($defer,params){repository.GetPaginated(repository.apiData.userEquipment.url,params.page()-1,params.count(),params.sorting(),params.filter()).then(function(result){$scope.userEquipmentTable.settings().total=result.TotalCount,$scope.userEquipmentTable.settings().filterDelay=500,$defer.resolve(result.List)},function(error){repository.growl(error,"danger")})}})};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")}),getCardTables()};$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.PropertyFilter=[{Property:"IsUserGroup",Operator:"=",Value:1}],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.removeDataOwner=function(dataOwner){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,dataOwner.Guid).then(function(result){window.onkeydown=null,window.onfocus=null,repository.growl(translationService.translate("user-removeDataOwner-Success","Klient ble fjernet fra Bruker."),"success"),$scope.dataOwnerTable.reload(),swal.close()})})},$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.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.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.updateSingleDictionary(repository.apiData.user.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(repository.apiData.user.url,$scope.model).then(success).catch(error)},$scope.addDataOwner=function(){$modal.open({templateUrl:"app/user/views/editUserDataOwner.html",controller:"CreateUserDataOwnerController",resolve:{params:function(){return{guidUser:$scope.model.Guid,isFirst:$scope.dataOwnerTable.data.length<1}}}}).result.then(function(userProfile){userProfile&&userProfile.IsDefaultDataOwner&&($scope.model.GuidDefaultDataOwner=userProfile.GuidLinkedDataOwner),$scope.dataOwnerTable.reload()})},$scope.updateDataOwner=function(dataOwner){$scope.restrictEdit||$scope.model.GuidUserGroup||$modal.open({templateUrl:"app/user/views/editUserDataOwner.html",controller:"EditUserDataOwnerController",resolve:{params:function(){return{guidUserProfile:dataOwner.Guid}}}}).result.then(function(userProfile){userProfile&&userProfile.IsDefaultDataOwner&&($scope.model.GuidDefaultDataOwner=userProfile.GuidLinkedDataOwner),$scope.dataOwnerTable.reload().then()})},$scope.addEquipment=function(){$modal.open({templateUrl:"app/user/views/createUserEquipment.html",controller:"CreateUserEquipmentController",size:"lg",resolve:{params:function(){return{guidUser:$scope.model.Guid}}}}).result.then(function(){$scope.userEquipmentTable.reload()})},$scope.removeEquipment=function(equipment){swal({title:translationService.translate("web-swal-error-areyousure","Er du sikker?"),text:translationService.translate("web-swal-user-equipment-message","Utstyr vil bli fjernet!"),type:"warning",showCancelButton:!0,confirmButtonColor:"#f44336",confirmButtonText:translationService.translate("web-swal-user-equipment-button-confirm","Ja, fjern utstyret!"),cancelButtonText:translationService.translate("web-button-cancel","Avbryt"),closeOnConfirm:!1,showLoaderOnConfirm:!0},function(){window.onkeydown=null,window.onfocus=null,repository.deleteSingle(repository.apiData.userEquipment.url,equipment.Guid).then(function(result){window.onkeydown=null,window.onfocus=null,swal(translationService.translate("web-swal-user-equipment-success","Utstyret ble fjernet!"),result,"success"),repository.growl(translationService.translate("delete-user-equipment-success-message","Utstyret ble slettet fra systemet"),"success"),$scope.userEquipmentTable.reload()})}),$scope.$on($scope.events.newSelection,function(){updateAccess()})},$scope.$on("$stateChangeStart",function(event,toState,toParams,fromState,fromParams){"user.edit"!==toState.name&&$scope.update&&!$scope.isDeletingUser&&(0===$scope.dataOwnerTable.total()&&(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")),0===_.filter($scope.dataOwnerTable.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")),0===_.filter($scope.dataOwnerTable.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")))}),$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:"circle"}}}}).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};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,$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"))})}}angular.module("Plania").controller("UserController",["$scope","TranslationService","Repository","$modal","$stateParams","ngTableParams","$localStorage","$rootScope",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(JSON.stringify({Guid:webProfile.Guid,IndexPosition:webProfile.IndexPosition}))}$scope.isChanging=!0,repository.patch(repository.apiData.userXWebProfile.url,null,changeList).then(function(result){$scope.isChanging=!1,repository.growl(translationService.translate("web-userXWebProfile-reorderAndSave-success","Webprofiler har blitt oppdatert"),"success")},function(error){$scope.isChanging=!1})}},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 JSON.stringify({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 editetRows=[];selectedEntities.forEach(function(guid){editetRows.push(JSON.stringify({Guid:guid,GuidUserGroup:$scope.model.Guid}))}),repository.createMultiple(repository.apiData.massUpdate.url,editetRows,"Prefix="+repository.apiData.user.prefix).then(function(response){$scope.userTable.reload()})})},$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.createMultiple(repository.apiData.massUpdate.url,[JSON.stringify({Guid:user.Guid,GuidUserGroup:null})],"Prefix=User").then(function(result){repository.growl(translationService.translate("web-swal-usergroup-user-success","Brukeren ble fjernet!",result),"success"),$scope.userTable.reload(),swal.close()})})},$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.userProfileColumns=[],$scope.userProfileColumns.addColumn=function(translationId,defaultText,property,propertyType){return this.push({Position:this.length,Title:translationService.translate(translationId,defaultText),Property:property,PropertyType:propertyType}),this},$scope.userProfileColumns.addColumn("user-clientTable-dataOwnerName","Klient","LinkedDataOwner.Description","string").addColumn("user-clientTable-userProfileName","Profil","EntityPermissionProfile.Id","string").addColumn("user-clientTable-userProfileDescription","Profilbeskrivelse","EntityPermissionProfile.Description","string").addColumn("user-clientTable-isDefaultDataOwner","Standard Klient","IsDefaultDataOwner","string");var getCardTables=function(){$scope.dataOwnerTable=new ngTableParams({page:1,count:10,filter:{PropertyFilter:[{Property:"GuidUser",Operator:"=",Value:$scope.model.Guid}]}},{total:0,filterDelay:10,counts:[10,20,50],getData:function($defer,params){var columns=[];$scope.userProfileColumns.forEach(function(col){columns.push(col.Property)}),repository.GetPaginated(repository.apiData.userProfile.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,$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")}),getCardTables()):$scope.model.IsUserGroup=!0,$scope.GuidChangeLanguage=function(selectedLanguage){$scope.model.GuidLanguage=selectedLanguage.Guid},$scope.changeStartPage=function(selected){$scope.model.GuidWebMenu=selected.guid},$scope.removeDataOwner=function(dataOwner){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,dataOwner.Guid).then(function(result){repository.growl(translationService.translate("usergroup-removeDataOwner-Success","Klient ble fjernet fra brukergruppen."),"success"),$scope.dataOwnerTable.reload(),swal.close()})})},$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(),console.log($scope.model.AccessType);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.updateSingleDictionary(repository.apiData.user.url,$scope.model).then(success).catch(error):repository.createSingleDictionary(repository.apiData.user.url,$scope.model).then(success).catch(error)},$scope.addDataOwner=function(){$modal.open({templateUrl:"app/user/views/editUserDataOwner.html",controller:"CreateUserDataOwnerController",resolve:{params:function(){ return{guidUser:$scope.model.Guid,isFirst:$scope.dataOwnerTable.data.length<1}}}}).result.then(function(){$scope.dataOwnerTable.reload()})},$scope.updateDataOwner=function(dataOwner){$scope.restrictEdit||$scope.model.GuidUserGroup||$modal.open({templateUrl:"app/user/views/editUserDataOwner.html",controller:"EditUserDataOwnerController",resolve:{params:function(){return{guidUserProfile:dataOwner.Guid}}}}).result.then(function(){$scope.dataOwnerTable.reload()})},$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.updateSingleDictionary(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,$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.createMultipleWithGuid(repository.apiData.userXWebProfile.url,params.guidWebProfile,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(JSON.stringify({Guid:menu.Guid,IndexPosition:menu.IndexPosition}))}$scope.isWebMenusChanging=!0,repository.patch(repository.apiData.webProfileWebMenu.url,null,changeList).then(function(result){$scope.isWebMenusChanging=!1,repository.growl(translationService.translate("web-webProfile-reorderAndSave-success","Webmenyene har blitt oppdatert"),"success")},function(error){$scope.isWebMenusChanging=!1})}},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.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 JSON.stringify({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 JSON.stringify({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",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:"",Conditions:[],GeneratedFrom:repository.commonService.prefix.Condition};conditions.forEach(function(condition){newWorkOrder.Conditions.push({Guid: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(JSON.stringify(wo))}),$scope.isRunningAction=!0,$scope.reloadMainTable=!0,startSignalRListener(),$scope.currentTab="creationResults",repository.createMultiple(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-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}];$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,filter.PropertyFilter=[{Property:"IsTemplate",Operator:"=",Value:!1}]),"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.createSingleDictionary(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.createSingleDictionary(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","User.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.createSingleDictionary(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.updateSingleDictionary(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){$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,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()});var 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=!!$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&&!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&&(isDirtyEndDate=!0),oldValue&&!newValue&&(isDirtyEndDate=!1))}),$scope.getPropertyValue=function(building,column){return listService.GetPropertyValue(building,column)},$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:"lg",resolve:{params:function(){return{isUpdate:!1,excludeGuids:selectedGuids,workOrder:$scope.model}}}}).result.then(function(item){item&&item.GuidSparePart&&(item.GuidWorkOrder=$scope.model.Guid,repository.createSingleDictionary(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.updateSingleDictionary(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.updateSingleDictionary(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="zmdi-edit",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="zmdi-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="zmdi-edit",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="zmdi-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="zmdi-edit",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="zmdi-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&&repository.enableWebNavigation&&options.push(getMenuLink($rootScope.navigation.href("purchaseOrder.edit",{guid:item.GuidPurchaseOrder}),"zmdi-shopping-cart",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:"GUID_WORK_ORDER",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)},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","Person.FirstName","Person.LastName","Person.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","ResourceResponsible.FirstName","ResourceResponsible.LastName","ResourceResponsible.Email","User.RealName","User1.RealName","User2.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":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.Deviations=[],persistentData.guidSelections.forEach(function(guid){workOrder.Deviations.push({Guid: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.Conditions=[],persistentData.guidSelections.forEach(function(guid){workOrder.Conditions.push({Guid:guid})}),generatedFrom=repository.commonService.prefix.Condition),persistentData.fromEquipment&&(generatedFrom=repository.commonService.prefix.Equipment),persistentData.fromOperationalMessage&&(generatedFrom=repository.commonService.prefix.OperationalMessage,workOrder.OperationalMessages=[],persistentData.guidSelections.forEach(function(guid){workOrder.OperationalMessages.push({Guid: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))},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=repository.enableWebNavigation,$scope.isClosable="Proposal"===$scope.model.PurchaseOrderStatus||"NoOrder"===$scope.model.PurchaseOrderStatus,$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,isDirtyEndDate=!1,$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||payloadEntity.RequestAction?repository.updateSingleDictionary:repository.createSingleDictionary)(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)},$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 $localStorage.userData.isSystemAdministrator&&!$localStorage.userData.isProjectAdministrator?filter.PropertyFilter=[{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"},{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"}]:filter.PropertyFilter=[{Property:"GuidOwnerPerson",Operator:"=",value:$localStorage.userData.guidPerson,Operand:"AND"},{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"},{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"},{Property:"GuidManagerPerson",Operator:"=",value:$localStorage.userData.guidPerson,Operand:"OR"},{Property:"ClosedDate",Operator:"=",value:null,Operand:"AND"},{Property:"IsTemplate",Operator:"=",value:0,Operand:"AND"}],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.updateSingleDictionary(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){$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&&isDirtyEndDate&&workOrder.PeriodicTask&&"HourOfUse"===workOrder.PeriodicTask.Period?$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.createSingleDictionary(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 attachments=$scope.documents.concat($scope.model.Images),onNewDocument=function(){$scope.reloads.forceDocuments=!1,$timeout(function(){$scope.reloads.forceDocuments=!0},250)},reloadImages=function(){return repository.getMainModel(repository.apiData.workOrder.url,$stateParams.guid).then(function(response){return $scope.model.Images=response.Data.Images,$scope.model.Images})};$modal.open({templateUrl:"app/common/views/emailModal.html",controller:"EmailModalController",size:"lg",resolve:{params:function(){return{entity:"WorkOrder",columns:columns,model:$scope.model,attachments:attachments,getAllDocuments:$scope.counts.documentTotalCount>10,prefillSubjectWithCaption:!0,onNewDocument:onNewDocument,reloadImages:reloadImages}}}}).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.onPrioritySelect=function(priority){priority?($scope.model.GuidPriority=priority.Guid,priority.HasDeadline&&($scope.model.StartDate||($scope.model.StartDate=new Date),$scope.model.DueDate=enumService.getTimeUnitDate($scope.model.StartDate,priority.DeadlinePeriodUnit,priority.DeadlinePeriodNumber),$scope.restrictDueDate=!0)):($scope.model.GuidPriority=null,$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($scope.model.ActivityCategory&&!0===$scope.model.ActivityCategory.UseInRequest){for(var countCombo=1;countCombo<=40;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<=30;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",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){var payload={Guid:"00000000-0000-0000-0000-000000000000",RequestAction:"ActivateWorkOrders",RequestActionParameter1:JSON.stringify(workOrderGuids)};return repository.updateSingleDictionary(repository.apiData.workOrder.url,payload)},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