NINS_CODE/bahmniapps/bedmanagement/bedmanagement.min.6a5997f5.js
travelershot 70dda814aa codepush
2024-12-12 22:37:39 +06:00

9 lines
272 KiB
JavaScript

"use strict";angular.module("bahmni.common.routeErrorHandler",["ui.router"]).run(["$rootScope",function($rootScope){$rootScope.$on("$stateChangeError",function(event){event.preventDefault()})}]),angular.module("httpErrorInterceptor",[]).config(["$httpProvider",function($httpProvider){var interceptor=["$rootScope","$q",function($rootScope,$q){function stringAfter(value,searchString){var indexOfFirstColon=value.indexOf(searchString);return value.substr(indexOfFirstColon+1).trim()}function getServerError(message){return stringAfter(message,":")}function success(response){return response}function shouldRedirectToLogin(response){var errorMessage=response.data.error?response.data.error.message:response.data;if(errorMessage.search("HTTP Status 403 - Session timed out")>0)return!0}function error(response){var data=response.data,unexpectedError="There was an unexpected issue on the server. Please try again";if(500===response.status){var errorMessage=data.error&&data.error.message?getServerError(data.error.message):unexpectedError;showError(errorMessage)}else if(409===response.status){var errorMessage=data.error&&data.error.message?getServerError(data.error.message):"Duplicate entry error";showError(errorMessage)}else if(0===response.status)showError("Could not connect to the server. Please check your connection and try again");else if(405===response.status)showError(unexpectedError);else if(400===response.status){var errorMessage=data.error&&data.error.message?data.error.message:data.localizedMessage||"Could not connect to the server. Please check your connection and try again";showError(errorMessage)}else if(403===response.status){var errorMessage=data.error&&data.error.message?data.error.message:unexpectedError;shouldRedirectToLogin(response)?$rootScope.$broadcast("event:auth-loginRequired"):showError(errorMessage)}else 404===response.status&&(_.includes(response.config.url,"implementation_config")||_.includes(response.config.url,"locale_")||_.includes(response.config.url,"offlineMetadata")||showError("The requested information does not exist"));return $q.reject(response)}var serverErrorMessages=Bahmni.Common.Constants.serverErrorMessages,showError=function(errorMessage){var result=_.find(serverErrorMessages,function(listItem){return listItem.serverMessage===errorMessage});_.isEmpty(result)&&$rootScope.$broadcast("event:serverError",errorMessage)};return{response:success,responseError:error}}];$httpProvider.interceptors.push(interceptor)}]);var Bahmni=Bahmni||{};Bahmni.Auth=Bahmni.Auth||{},angular.module("authentication",["ui.router"]),Bahmni.Auth.User=function(user){angular.extend(this,user),this.userProperties=user.userProperties||{},this.favouriteObsTemplates=this.userProperties.favouriteObsTemplates?this.userProperties.favouriteObsTemplates.split("###"):[],this.favouriteWards=this.userProperties.favouriteWards?this.userProperties.favouriteWards.split("###"):[],this.recentlyViewedPatients=this.userProperties.recentlyViewedPatients?JSON.parse(this.userProperties.recentlyViewedPatients):[],this.toContract=function(){var user=angular.copy(this);return user.userProperties.favouriteObsTemplates=this.favouriteObsTemplates.join("###"),user.userProperties.favouriteWards=this.favouriteWards.join("###"),user.userProperties.recentlyViewedPatients=JSON.stringify(this.recentlyViewedPatients),delete user.favouriteObsTemplates,delete user.favouriteWards,delete user.recentlyViewedPatients,user},this.addDefaultLocale=function(locale){this.userProperties.defaultLocale=locale},this.addToRecentlyViewed=function(patient,maxPatients){_.some(this.recentlyViewedPatients,{uuid:patient.uuid})||(this.recentlyViewedPatients.unshift({uuid:patient.uuid,name:patient.name,identifier:patient.identifier}),_.size(this.recentlyViewedPatients)>=maxPatients&&(this.recentlyViewedPatients=_.take(this.recentlyViewedPatients,maxPatients)))},this.isFavouriteObsTemplate=function(conceptName){return _.includes(this.favouriteObsTemplates,conceptName)},this.toggleFavoriteObsTemplate=function(conceptName){this.isFavouriteObsTemplate(conceptName)?this.favouriteObsTemplates=_.without(this.favouriteObsTemplates,conceptName):this.favouriteObsTemplates.push(conceptName)},this.isFavouriteWard=function(wardName){return _.includes(this.favouriteWards,wardName)},this.toggleFavoriteWard=function(wardName){this.isFavouriteWard(wardName)?this.favouriteWards=_.without(this.favouriteWards,wardName):this.favouriteWards.push(wardName)}},angular.module("authentication").service("userService",["$rootScope","$http","$q",function($rootScope,$http,$q){var getUserFromServer=function(userName){return $http.get(Bahmni.Common.Constants.userUrl,{method:"GET",params:{username:userName,v:"custom:(username,uuid,person:(uuid,),privileges:(name,retired),userProperties)"},cache:!1})};this.getUser=function(userName){var deferrable=$q.defer();return getUserFromServer(userName).success(function(data){deferrable.resolve(data)}).error(function(){deferrable.reject("Unable to get user data")}),deferrable.promise},this.savePreferences=function(){var deferrable=$q.defer(),user=$rootScope.currentUser.toContract();return $http.post(Bahmni.Common.Constants.userUrl+"/"+user.uuid,{uuid:user.uuid,userProperties:user.userProperties},{withCredentials:!0}).then(function(response){$rootScope.currentUser.userProperties=response.data.userProperties,deferrable.resolve()}),deferrable.promise};var getProviderFromServer=function(uuid){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",params:{user:uuid},cache:!1})};this.getProviderForUser=function(uuid){var deferrable=$q.defer();return getProviderFromServer(uuid).success(function(data){if(data.results.length>0){var providerName=data.results[0].display.split("-")[1];data.results[0].name=providerName?providerName.trim():providerName,deferrable.resolve(data)}else deferrable.reject("UNABLE_TO_GET_PROVIDER_DATA")}).error(function(){deferrable.reject("UNABLE_TO_GET_PROVIDER_DATA")}),deferrable.promise},this.getPasswordPolicies=function(){return $http.get(Bahmni.Common.Constants.passwordPolicyUrl,{method:"GET",withCredentials:!0})},this.allowedDomains=function(redirectUrl){var deferrable=$q.defer();return $http.get(Bahmni.Common.Constants.loginConfig,{method:"GET",cache:!0}).success(function(data){deferrable.resolve(data.whiteListedDomains)}).error(function(){deferrable.resolve([])}),deferrable.promise}}]),angular.module("authentication").config(["$httpProvider",function($httpProvider){var interceptor=["$rootScope","$q",function($rootScope,$q){function success(response){return response}function error(response){return 401===response.status&&$rootScope.$broadcast("event:auth-loginRequired"),$q.reject(response)}return{response:success,responseError:error}}];$httpProvider.interceptors.push(interceptor)}]).run(["$rootScope","$window","$timeout",function($rootScope,$window,$timeout){$rootScope.$on("event:auth-loginRequired",function(){$timeout(function(){$window.location="../home/index.html#/login"})})}]).service("sessionService",["$rootScope","$http","$q","$bahmniCookieStore","userService",function($rootScope,$http,$q,$bahmniCookieStore,userService){var sessionResourcePath=Bahmni.Common.Constants.RESTWS_V1+"/session?v=custom:(uuid)",getAuthFromServer=function(username,password,otp){var btoa=otp?username+":"+password+":"+otp:username+":"+password;return $http.get(sessionResourcePath,{headers:{Authorization:"Basic "+window.btoa(btoa)},cache:!1})};this.resendOTP=function(username,password){var btoa=username+":"+password;return $http.get(sessionResourcePath+"&resendOTP=true",{headers:{Authorization:"Basic "+window.btoa(btoa)},cache:!1})};var createSession=function(username,password,otp){var deferrable=$q.defer();return destroySessionFromServer().success(function(){getAuthFromServer(username,password,otp).then(function(response){204==response.status&&deferrable.resolve({firstFactAuthorization:!0}),deferrable.resolve(response.data)},function(response){401==response.status?deferrable.reject("LOGIN_LABEL_WRONG_OTP_MESSAGE_KEY"):410==response.status?deferrable.reject("LOGIN_LABEL_OTP_EXPIRED"):429==response.status&&deferrable.reject("LOGIN_LABEL_MAX_FAILED_ATTEMPTS"),deferrable.reject("LOGIN_LABEL_LOGIN_ERROR_MESSAGE_KEY")})}).error(function(){deferrable.reject("LOGIN_LABEL_LOGIN_ERROR_MESSAGE_KEY")}),deferrable.promise},hasAnyActiveProvider=function(providers){return _.filter(providers,function(provider){return void 0==provider.retired||"false"==provider.retired}).length>0},self=this,destroySessionFromServer=function(){return $http.delete(sessionResourcePath)},sessionCleanup=function(){delete $.cookie(Bahmni.Common.Constants.currentUser,null,{path:"/"}),delete $.cookie(Bahmni.Common.Constants.currentUser,null,{path:"/"}),delete $.cookie(Bahmni.Common.Constants.retrospectiveEntryEncounterDateCookieName,null,{path:"/"}),delete $.cookie(Bahmni.Common.Constants.grantProviderAccessDataCookieName,null,{path:"/"}),$rootScope.currentUser=void 0};this.destroy=function(){var deferrable=$q.defer();return destroySessionFromServer().then(function(){sessionCleanup(),deferrable.resolve()}),deferrable.promise},this.loginUser=function(username,password,location,otp){var deferrable=$q.defer();return createSession(username,password,otp).then(function(data){data.authenticated?($bahmniCookieStore.put(Bahmni.Common.Constants.currentUser,username,{path:"/",expires:7}),void 0!=location&&($bahmniCookieStore.remove(Bahmni.Common.Constants.locationCookieName),$bahmniCookieStore.put(Bahmni.Common.Constants.locationCookieName,{name:location.display,uuid:location.uuid},{path:"/",expires:7})),deferrable.resolve(data)):data.firstFactAuthorization?deferrable.resolve(data):deferrable.reject("LOGIN_LABEL_LOGIN_ERROR_MESSAGE_KEY")},function(errorInfo){deferrable.reject(errorInfo)}),deferrable.promise},this.get=function(){return $http.get(sessionResourcePath,{cache:!1})},this.loadCredentials=function(){var deferrable=$q.defer(),currentUser=$bahmniCookieStore.get(Bahmni.Common.Constants.currentUser);return currentUser?(userService.getUser(currentUser).then(function(data){userService.getProviderForUser(data.results[0].uuid).then(function(providers){!_.isEmpty(providers.results)&&hasAnyActiveProvider(providers.results)?($rootScope.currentUser=new Bahmni.Auth.User(data.results[0]),$rootScope.currentUser.currentLocation=$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName).name,$rootScope.$broadcast("event:user-credentialsLoaded",data.results[0]),deferrable.resolve(data.results[0])):(self.destroy(),deferrable.reject("YOU_HAVE_NOT_BEEN_SETUP_PROVIDER"))},function(){self.destroy(),deferrable.reject("COULD_NOT_GET_PROVIDER")})},function(){self.destroy(),deferrable.reject("Could not get roles for the current user.")}),deferrable.promise):(this.destroy().finally(function(){$rootScope.$broadcast("event:auth-loginRequired"),deferrable.reject("No User in session. Please login again.")}),deferrable.promise)},this.getLoginLocationUuid=function(){return $bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName)?$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName).uuid:null},this.changePassword=function(currentUserUuid,oldPassword,newPassword){return $http({method:"POST",url:Bahmni.Common.Constants.passwordUrl,data:{oldPassword:oldPassword,newPassword:newPassword},headers:{"Content-Type":"application/json"}})},this.loadProviders=function(userInfo){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",params:{user:userInfo.uuid},cache:!1}).success(function(data){var providerUuid=data.results.length>0?data.results[0].uuid:void 0;$rootScope.currentProvider={uuid:providerUuid}})}}]).factory("authenticator",["$rootScope","$q","$window","sessionService",function($rootScope,$q,$window,sessionService){var authenticateUser=function(){var defer=$q.defer(),sessionDetails=sessionService.get();return sessionDetails.then(function(response){response.data.authenticated?defer.resolve():(defer.reject("User not authenticated"),$rootScope.$broadcast("event:auth-loginRequired"))}),defer.promise};return{authenticateUser:authenticateUser}}]).directive("logOut",["sessionService","$window","configurationService","auditLogService",function(sessionService,$window,configurationService,auditLogService){return{link:function(scope,element){element.bind("click",function(){scope.$apply(function(){auditLogService.log(void 0,"USER_LOGOUT_SUCCESS",void 0,"MODULE_LABEL_LOGOUT_KEY").then(function(){sessionService.destroy().then(function(){$window.location="../home/index.html#/login"})})})})}}}]).directive("btnUserInfo",[function(){return{restrict:"CA",link:function(scope,elem){elem.bind("click",function(event){$(this).next().toggleClass("active"),event.stopPropagation()}),$(document).find("body").bind("click",function(){$(elem).next().removeClass("active")})}}}]),angular.module("bahmni.common.config",[]),angular.module("bahmni.common.config").service("configurations",["configurationService",function(configurationService){this.configs={},this.load=function(configNames){var self=this;return configurationService.getConfigurations(_.difference(configNames,Object.keys(this.configs))).then(function(configurations){angular.extend(self.configs,configurations)})},this.dosageInstructionConfig=function(){return this.configs.dosageInstructionConfig||[]},this.stoppedOrderReasonConfig=function(){return this.configs.stoppedOrderReasonConfig||[]},this.dosageFrequencyConfig=function(){return this.configs.dosageFrequencyConfig||[]},this.allTestsAndPanelsConcept=function(){return this.configs.allTestsAndPanelsConcept.results[0]||[]},this.impressionConcept=function(){return this.configs.radiologyImpressionConfig.results[0]||[]},this.labOrderNotesConcept=function(){return this.configs.labOrderNotesConfig.results[0]||[]},this.consultationNoteConcept=function(){return this.configs.consultationNoteConfig.results[0]||[]},this.patientConfig=function(){return this.configs.patientConfig||{}},this.encounterConfig=function(){return angular.extend(new EncounterConfig,this.configs.encounterConfig||[])},this.patientAttributesConfig=function(){return this.configs.patientAttributesConfig.results},this.identifierTypesConfig=function(){return this.configs.identifierTypesConfig},this.genderMap=function(){return this.configs.genderMap},this.addressLevels=function(){return this.configs.addressLevels},this.relationshipTypes=function(){return this.configs.relationshipTypeConfig.results||[]},this.relationshipTypeMap=function(){return this.configs.relationshipTypeMap||{}},this.loginLocationToVisitTypeMapping=function(){return this.configs.loginLocationToVisitTypeMapping||{}},this.defaultEncounterType=function(){return this.configs.defaultEncounterType}}]),angular.module("bahmni.common.appFramework",["authentication"]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.AppFramework=Bahmni.Common.AppFramework||{},angular.module("bahmni.common.appFramework").config(["$compileProvider",function($compileProvider){$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|file):/)}]).service("appService",["$http","$q","sessionService","$rootScope","mergeService","loadConfigService","messagingService","$translate",function($http,$q,sessionService,$rootScope,mergeService,loadConfigService,messagingService,$translate){var currentUser=null,baseUrl=Bahmni.Common.Constants.baseUrl,customUrl=Bahmni.Common.Constants.customUrl,appDescriptor=null;$rootScope.meetId=null;var loadConfig=function(url){return loadConfigService.loadConfig(url,appDescriptor.contextPath)},loadTemplate=function(appDescriptor){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.contextPath+"/appTemplate.json").then(function(result){_.keys(result.data).length>0&&appDescriptor.setTemplate(result.data),deferrable.resolve(appDescriptor)},function(error){404!==error.status?deferrable.reject(error):deferrable.resolve(appDescriptor)}),deferrable.promise},setDefinition=function(baseResultData,customResultData){customResultData&&(_.keys(baseResultData).length>0||_.keys(customResultData.length>0))?appDescriptor.setDefinition(baseResultData,customResultData):_.keys(baseResultData).length>0&&appDescriptor.setDefinition(baseResultData)},loadDefinition=function(appDescriptor){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.contextPath+"/app.json").then(function(baseResult){baseResult.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.contextPath+"/app.json").then(function(customResult){setDefinition(baseResult.data,customResult.data),deferrable.resolve(appDescriptor)},function(){setDefinition(baseResult.data),deferrable.resolve(appDescriptor)}):(setDefinition(baseResult.data),deferrable.resolve(appDescriptor))},function(error){404!==error.status?deferrable.reject(error):deferrable.resolve(appDescriptor)}),deferrable.promise},setExtensions=function(baseResultData,customResultData){customResultData?appDescriptor.setExtensions(baseResultData,customResultData):appDescriptor.setExtensions(baseResultData)},loadExtensions=function(appDescriptor,extensionFileName){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.extensionPath+extensionFileName).then(function(baseResult){baseResult.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.extensionPath+extensionFileName).then(function(customResult){setExtensions(baseResult.data,customResult.data),deferrable.resolve(appDescriptor)},function(){setExtensions(baseResult.data),deferrable.resolve(appDescriptor)}):(setExtensions(baseResult.data),deferrable.resolve(appDescriptor))},function(error){404!==error.status?deferrable.reject(error):deferrable.resolve(appDescriptor)}),deferrable.promise},setDefaultPageConfig=function(pageName,baseResultData,customResultData){customResultData&&(_.keys(customResultData).length>0||_.keys(baseResultData).length>0)?appDescriptor.addConfigForPage(pageName,baseResultData,customResultData):_.keys(baseResultData).length>0&&appDescriptor.addConfigForPage(pageName,baseResultData)},hasPrivilegeOf=function(privilegeName){return _.some(currentUser.privileges,{name:privilegeName})},loadPageConfig=function(pageName,appDescriptor){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.contextPath+"/"+pageName+".json").then(function(baseResult){baseResult.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.contextPath+"/"+pageName+".json").then(function(customResult){setDefaultPageConfig(pageName,baseResult.data,customResult.data),deferrable.resolve(appDescriptor)},function(){setDefaultPageConfig(pageName,baseResult.data),deferrable.resolve(appDescriptor)}):(setDefaultPageConfig(pageName,baseResult.data),deferrable.resolve(appDescriptor))},function(error){404!==error.status?(messagingService.showMessage("error",$translate.instance("INCORRECT_CONFIGURATION_MESSAGE",{error:error.message})),deferrable.reject(error)):deferrable.resolve(appDescriptor)}),deferrable.promise};this.getAppDescriptor=function(){return appDescriptor},this.configBaseUrl=function(){return baseUrl},this.loadCsvFileFromConfig=function(name){return loadConfig(baseUrl+appDescriptor.contextPath+"/"+name)},this.loadConfig=function(name,shouldMerge){return loadConfig(baseUrl+appDescriptor.contextPath+"/"+name).then(function(baseResponse){return baseResponse.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.contextPath+"/"+name).then(function(customResponse){return shouldMerge||void 0===shouldMerge?mergeService.merge(baseResponse.data,customResponse.data):[baseResponse.data,customResponse.data]},function(){return baseResponse.data}):baseResponse.data})},this.loadMandatoryConfig=function(path){return $http.get(path)},this.getAppName=function(){return this.appName},this.checkPrivilege=function(privilegeName){return hasPrivilegeOf(privilegeName)?$q.when(!0):(messagingService.showMessage("error",$translate.instant(Bahmni.Common.Constants.privilegeRequiredErrorMessage)+" [Privileges required: "+privilegeName+"]"),$q.reject())},this.initApp=function(appName,options,extensionFileSuffix,configPages){this.appName=appName;var appLoader=$q.defer(),extensionFileName=extensionFileSuffix&&"default"!==extensionFileSuffix.toLowerCase()?"/extension-"+extensionFileSuffix+".json":"/extension.json",promises=[],opts=options||{app:!0,extension:!0},inheritAppContext=!opts.inherit||opts.inherit;appDescriptor=new Bahmni.Common.AppFramework.AppDescriptor(appName,inheritAppContext,function(){return currentUser},mergeService);var loadCredentialsPromise=sessionService.loadCredentials(),loadProviderPromise=loadCredentialsPromise.then(sessionService.loadProviders);return promises.push(loadCredentialsPromise),promises.push(loadProviderPromise),opts.extension&&promises.push(loadExtensions(appDescriptor,extensionFileName)),opts.template&&promises.push(loadTemplate(appDescriptor)),opts.app&&promises.push(loadDefinition(appDescriptor)),_.isEmpty(configPages)||configPages.forEach(function(configPage){promises.push(loadPageConfig(configPage,appDescriptor))}),$q.all(promises).then(function(results){currentUser=results[0],appLoader.resolve(appDescriptor),$rootScope.$broadcast("event:appExtensions-loaded")},function(errors){appLoader.reject(errors)}),appLoader.promise}}]),angular.module("bahmni.common.appFramework").service("mergeService",[function(){this.merge=function(base,custom){var mergeResult=$.extend(!0,{},base,custom);return deleteNullValuedKeys(mergeResult)};var deleteNullValuedKeys=function(currentObject){return _.forOwn(currentObject,function(value,key){(_.isUndefined(value)||_.isNull(value)||_.isNaN(value)||_.isObject(value)&&_.isNull(deleteNullValuedKeys(value)))&&delete currentObject[key]}),currentObject}}]),angular.module("bahmni.common.appFramework").directive("appExtensionList",["appService",function(appService){var appDescriptor=appService.getAppDescriptor();return{restrict:"EA",template:'<ul><li ng-repeat="appExtn in appExtensions"><a href="{{formatUrl(appExtn.url, extnParams)}}" class="{{appExtn.icon}}" onclick="return false;" title="{{appExtn.label}}" ng-click="extnLinkClick(appExtn, extnParams)"> <span ng-show="showLabel">{{appExtn.label}}</span></a></li></ul>',scope:{extnPointId:"@",showLabel:"@",onExtensionClick:"&",contextModel:"&"},compile:function(cElement,cAttrs){var extnList=appDescriptor.getExtensions(cAttrs.extnPointId);return function(scope){scope.appExtensions=extnList;var model=scope.contextModel();scope.extnParams=model||{}}},controller:function($scope,$location){$scope.formatUrl=appDescriptor.formatUrl,$scope.extnLinkClick=function(extn,params){var proceedWithDefault=!0,clickHandler=$scope.onExtensionClick(),target=appDescriptor.formatUrl(extn.url,params);if(clickHandler){var event={src:extn,target:target,params:params,preventDefault:function(){proceedWithDefault=!1}};clickHandler(event)}proceedWithDefault&&$location.url(target)}}}}]),Bahmni.Common.AppFramework.AppDescriptor=function(context,inheritContext,retrieveUserCallback,mergeService){this.id=null,this.instanceOf=null,this.description=null,this.contextModel=null,this.baseExtensionPoints=[],this.customExtensionPoints=[],this.baseExtensions={},this.customExtensions={},this.customConfigs={},this.baseConfigs={},this.extensionPath=context,this.contextPath=inheritContext?context.split("/")[0]:context;var self=this,setExtensionPointsFromExtensions=function(currentExtensions,currentExtensionPoints){_.values(currentExtensions).forEach(function(extn){if(extn){var existing=self[currentExtensionPoints].filter(function(ep){return ep.id===extn.extensionPointId});0===existing.length&&self[currentExtensionPoints].push({id:extn.extensionPointId,description:extn.description})}})};this.setExtensions=function(baseExtensions,customExtensions){customExtensions&&(setExtensionPointsFromExtensions(customExtensions,"customExtensionPoints"),self.customExtensions=customExtensions),self.baseExtensions=baseExtensions,setExtensionPointsFromExtensions(baseExtensions,"baseExtensionPoints")},this.setTemplate=function(template){self.instanceOf=template.id,self.description=self.description||template.description,self.contextModel=self.contextModel||template.contextModel,template.configOptions&&_.values(template.configOptions).forEach(function(opt){var existing=self.configs.filter(function(cfg){return cfg.name===opt.name});existing.length>0?existing[0].description=opt.description:self.configs.push({name:opt.name,description:opt.description,value:opt.defaultValue})})};var setConfig=function(instance,currentConfig){for(var configName in instance.config){var existingConfig=getConfig(self[currentConfig],configName);existingConfig?existingConfig.value=instance.config[configName]:self[currentConfig][configName]={name:configName,value:instance.config[configName]}}},setDefinitionExtensionPoints=function(extensionPoints,currentExtensionPoints){extensionPoints&&extensionPoints.forEach(function(iep){if(iep){var existing=self[currentExtensionPoints].filter(function(ep){return ep.id===iep.id});0===existing.length&&self[currentExtensionPoints].push(iep)}})};this.setDefinition=function(baseInstance,customInstance){self.instanceOf=customInstance&&customInstance.instanceOf?customInstance.instanceOf:baseInstance.instanceOf,self.id=customInstance&&customInstance.id?customInstance.id:baseInstance.id,self.description=customInstance&&customInstance.description?customInstance.description:baseInstance.description,self.contextModel=customInstance&&customInstance.contextModel?customInstance.contextModel:baseInstance.contextModel,setDefinitionExtensionPoints(baseInstance.extensionPoints,"baseExtensionPoints"),setConfig(baseInstance,"baseConfigs"),customInstance&&(setDefinitionExtensionPoints(customInstance.extensionPoints,"customExtensionPoints"),setConfig(customInstance,"customConfigs"))};var getExtensions=function(extPointId,type,extensions){var currentUser=retrieveUserCallback(),currentExtensions=_.values(extensions);if(currentUser&&currentExtensions){var extnType=type||"all",userPrivileges=currentUser.privileges.map(function(priv){return priv.retired?"":priv.name}),appsExtns=currentExtensions.filter(function(extn){return("all"===extnType||extn.type===extnType)&&extn.extensionPointId===extPointId&&(!extn.requiredPrivilege||userPrivileges.indexOf(extn.requiredPrivilege)>=0)});return appsExtns.sort(function(extn1,extn2){return extn1.order-extn2.order}),appsExtns}};this.getExtensions=function(extPointId,type,shouldMerge){if(shouldMerge||void 0===shouldMerge){var mergedExtensions=mergeService.merge(self.baseExtensions,self.customExtensions);return getExtensions(extPointId,type,mergedExtensions)}return[getExtensions(extPointId,type,self.baseExtensions),getExtensions(extPointId,type,self.customExtensions)]},this.getExtensionById=function(id,shouldMerge){if(shouldMerge||void 0===shouldMerge){var mergedExtensions=_.values(mergeService.merge(self.baseExtensions,self.customExtensions));return mergedExtensions.filter(function(extn){return extn.id===id})[0]}return[self.baseExtensions.filter(function(extn){return extn.id===id})[0],self.customExtensions.filter(function(extn){return extn.id===id})[0]]};var getConfig=function(config,configName){var cfgList=_.values(config).filter(function(cfg){return cfg.name===configName});return cfgList.length>0?cfgList[0]:null};this.getConfig=function(configName,shouldMerge){return shouldMerge||void 0===shouldMerge?getConfig(mergeService.merge(self.baseConfigs,self.customConfigs),configName):[getConfig(self.baseConfigs,configName),getConfig(self.customConfigs,configName)]},this.getConfigValue=function(configName,shouldMerge){var config=this.getConfig(configName,shouldMerge);return shouldMerge||void 0===shouldMerge?config?config.value:null:config},this.formatUrl=function(url,options,useQueryParams){var pattern=/{{([^}]*)}}/g,matches=url.match(pattern),replacedString=url,checkQueryParams=useQueryParams||!1,queryParameters=this.parseQueryParams();return matches&&matches.forEach(function(el){var key=el.replace("{{","").replace("}}",""),value=options[key];value||checkQueryParams!==!0||(value=queryParameters[key]||null),replacedString=replacedString.replace(el,value)}),replacedString.trim()},this.parseQueryParams=function(locationSearchString){var urlParams,match,pl=/\+/g,search=/([^&=]+)=?([^&]*)/g,decode=function(s){return decodeURIComponent(s.replace(pl," "))},queryString=locationSearchString||window.location.search.substring(1);for(urlParams={};match=search.exec(queryString);)urlParams[decode(match[1])]=decode(match[2]);return urlParams},this.addConfigForPage=function(pageName,baseConfig,customConfig){self.basePageConfigs=self.basePageConfigs||{},self.basePageConfigs[pageName]=baseConfig,self.customPageConfigs=self.customPageConfigs||{},self.customPageConfigs[pageName]=customConfig},this.getConfigForPage=function(pageName,shouldMerge){return shouldMerge||void 0===shouldMerge?mergeService.merge(self.basePageConfigs[pageName],self.customPageConfigs[pageName]):[_.values(self.basePageConfigs[pageName]),_.values(self.customPageConfigs[pageName])]}},angular.module("bahmni.common.appFramework").service("loadConfigService",["$http",function($http){this.loadConfig=function(url){return $http.get(url,{withCredentials:!0})}}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},function(){var hostUrl=localStorage.getItem("host")?"https://"+localStorage.getItem("host"):"",rootDir=localStorage.getItem("rootDir")||"",RESTWS=hostUrl+"/openmrs/ws/rest",RESTWS_V1=hostUrl+"/openmrs/ws/rest/v1",BAHMNI_CORE=RESTWS_V1+"/bahmnicore",EMRAPI=RESTWS+"/emrapi",BACTERIOLOGY=RESTWS_V1,BASE_URL=hostUrl+"/bahmni_config/openmrs/apps/",CUSTOM_URL=hostUrl+"/implementation_config/openmrs/apps/",IE_APPS_API=RESTWS_V1+"/bahmniie",serverErrorMessages=[{serverMessage:"Cannot have more than one active order for the same orderable and care setting at same time",clientMessage:"One or more drugs you are trying to order are already active. Please change the start date of the conflicting drug or remove them from the new prescription."},{serverMessage:"[Order.cannot.have.more.than.one]",clientMessage:"One or more drugs you are trying to order are already active. Please change the start date of the conflicting drug or remove them from the new prescription."}],representation="custom:(uuid,name,names,conceptClass,setMembers:(uuid,name,names,conceptClass,setMembers:(uuid,name,names,conceptClass,setMembers:(uuid,name,names,conceptClass))))",unAuthenticatedReferenceDataMap={"/openmrs/ws/rest/v1/location?tags=Login+Location&s=byTags&v=default":"LoginLocations","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=locale.allowed.list":"LocaleList"},authenticatedReferenceDataMap={"/openmrs/ws/rest/v1/idgen/identifiertype":"IdentifierTypes","/openmrs/module/addresshierarchy/ajax/getOrderedAddressHierarchyLevels.form":"AddressHierarchyLevels","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=mrs.genders":"Genders","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=bahmni.encountersession.duration":"encounterSessionDuration","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=bahmni.relationshipTypeMap":"RelationshipTypeMap","/openmrs/ws/rest/v1/bahmnicore/config/bahmniencounter?callerContext=REGISTRATION_CONCEPTS":"RegistrationConcepts","/openmrs/ws/rest/v1/relationshiptype?v=custom:(aIsToB,bIsToA,uuid)":"RelationshipType","/openmrs/ws/rest/v1/personattributetype?v=custom:(uuid,name,sortWeight,description,format,concept)":"PersonAttributeType","/openmrs/ws/rest/v1/entitymapping?mappingType=loginlocation_visittype&s=byEntityAndMappingType":"LoginLocationToVisitTypeMapping","/openmrs/ws/rest/v1/bahmnicore/config/patient":"PatientConfig","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Consultation+Note&v=custom:(uuid,name,answers)":"ConsultationNote","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Lab+Order+Notes&v=custom:(uuid,name)":"LabOrderNotes","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Impression&v=custom:(uuid,name)":"RadiologyImpressionConfig","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=All_Tests_and_Panels&v=custom:(uuid,name:(uuid,name),setMembers:(uuid,name:(uuid,name)))":"AllTestsAndPanelsConcept",
"/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Dosage+Frequency&v=custom:(uuid,name,answers)":"DosageFrequencyConfig","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Dosage+Instructions&v=custom:(uuid,name,answers)":"DosageInstructionConfig","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=bahmni.encounterType.default":"DefaultEncounterType","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Stopped+Order+Reason&v=custom:(uuid,name,answers)":"StoppedOrderReasonConfig","/openmrs/ws/rest/v1/ordertype":"OrderType","/openmrs/ws/rest/v1/bahmnicore/config/drugOrders":"DrugOrderConfig","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=drugOrder.drugOther":"NonCodedDrugConcept"};authenticatedReferenceDataMap["/openmrs/ws/rest/v1/entitymapping?mappingType=location_encountertype&s=byEntityAndMappingType&entityUuid="+(localStorage.getItem("LoginInformation")?JSON.parse(localStorage.getItem("LoginInformation")).currentLocation.uuid:"")]="LoginLocationToEncounterTypeMapping",Bahmni.Common.Constants={hostURL:hostUrl,dateFormat:"dd/mm/yyyy",dateDisplayFormat:"DD-MMM-YYYY",timeDisplayFormat:"hh:mm",emrapiDiagnosisUrl:EMRAPI+"/diagnosis",bahmniDiagnosisUrl:BAHMNI_CORE+"/diagnosis/search",bahmniDeleteDiagnosisUrl:BAHMNI_CORE+"/diagnosis/delete",diseaseTemplateUrl:BAHMNI_CORE+"/diseaseTemplates",AllDiseaseTemplateUrl:BAHMNI_CORE+"/diseaseTemplate",emrapiConceptUrl:EMRAPI+"/concept",encounterConfigurationUrl:BAHMNI_CORE+"/config/bahmniencounter",patientConfigurationUrl:BAHMNI_CORE+"/config/patient",drugOrderConfigurationUrl:BAHMNI_CORE+"/config/drugOrders",emrEncounterUrl:EMRAPI+"/encounter",encounterUrl:RESTWS_V1+"/encounter",locationUrl:RESTWS_V1+"/location",bahmniVisitLocationUrl:BAHMNI_CORE+"/visitLocation",bahmniOrderUrl:BAHMNI_CORE+"/orders",bahmniDrugOrderUrl:BAHMNI_CORE+"/drugOrders",bahmniDispositionByVisitUrl:BAHMNI_CORE+"/disposition/visitWithLocale",bahmniDispositionByPatientUrl:BAHMNI_CORE+"/disposition/patientWithLocale",bahmniSearchUrl:BAHMNI_CORE+"/search",bahmniLabOrderResultsUrl:BAHMNI_CORE+"/labOrderResults",bahmniEncounterUrl:BAHMNI_CORE+"/bahmniencounter",conceptUrl:RESTWS_V1+"/concept",bahmniConceptAnswerUrl:RESTWS_V1+"/bahmniconceptanswer",conceptSearchByFullNameUrl:RESTWS_V1+"/concept?s=byFullySpecifiedName",visitUrl:RESTWS_V1+"/visit",endVisitUrl:BAHMNI_CORE+"/visit/endVisit",endVisitAndCreateEncounterUrl:BAHMNI_CORE+"/visit/endVisitAndCreateEncounter",visitTypeUrl:RESTWS_V1+"/visittype",patientImageUrlByPatientUuid:RESTWS_V1+"/patientImage?patientUuid=",labResultUploadedFileNameUrl:"/uploaded_results/",visitSummaryUrl:BAHMNI_CORE+"/visit/summary",encounterModifierUrl:BAHMNI_CORE+"/bahmniencountermodifier",openmrsUrl:hostUrl+"/openmrs",loggingUrl:hostUrl+"/log/",idgenConfigurationURL:RESTWS_V1+"/idgen/identifiertype",bahmniRESTBaseURL:BAHMNI_CORE+"",observationsUrl:BAHMNI_CORE+"/observations",obsRelationshipUrl:BAHMNI_CORE+"/obsrelationships",encounterImportUrl:BAHMNI_CORE+"/admin/upload/encounter",programImportUrl:BAHMNI_CORE+"/admin/upload/program",conceptImportUrl:BAHMNI_CORE+"/admin/upload/concept",conceptSetImportUrl:BAHMNI_CORE+"/admin/upload/conceptset",drugImportUrl:BAHMNI_CORE+"/admin/upload/drug",labResultsImportUrl:BAHMNI_CORE+"/admin/upload/labResults",referenceTermsImportUrl:BAHMNI_CORE+"/admin/upload/referenceterms",updateReferenceTermsImportUrl:BAHMNI_CORE+"/admin/upload/referenceterms/new",relationshipImportUrl:BAHMNI_CORE+"/admin/upload/relationship",conceptSetExportUrl:BAHMNI_CORE+"/admin/export/conceptset?conceptName=:conceptName",patientImportUrl:BAHMNI_CORE+"/admin/upload/patient",adminImportStatusUrl:BAHMNI_CORE+"/admin/upload/status",programUrl:RESTWS_V1+"/program",programEnrollPatientUrl:RESTWS_V1+"/bahmniprogramenrollment",programStateDeletionUrl:RESTWS_V1+"/programenrollment",programEnrollmentDefaultInformation:"default",programEnrollmentFullInformation:"full",programAttributeTypes:RESTWS_V1+"/programattributetype",relationshipTypesUrl:RESTWS_V1+"/relationshiptype",personAttributeTypeUrl:RESTWS_V1+"/personattributetype",diseaseSummaryPivotUrl:BAHMNI_CORE+"/diseaseSummaryData",allTestsAndPanelsConceptName:"All_Tests_and_Panels",dosageFrequencyConceptName:"Dosage Frequency",dosageInstructionConceptName:"Dosage Instructions",stoppedOrderReasonConceptName:"Stopped Order Reason",consultationNoteConceptName:"Consultation Note",diagnosisConceptSet:"Diagnosis Concept Set",radiologyOrderType:"Radiology Order",radiologyResultConceptName:"Radiology Result",investigationEncounterType:"INVESTIGATION",validationNotesEncounterType:"VALIDATION NOTES",labOrderNotesConcept:"Lab Order Notes",impressionConcept:"Impression",qualifiedByRelationshipType:"qualified-by",dispositionConcept:"Disposition",dispositionGroupConcept:"Disposition Set",dispositionNoteConcept:"Disposition Note",ruledOutDiagnosisConceptName:"Ruled Out Diagnosis",emrapiConceptMappingSource:"org.openmrs.module.emrapi",abbreviationConceptMappingSource:"Abbreviation",includeAllObservations:!1,openmrsObsUrl:RESTWS_V1+"/obs",openmrsObsRepresentation:"custom:(uuid,obsDatetime,value:(uuid,name:(uuid,name)))",admissionCode:"ADMIT",dischargeCode:"DISCHARGE",transferCode:"TRANSFER",undoDischargeCode:"UNDO_DISCHARGE",vitalsConceptName:"Vitals",heightConceptName:"HEIGHT",weightConceptName:"WEIGHT",bmiConceptName:"BMI",bmiStatusConceptName:"BMI STATUS",abnormalObservationConceptName:"IS_ABNORMAL",documentsPath:"/document_images",documentsConceptName:"Document",miscConceptClassName:"Misc",abnormalConceptClassName:"Abnormal",unknownConceptClassName:"Unknown",durationConceptClassName:"Duration",conceptDetailsClassName:"Concept Details",admissionEncounterTypeName:"ADMISSION",dischargeEncounterTypeName:"DISCHARGE",imageClassName:"Image",videoClassName:"Video",locationCookieName:"bahmni.user.location",retrospectiveEntryEncounterDateCookieName:"bahmni.clinical.retrospectiveEncounterDate",JSESSIONID:"JSESSIONID",rootScopeRetrospectiveEntry:"retrospectiveEntry.encounterDate",patientFileConceptName:"Patient file",serverErrorMessages:serverErrorMessages,currentUser:"bahmni.user",retrospectivePrivilege:"app:clinical:retrospective",locationPickerPrivilege:"app:clinical:locationpicker",onBehalfOfPrivilege:"app:clinical:onbehalf",nutritionalConceptName:"Nutritional Values",messageForNoObservation:"NO_OBSERVATIONS_CAPTURED",messageForNoDisposition:"NO_DISPOSTIONS_AVAILABLE_MESSAGE_KEY",messageForNoFulfillment:"NO_FULFILMENT_MESSAGE",reportsUrl:"/bahmnireports",uploadReportTemplateUrl:"/bahmnireports/upload",ruledOutdiagnosisStatus:"Ruled Out Diagnosis",registartionConsultationPrivilege:"app:common:registration_consultation_link",manageIdentifierSequencePrivilege:"Manage Identifier Sequence",closeVisitPrivilege:"app:common:closeVisit",deleteDiagnosisPrivilege:"app:clinical:deleteDiagnosis",viewPatientsPrivilege:"View Patients",editPatientsPrivilege:"Edit Patients",addVisitsPrivilege:"Add Visits",deleteVisitsPrivilege:"Delete Visits",grantProviderAccess:"app:clinical:grantProviderAccess",grantProviderAccessDataCookieName:"app.clinical.grantProviderAccessData",globalPropertyUrl:BAHMNI_CORE+"/sql/globalproperty",passwordPolicyUrl:BAHMNI_CORE+"/globalProperty/passwordPolicyProperties",fulfillmentConfiguration:"fulfillment",fulfillmentFormSuffix:" Fulfillment Form",noNavigationLinksMessage:"NO_NAVIGATION_LINKS_AVAILABLE_MESSAGE",conceptSetRepresentationForOrderFulfillmentConfig:representation,entityMappingUrl:RESTWS_V1+"/entitymapping",encounterTypeUrl:RESTWS_V1+"/encountertype",defaultExtensionName:"default",orderSetMemberAttributeTypeUrl:RESTWS_V1+"/ordersetmemberattributetype",orderSetUrl:RESTWS_V1+"/bahmniorderset",primaryOrderSetMemberAttributeTypeName:"Primary",bahmniBacteriologyResultsUrl:BACTERIOLOGY+"/specimen",bedFromVisit:RESTWS_V1+"/beds",ordersUrl:RESTWS_V1+"/order",formDataUrl:RESTWS_V1+"/obs",providerUrl:RESTWS_V1+"/provider",drugUrl:RESTWS_V1+"/drug",orderTypeUrl:RESTWS_V1+"/ordertype",userUrl:RESTWS_V1+"/user",passwordUrl:RESTWS_V1+"/password",formUrl:RESTWS_V1+"/form",allFormsUrl:RESTWS_V1+"/bahmniie/form/allForms",latestPublishedForms:RESTWS_V1+"/bahmniie/form/latestPublishedForms",formTranslationsUrl:RESTWS_V1+"/bahmniie/form/translations",sqlUrl:BAHMNI_CORE+"/sql",patientAttributeDateFieldFormat:"org.openmrs.util.AttributableDate",platform:"user.platform",RESTWS_V1:RESTWS_V1,baseUrl:BASE_URL,customUrl:CUSTOM_URL,faviconUrl:hostUrl+"/bahmni/favicon.ico",platformType:{other:"other"},numericDataType:"Numeric",encryptionType:{SHA3:"SHA3"},LoginInformation:"LoginInformation",ServerDateTimeFormat:"YYYY-MM-DDTHH:mm:ssZZ",calculateDose:BAHMNI_CORE+"/calculateDose",unAuthenticatedReferenceDataMap:unAuthenticatedReferenceDataMap,authenticatedReferenceDataMap:authenticatedReferenceDataMap,rootDir:rootDir,dischargeUrl:BAHMNI_CORE+"/discharge",uuidRegex:"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",eventlogFilterUrl:hostUrl+"/openmrs/ws/rest/v1/eventlog/filter",bahmniConnectMetaDataDb:"metaData",serverDateTimeUrl:"/cgi-bin/systemdate",loginText:"/bahmni_config/openmrs/apps/home/whiteLabel.json",auditLogUrl:RESTWS_V1+"/auditlog",appointmentServiceUrl:RESTWS_V1+"/appointmentService",conditionUrl:EMRAPI+"/condition",conditionHistoryUrl:EMRAPI+"/conditionhistory",followUpConditionConcept:"Follow-up Condition",localeLangs:"/bahmni_config/openmrs/apps/home/locale_languages.json",privilegeRequiredErrorMessage:"PRIVILEGE_REQUIRED",patientFormsUrl:BAHMNI_CORE+"/patient/{patientUuid}/forms",defaultPossibleRelativeSearchLimit:10,formBuilderDisplayControlType:"formsV2",formBuilderType:"v2",formBuilderTranslationApi:IE_APPS_API+"/form/translate",disposition:"DISPOSITION",registration:"REGISTRATION",clinical:"CLINICAL",diagnosis:"DIAGNOSIS",ot:"OT",patientAttribute:"PATIENT_ATTRIBUTE",program:"PROGRAM",visitType:"VISIT_TYPE",bedmanagement:"BEDMANAGEMENT",bedmanagementDisposition:"BEDMANAGEMENT_DISPOSITION",loginConfig:"/bahmni_config/openmrs/apps/home/login_config.json",visit:"VISIT"}}();var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Util=Bahmni.Common.Util||{},angular.module("bahmni.common.util",[]).provider("$bahmniCookieStore",[function(){var self=this;self.defaultOptions={};var fixedEncodeURIComponent=function(str){return encodeURIComponent(str).replace(/[!'()*]/g,function(c){return"%"+c.charCodeAt(0).toString(16)})};self.setDefaultOptions=function(options){self.defaultOptions=options},self.$get=function(){return{get:function(name){var jsonCookie=$.cookie(name);return jsonCookie?angular.fromJson(decodeURIComponent(jsonCookie)):null},put:function(name,value,options){options=$.extend({},self.defaultOptions,options),$.cookie.raw=!0,$.cookie(name,fixedEncodeURIComponent(angular.toJson(value)),options)},remove:function(name,options){options=$.extend({},self.defaultOptions,options),$.removeCookie(name,options)}}}}]),Bahmni.Common.Util.DateUtil={diffInDays:function(dateFrom,dateTo){return Math.floor((this.parse(dateTo)-this.parse(dateFrom))/864e5)},diffInMinutes:function(dateFrom,dateTo){return moment(dateTo).diff(moment(dateFrom),"minutes")},diffInSeconds:function(dateFrom,dateTo){return moment(dateFrom).diff(moment(dateTo),"seconds")},isInvalid:function(date){return"Invalid Date"==date},diffInDaysRegardlessOfTime:function(dateFrom,dateTo){var from=new Date(dateFrom),to=new Date(dateTo);return from.setHours(0,0,0,0),to.setHours(0,0,0,0),Math.floor((to-from)/864e5)},addSeconds:function(date,seconds){return moment(date).add(seconds,"seconds").toDate()},addMinutes:function(date,minutes){return this.addSeconds(date,60*minutes)},addDays:function(date,days){return moment(date).add(days,"day").toDate()},addMonths:function(date,months){return moment(date).add(months,"month").toDate()},addYears:function(date,years){return moment(date).add(years,"year").toDate()},subtractSeconds:function(date,seconds){return moment(date).subtract(seconds,"seconds").toDate()},subtractDays:function(date,days){return this.addDays(date,-1*days)},subtractISOWeekDays:function(date,days){return null==days?moment(date).isoWeekday():moment(date).isoWeekday()>=days?moment(date).isoWeekday()-days:7+moment(date).isoWeekday()-days},subtractMonths:function(date,months){return this.addMonths(date,-1*months)},subtractYears:function(date,years){return this.addYears(date,-1*years)},createDays:function(startDate,endDate){for(var startDate=this.getDate(startDate),endDate=this.getDate(endDate),numberOfDays=this.diffInDays(startDate,endDate),days=[],i=0;i<=numberOfDays;i++)days.push({dayNumber:i+1,date:this.addDays(startDate,i)});return days},getDayNumber:function(referenceDate,date){return this.diffInDays(this.getDate(referenceDate),this.getDate(date))+1},getDateWithoutTime:function(datetime){return datetime?moment(datetime).format("YYYY-MM-DD"):null},getDateInMonthsAndYears:function(date,format){var format=format||"MMM YY",dateRepresentation=isNaN(Number(date))?date:Number(date);return moment(dateRepresentation).isValid()?dateRepresentation?moment(dateRepresentation).format(format):null:date},formatDateWithTime:function(datetime){var dateRepresentation=isNaN(Number(datetime))?datetime:Number(datetime);return moment(dateRepresentation).isValid()?dateRepresentation?moment(dateRepresentation).format("DD MMM YY h:mm a"):null:datetime},formatDateWithoutTime:function(date){var dateRepresentation=isNaN(Number(date))?date:Number(date);return moment(dateRepresentation).isValid()?dateRepresentation?moment(dateRepresentation).format("DD MMM YY"):null:date},formatDateInStrictMode:function(date){var dateRepresentation=isNaN(Number(date))?date:Number(date);return moment(dateRepresentation,"YYYY-MM-DD",!0).isValid()?moment(dateRepresentation).format("DD MMM YY"):moment(dateRepresentation,"YYYY-MM-DDTHH:mm:ss.SSSZZ",!0).isValid()?moment(dateRepresentation).format("DD MMM YY"):date},formatTime:function(date){var dateRepresentation=isNaN(Number(date))?date:Number(date);return moment(dateRepresentation).isValid()?dateRepresentation?moment(dateRepresentation).format("h:mm a"):null:date},getDate:function(dateTime){return moment(this.parse(dateTime)).startOf("day").toDate()},parse:function(dateString){return dateString?moment(dateString).toDate():null},parseDatetime:function(dateTimeString){return dateTimeString?moment(dateTimeString):null},now:function(){return new Date},today:function(){return this.getDate(this.now())},endOfToday:function(){return moment(this.parse(this.now())).endOf("day").toDate()},getDateWithoutHours:function(dateString){return moment(dateString).toDate().setHours(0,0,0,0)},getDateTimeWithoutSeconds:function(dateString){return moment(dateString).toDate().setSeconds(0,0)},isSameDateTime:function(date1,date2){if(null==date1||null==date2)return!1;var dateOne=this.parse(date1),dateTwo=this.parse(date2);return dateOne.getTime()==dateTwo.getTime()},isBeforeDate:function(date1,date2){return moment(date1).isBefore(moment(date2))},isSameDate:function(date1,date2){if(null==date1||null==date2)return!1;var dateOne=this.parse(date1),dateTwo=this.parse(date2);return dateOne.getFullYear()===dateTwo.getFullYear()&&dateOne.getMonth()===dateTwo.getMonth()&&dateOne.getDate()===dateTwo.getDate()},diffInYearsMonthsDays:function(dateFrom,dateTo){dateFrom=this.parse(dateFrom),dateTo=this.parse(dateTo);var from={d:dateFrom.getDate(),m:dateFrom.getMonth(),y:dateFrom.getFullYear()},to={d:dateTo.getDate(),m:dateTo.getMonth(),y:dateTo.getFullYear()},age={d:0,m:0,y:0},daysFebruary=to.y%4!=0||to.y%100==0&&to.y%400!=0?28:29,daysInMonths=[31,daysFebruary,31,30,31,30,31,31,30,31,30,31];return age.y=to.y-from.y,age.m=to.m-from.m,from.m>to.m&&(age.y=age.y-1,age.m=to.m-from.m+12),age.d=to.d-from.d,from.d>to.d&&(age.m=age.m-1,from.m==to.m&&(age.y=age.y-1,age.m=age.m+12),age.d=to.d-from.d+daysInMonths[parseInt(from.m)]),{days:age.d,months:age.m,years:age.y}},convertToUnits:function(minutes){var allUnits={Years:525600,Months:43200,Weeks:10080,Days:1440,Hours:60,Minutes:1},durationRepresentation=function(value,unitName,unitValueInMinutes){return{value:value,unitName:unitName,unitValueInMinutes:unitValueInMinutes,allUnits:allUnits}};for(var unitName in allUnits){var unitValueInMinutes=allUnits[unitName];if((minutes||0!==minutes)&&minutes>=unitValueInMinutes&&minutes%unitValueInMinutes===0)return durationRepresentation(minutes/unitValueInMinutes,unitName,unitValueInMinutes)}return durationRepresentation(void 0,void 0,void 0)},getEndDateFromDuration:function(dateFrom,value,unit){dateFrom=this.parse(dateFrom);var from={h:dateFrom.getHours(),d:dateFrom.getDate(),m:dateFrom.getMonth(),y:dateFrom.getFullYear()},to=new Date(from.y,from.m,from.d,from.h);return"Months"===unit?to.setMonth(from.m+value):"Weeks"===unit?to.setDate(from.d+7*value):"Days"===unit?to.setDate(from.d+value):"Hours"===unit&&to.setHours(from.h+value),to},parseLongDateToServerFormat:function(longDate){return longDate?moment(longDate).format("YYYY-MM-DDTHH:mm:ss.SSS"):null},parseServerDateToDate:function(longDate){return longDate?moment(longDate,"YYYY-MM-DDTHH:mm:ss.SSSZZ").toDate():null},getDateTimeInSpecifiedFormat:function(date,format){return date?moment(date).format(format):null},getISOString:function(date){return date?moment(date).toDate().toISOString():null},isBeforeTime:function(time,otherTime){return moment(time,"hh:mm a").format("YYYY-MM-DD")},getWeekStartDate:function(date,startOfWeek){var daysToBeSubtracted=this.subtractISOWeekDays(date,startOfWeek);return moment(date).subtract(daysToBeSubtracted,"days").toDate()},getWeekEndDate:function(weekStartDate){return moment(weekStartDate).add(6,"days").toDate()}},Bahmni.Common.Util.DateTimeFormatter={getDateWithoutTime:function(datetime){return datetime?moment(datetime).format("YYYY-MM-DD"):null}},Bahmni.Common.Util.ArrayUtil={chunk:function(array,chunkSize){for(var chunks=[],i=0;i<array.length;i+=chunkSize)chunks.push(array.slice(i,i+chunkSize));return chunks},groupByPreservingOrder:function(records,groupingFunction,keyName,valueName){var groups=[];return records.forEach(function(record){var recordKey=groupingFunction(record),existingGroup=_.find(groups,function(group){return group[keyName]===recordKey});if(existingGroup)existingGroup[valueName].push(record);else{var newGroup={};newGroup[keyName]=recordKey,newGroup[valueName]=[record],groups.push(newGroup)}}),groups}},String.prototype.format=function(){for(var content=this,i=0;i<arguments.length;i++){var replacement="{"+i+"}";content=content.replace(replacement,arguments[i])}return content},String.prototype.toValidId=function(){var content=this;return content.replace(/\s/g,"-")},Modernizr.addTest("ios",function(){return!!navigator.userAgent.match(/(iPad|iPhone|iPod)/i)}),Modernizr.addTest("windowOS",function(){return navigator.appVersion.indexOf("Win")!=-1});var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Models=Bahmni.Common.Models||{},angular.module("bahmni.common.models",[]),Bahmni.Common.VisitControl=function(visitTypes,defaultVisitTypeName,encounterService,$translate,visitService){var self=this;self.visitTypes=visitTypes,self.defaultVisitTypeName=defaultVisitTypeName,self.defaultVisitType=visitTypes.filter(function(visitType){return visitType.name===defaultVisitTypeName})[0],self.startButtonText=function(visitType){return $translate.instant("REGISTRATION_START_VISIT",{visitType:visitType.name})},self.startVisit=function(visitType){self.onStartVisit(),self.selectedVisitType=visitType},self.createVisitOnly=function(patientUuid,visitLocationUuid){var visitType=self.selectedVisitType||self.defaultVisitType,visitDetails={patient:patientUuid,visitType:visitType.uuid,location:visitLocationUuid};return visitService.createVisit(visitDetails)}},Bahmni.Common.VisitSummary=function(visitSummary){angular.extend(this,visitSummary),this.isAdmitted=function(){return!(!this.admissionDetails||!this.admissionDetails.uuid)},this.isDischarged=function(){return!(!this.dischargeDetails||!this.dischargeDetails.uuid)},this.getAdmissionEncounterUuid=function(){return this.isAdmitted()?this.admissionDetails.uuid:void 0},this.getDischargeEncounterUuid=function(){return this.isDischarged()?this.dischargeDetails.uuid:void 0},this.hasBeenAdmitted=function(){return this.isAdmitted()&&!this.isDischarged()}},angular.module("bahmni.common.patient",[]),Bahmni.PatientMapper=function(patientConfig,$rootScope,$translate){this.patientConfig=patientConfig,this.map=function(openmrsPatient){var patient=this.mapBasic(openmrsPatient);return this.mapAttributes(patient,openmrsPatient.person.attributes),patient},this.mapBasic=function(openmrsPatient){var patient={};if(patient.uuid=openmrsPatient.uuid,patient.givenName=openmrsPatient.person.preferredName.givenName,patient.familyName=null===openmrsPatient.person.preferredName.familyName?"":openmrsPatient.person.preferredName.familyName,patient.name=patient.givenName+" "+patient.familyName,patient.age=openmrsPatient.person.age,patient.ageText=calculateAge(Bahmni.Common.Util.DateUtil.parseServerDateToDate(openmrsPatient.person.birthdate)),patient.gender=openmrsPatient.person.gender,patient.genderText=mapGenderText(patient.gender),patient.address=mapAddress(openmrsPatient.person.preferredAddress),patient.birthdateEstimated=openmrsPatient.person.birthdateEstimated,patient.birthtime=Bahmni.Common.Util.DateUtil.parseServerDateToDate(openmrsPatient.person.birthtime),patient.bloodGroupText=getPatientBloodGroupText(openmrsPatient),openmrsPatient.identifiers){var primaryIdentifier=openmrsPatient.identifiers[0].primaryIdentifier;patient.identifier=primaryIdentifier?primaryIdentifier:openmrsPatient.identifiers[0].identifier}return openmrsPatient.person.birthdate&&(patient.birthdate=parseDate(openmrsPatient.person.birthdate)),openmrsPatient.person.personDateCreated&&(patient.registrationDate=parseDate(openmrsPatient.person.personDateCreated)),patient.image=Bahmni.Common.Constants.patientImageUrlByPatientUuid+openmrsPatient.uuid,patient},this.getPatientConfigByUuid=function(patientConfig,attributeUuid){return this.patientConfig.personAttributeTypes?patientConfig.personAttributeTypes.filter(function(item){return item.uuid===attributeUuid})[0]:{}},this.mapAttributes=function(patient,attributes){var self=this;this.patientConfig&&attributes.forEach(function(attribute){var x=self.getPatientConfigByUuid(patientConfig,attribute.attributeType.uuid);patient[x.name]={label:x.description,value:attribute.value,isDateField:checkIfDateField(x)}})};var calculateAge=function(birthDate){var DateUtil=Bahmni.Common.Util.DateUtil,age=DateUtil.diffInYearsMonthsDays(birthDate,DateUtil.now()),ageInString="";return age.years&&(ageInString+=age.years+" <span> "+$translate.instant("CLINICAL_YEARS_TRANSLATION_KEY")+" </span>"),age.months&&(ageInString+=age.months+"<span> "+$translate.instant("CLINICAL_MONTHS_TRANSLATION_KEY")+" </span>"),age.days&&(ageInString+=age.days+"<span> "+$translate.instant("CLINICAL_DAYS_TRANSLATION_KEY")+" </span>"),ageInString},mapAddress=function(preferredAddress){return preferredAddress?{address1:preferredAddress.address1,address2:preferredAddress.address2,address3:preferredAddress.address3,cityVillage:preferredAddress.cityVillage,countyDistrict:null===preferredAddress.countyDistrict?"":preferredAddress.countyDistrict,stateProvince:preferredAddress.stateProvince}:{}},parseDate=function(dateStr){return dateStr?Bahmni.Common.Util.DateUtil.parse(dateStr.substr(0,10)):dateStr},mapGenderText=function(genderChar){return null==genderChar?null:"<span>"+$rootScope.genderMap[angular.uppercase(genderChar)]+"</span>"},getPatientBloodGroupText=function(openmrsPatient){if(openmrsPatient.person.bloodGroup)return"<span>"+openmrsPatient.person.bloodGroup+"</span>";if(openmrsPatient.person.attributes&&openmrsPatient.person.attributes.length>0){var bloodGroup;if(_.forEach(openmrsPatient.person.attributes,function(attribute){"bloodGroup"==attribute.attributeType.display&&(bloodGroup=attribute.display)}),bloodGroup)return"<span>"+bloodGroup+"</span>"}},checkIfDateField=function(x){return x.format===Bahmni.Common.Constants.patientAttributeDateFieldFormat}},angular.module("bahmni.common.patient").service("patientService",["$http","sessionService",function($http,sessionService){this.getPatient=function(uuid,rep){rep||(rep="full");var patient=$http.get(Bahmni.Common.Constants.openmrsUrl+"/ws/rest/v1/patient/"+uuid,{method:"GET",params:{v:rep},withCredentials:!0});return patient},this.getRelationships=function(patientUuid){return $http.get(Bahmni.Common.Constants.openmrsUrl+"/ws/rest/v1/relationship",{method:"GET",params:{person:patientUuid,v:"full"},withCredentials:!0})},this.findPatients=function(params){return $http.get(Bahmni.Common.Constants.sqlUrl,{method:"GET",params:params,withCredentials:!0})},this.search=function(query,offset,identifier){return offset=offset||0,$http.get(Bahmni.Common.Constants.bahmniSearchUrl+"/patient",{method:"GET",params:{q:query,startIndex:offset,identifier:identifier,loginLocationUuid:sessionService.getLoginLocationUuid()},withCredentials:!0})},this.getPatientContext=function(patientUuid,programUuid,personAttributes,programAttributes,patientIdentifiers){return $http.get("/openmrs/ws/rest/v1/bahmnicore/patientcontext",{params:{patientUuid:patientUuid,programUuid:programUuid,personAttributes:personAttributes,programAttributes:programAttributes,patientIdentifiers:patientIdentifiers},withCredentials:!0})}}]),angular.module("bahmni.common.config").directive("showIfPrivilege",["$rootScope",function($rootScope){return{scope:{showIfPrivilege:"@"},link:function(scope,element){var privileges=scope.showIfPrivilege.split(","),requiredPrivilege=!1;if($rootScope.currentUser){var allTypesPrivileges=_.map($rootScope.currentUser.privileges,_.property("name")),intersect=_.intersectionWith(allTypesPrivileges,privileges,_.isEqual);requiredPrivilege=intersect.length>0}requiredPrivilege||element.hide()}}}]),angular.module("bahmni.common.patient").filter("gender",["$rootScope",function($rootScope){return function(genderChar){return null==genderChar?"Unknown":$rootScope.genderMap[angular.uppercase(genderChar)]}}]),angular.module("bahmni.common.patient").directive("patientSummary",function(){var link=function($scope){$scope.showPatientDetails=!1,$scope.togglePatientDetails=function(){$scope.showPatientDetails=!$scope.showPatientDetails},$scope.onImageClick=function(){$scope.onImageClickHandler&&$scope.onImageClickHandler()}};return{restrict:"E",templateUrl:"../common/patient/header/views/patientSummary.html",link:link,required:"patient",scope:{patient:"=",bedDetails:"=",onImageClickHandler:"&"}}}),angular.module("bahmni.common.patient").directive("fallbackSrc",function(){return{restrict:"A",link:function(scope,element,attrs){_.isEmpty(attrs.ngSrc)&&element.attr("src",attrs.fallbackSrc),element.bind("error",function(){element.attr("src",attrs.fallbackSrc)})}}});var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Domain=Bahmni.Common.Domain||{},Bahmni.Common.Domain.Helper=Bahmni.Common.Domain.Helper||{},angular.module("bahmni.common.domain",[]),Bahmni.Common.Domain.RetrospectiveEntry=function(){var self=this;Object.defineProperty(this,"encounterDate",{get:function(){return self._encounterDate},set:function(value){value&&(self._encounterDate=value)}})},Bahmni.Common.Domain.RetrospectiveEntry.createFrom=function(retrospectiveEncounterDateCookie){var obj=new Bahmni.Common.Domain.RetrospectiveEntry;return obj.encounterDate=retrospectiveEncounterDateCookie,obj},Bahmni.Common.Domain.Diagnosis=function(codedAnswer,order,certainty,existingObsUuid,freeTextAnswer,diagnosisDateTime,voided){var self=this;self.codedAnswer=codedAnswer,self.order=order,self.certainty=certainty,self.existingObs=existingObsUuid,self.freeTextAnswer=freeTextAnswer,self.diagnosisDateTime=diagnosisDateTime,self.diagnosisStatus=void 0,self.isNonCodedAnswer=!1,self.codedAnswer&&(self.conceptName=self.codedAnswer.name),self.voided=voided,self.firstDiagnosis=null,self.comments="",self.getDisplayName=function(){return self.freeTextAnswer?self.freeTextAnswer:self.codedAnswer.shortName||self.codedAnswer.name},self.isPrimary=function(){return"PRIMARY"==self.order},self.isSecondary=function(){return"SECONDARY"==self.order},self.isRuledOut=function(){return self.diagnosisStatus==$rootScope.diagnosisStatus},self.answerNotFilled=function(){return!self.codedAnswer.name},self.isValidAnswer=function(){return self.codedAnswer.name&&self.codedAnswer.uuid||self.codedAnswer.name&&!self.codedAnswer.uuid&&self.isNonCodedAnswer||self.answerNotFilled()},self.isValidOrder=function(){return self.isEmpty()||void 0!==self.order},self.isValidCertainty=function(){return self.isEmpty()||void 0!==self.certainty},self.isEmpty=function(){return void 0===self.getDisplayName()||0===self.getDisplayName().length},self.diagnosisStatusValue=null,self.diagnosisStatusConcept=null,Object.defineProperty(this,"diagnosisStatus",{get:function(){return this.diagnosisStatusValue},set:function(newStatus){newStatus?(this.diagnosisStatusValue=newStatus,this.diagnosisStatusConcept={name:Bahmni.Common.Constants.ruledOutdiagnosisStatus}):(this.diagnosisStatusValue=null,this.diagnosisStatusConcept=null)}}),self.clearCodedAnswerUuid=function(){self.codedAnswer.uuid=void 0},self.setAsNonCodedAnswer=function(){self.isNonCodedAnswer=!self.isNonCodedAnswer}},angular.module("bahmni.common.domain").service("retrospectiveEntryService",["$rootScope","$bahmniCookieStore",function($rootScope,$bahmniCookieStore){var retrospectiveEntryService=this,dateUtil=Bahmni.Common.Util.DateUtil;this.getRetrospectiveEntry=function(){return $rootScope.retrospectiveEntry},this.isRetrospectiveMode=function(){return!_.isEmpty(retrospectiveEntryService.getRetrospectiveEntry())},this.getRetrospectiveDate=function(){return $rootScope.retrospectiveEntry&&$rootScope.retrospectiveEntry.encounterDate},this.initializeRetrospectiveEntry=function(){var retrospectiveEncounterDateCookie=$bahmniCookieStore.get(Bahmni.Common.Constants.retrospectiveEntryEncounterDateCookieName);retrospectiveEncounterDateCookie&&($rootScope.retrospectiveEntry=Bahmni.Common.Domain.RetrospectiveEntry.createFrom(dateUtil.getDate(retrospectiveEncounterDateCookie)))},this.resetRetrospectiveEntry=function(date){$bahmniCookieStore.remove(Bahmni.Common.Constants.retrospectiveEntryEncounterDateCookieName,{path:"/",expires:1}),$rootScope.retrospectiveEntry=void 0,date&&!dateUtil.isSameDate(date,dateUtil.today())&&($rootScope.retrospectiveEntry=Bahmni.Common.Domain.RetrospectiveEntry.createFrom(dateUtil.getDate(date)),$bahmniCookieStore.put(Bahmni.Common.Constants.retrospectiveEntryEncounterDateCookieName,date,{path:"/",expires:1}))}}]),angular.module("bahmni.common.domain").service("diagnosisService",["$http","$rootScope",function($http,$rootScope){var self=this;this.getAllFor=function(searchTerm,locale){var url=Bahmni.Common.Constants.emrapiConceptUrl,parameters={term:searchTerm,limit:20};return locale&&(parameters.locale=locale),$http.get(url,{params:parameters})},this.getDiagnoses=function(patientUuid,visitUuid){var url=Bahmni.Common.Constants.bahmniDiagnosisUrl;return $http.get(url,{params:{patientUuid:patientUuid,visitUuid:visitUuid}})},this.deleteDiagnosis=function(obsUuid){var url=Bahmni.Common.Constants.bahmniDeleteDiagnosisUrl;return $http.get(url,{params:{obsUuid:obsUuid}})},this.getDiagnosisConceptSet=function(){return $http.get(Bahmni.Common.Constants.conceptUrl,{method:"GET",params:{v:"custom:(uuid,name,setMembers)",code:Bahmni.Common.Constants.diagnosisConceptSet,source:Bahmni.Common.Constants.emrapiConceptMappingSource},withCredentials:!0})},this.getPastAndCurrentDiagnoses=function(patientUuid,encounterUuid){return self.getDiagnoses(patientUuid).then(function(response){var diagnosisMapper=new Bahmni.DiagnosisMapper($rootScope.diagnosisStatus),allDiagnoses=diagnosisMapper.mapDiagnoses(response.data),pastDiagnoses=diagnosisMapper.mapPastDiagnosis(allDiagnoses,encounterUuid),savedDiagnosesFromCurrentEncounter=diagnosisMapper.mapSavedDiagnosesFromCurrentEncounter(allDiagnoses,encounterUuid);return{pastDiagnoses:pastDiagnoses,
savedDiagnosesFromCurrentEncounter:savedDiagnosesFromCurrentEncounter}})},this.populateDiagnosisInformation=function(patientUuid,consultation){return this.getPastAndCurrentDiagnoses(patientUuid,consultation.encounterUuid).then(function(diagnosis){return consultation.pastDiagnoses=diagnosis.pastDiagnoses,consultation.savedDiagnosesFromCurrentEncounter=diagnosis.savedDiagnosesFromCurrentEncounter,consultation})}}]),angular.module("bahmni.common.domain").service("bedService",["$http","$rootScope",function($http,$rootScope){var mapBedDetails=function(response){var results=response.data.results;if(!_.isEmpty(results)){var bed=_.first(results);return{wardName:bed.physicalLocation.parentLocation.display,wardUuid:bed.physicalLocation.parentLocation.uuid,physicalLocationName:bed.physicalLocation.name,bedNumber:bed.bedNumber,bedId:bed.bedId}}};this.setBedDetailsForPatientOnRootScope=function(uuid){var promise=this.getAssignedBedForPatient(uuid);return promise.then(function(bedDetails){$rootScope.bedDetails=bedDetails}),promise},this.getAssignedBedForPatient=function(patientUuid,visitUuid){var params={patientUuid:patientUuid,v:"full"};return visitUuid&&(params.visitUuid=visitUuid,params.s="bedDetailsFromVisit"),$http.get(Bahmni.Common.Constants.bedFromVisit,{method:"GET",params:params,withCredentials:!0}).then(mapBedDetails)},this.assignBed=function(bedId,patientUuid,encounterUuid){var patientJson={patientUuid:patientUuid,encounterUuid:encounterUuid};return $http.post(Bahmni.Common.Constants.bedFromVisit+"/"+bedId,patientJson,{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.getBedInfo=function(bedId){return $http.get(Bahmni.Common.Constants.bedFromVisit+"/"+bedId+"?v=custom:(bedId,bedNumber,patients:(uuid,person:(age,personName:(givenName,familyName),gender),identifiers:(uuid,identifier),),physicalLocation:(name))",{withCredentials:!0})},this.getCompleteBedDetailsByBedId=function(bedId){return $http.get(Bahmni.Common.Constants.bedFromVisit+"/"+bedId,{withCredentials:!0})}}]),angular.module("bahmni.common.domain").factory("configurationService",["$http","$q",function($http,$q){var configurationFunctions={};configurationFunctions.encounterConfig=function(){return $http.get(Bahmni.Common.Constants.encounterConfigurationUrl,{params:{callerContext:"REGISTRATION_CONCEPTS"},withCredentials:!0})},configurationFunctions.patientConfig=function(){var patientConfig=$http.get(Bahmni.Common.Constants.patientConfigurationUrl,{withCredentials:!0});return patientConfig},configurationFunctions.patientAttributesConfig=function(){return $http.get(Bahmni.Common.Constants.personAttributeTypeUrl,{params:{v:"custom:(uuid,name,sortWeight,description,format,concept)"},withCredentials:!0})},configurationFunctions.dosageFrequencyConfig=function(){var dosageFrequencyConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.dosageFrequencyConceptName},withCredentials:!0});return dosageFrequencyConfig},configurationFunctions.dosageInstructionConfig=function(){var dosageInstructionConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.dosageInstructionConceptName},withCredentials:!0});return dosageInstructionConfig},configurationFunctions.stoppedOrderReasonConfig=function(){var stoppedOrderReasonConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.stoppedOrderReasonConceptName},withCredentials:!0});return stoppedOrderReasonConfig},configurationFunctions.consultationNoteConfig=function(){var consultationNoteConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.consultationNoteConceptName},withCredentials:!0});return consultationNoteConfig},configurationFunctions.radiologyObservationConfig=function(){var radiologyObservationConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name)",name:Bahmni.Common.Constants.radiologyResultConceptName},withCredentials:!0});return radiologyObservationConfig},configurationFunctions.labOrderNotesConfig=function(){var labOrderNotesConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name)",name:Bahmni.Common.Constants.labOrderNotesConcept},withCredentials:!0});return labOrderNotesConfig},configurationFunctions.defaultEncounterType=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{params:{property:"bahmni.encounterType.default"},withCredentials:!0,transformResponse:[function(data){return data}]})},configurationFunctions.radiologyImpressionConfig=function(){var radiologyImpressionConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name)",name:Bahmni.Common.Constants.impressionConcept},withCredentials:!0});return radiologyImpressionConfig},configurationFunctions.addressLevels=function(){return $http.get(Bahmni.Common.Constants.openmrsUrl+"/module/addresshierarchy/ajax/getOrderedAddressHierarchyLevels.form",{withCredentials:!0})},configurationFunctions.allTestsAndPanelsConcept=function(){var allTestsAndPanelsConcept=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name:(uuid,name),setMembers:(uuid,name:(uuid,name)))",name:Bahmni.Common.Constants.allTestsAndPanelsConceptName},withCredentials:!0});return allTestsAndPanelsConcept},configurationFunctions.identifierTypesConfig=function(){return $http.get(Bahmni.Common.Constants.idgenConfigurationURL,{withCredentials:!0})},configurationFunctions.genderMap=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{method:"GET",params:{property:"mrs.genders"},withCredentials:!0})},configurationFunctions.relationshipTypeMap=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{method:"GET",params:{property:"bahmni.relationshipTypeMap"},withCredentials:!0})},configurationFunctions.relationshipTypeConfig=function(){return $http.get(Bahmni.Common.Constants.relationshipTypesUrl,{withCredentials:!0,params:{v:"custom:(aIsToB,bIsToA,uuid)"}})},configurationFunctions.loginLocationToVisitTypeMapping=function(){var url=Bahmni.Common.Constants.entityMappingUrl;return $http.get(url,{params:{mappingType:"loginlocation_visittype",s:"byEntityAndMappingType"}})},configurationFunctions.enableAuditLog=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{method:"GET",params:{property:"bahmni.enableAuditLog"},withCredentials:!0})};var existingPromises={},configurations={},getConfigurations=function(configurationNames){var configurationsPromiseDefer=$q.defer(),promises=[];return configurationNames.forEach(function(configurationName){existingPromises[configurationName]||(existingPromises[configurationName]=configurationFunctions[configurationName]().then(function(response){configurations[configurationName]=response.data}),promises.push(existingPromises[configurationName]))}),$q.all(promises).then(function(){configurationsPromiseDefer.resolve(configurations)}),configurationsPromiseDefer.promise};return{getConfigurations:getConfigurations}}]),angular.module("bahmni.common.domain").factory("dispositionService",["$http","$rootScope",function($http,$rootScope){var getDispositionActions=function(){return $http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl+"&name="+Bahmni.Common.Constants.dispositionConcept+"&v=custom:(uuid,name,answers:(uuid,name,mappings))",{cache:!0})},getDispositionNoteConcept=function(){return $http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl+"&name="+Bahmni.Common.Constants.dispositionNoteConcept+"&v=custom:(uuid,name:(name))",{cache:!0})},getDispositionByVisit=function(visitUuid){return $http.get(Bahmni.Common.Constants.bahmniDispositionByVisitUrl,{params:{visitUuid:visitUuid,locale:$rootScope.currentUser.userProperties.defaultLocale}})},getDispositionByPatient=function(patientUuid,numberOfVisits){return $http.get(Bahmni.Common.Constants.bahmniDispositionByPatientUrl,{params:{patientUuid:patientUuid,numberOfVisits:numberOfVisits,locale:$rootScope.currentUser.userProperties.defaultLocale}})};return{getDispositionActions:getDispositionActions,getDispositionNoteConcept:getDispositionNoteConcept,getDispositionByVisit:getDispositionByVisit,getDispositionByPatient:getDispositionByPatient}}]),angular.module("bahmni.common.domain").service("visitService",["$http",function($http){this.getVisit=function(uuid,params){var parameters=params?params:"custom:(uuid,visitId,visitType,patient,encounters:(uuid,encounterType,voided,orders:(uuid,orderType,voided,concept:(uuid,set,name),),obs:(uuid,value,concept,obsDatetime,groupMembers:(uuid,concept:(uuid,name),obsDatetime,value:(uuid,name),groupMembers:(uuid,concept:(uuid,name),value:(uuid,name),groupMembers:(uuid,concept:(uuid,name),value:(uuid,name)))))))";return $http.get(Bahmni.Common.Constants.visitUrl+"/"+uuid,{params:{v:parameters}})},this.endVisit=function(visitUuid){return $http.post(Bahmni.Common.Constants.endVisitUrl+"?visitUuid="+visitUuid,{withCredentials:!0})},this.endVisitAndCreateEncounter=function(visitUuid,bahmniEncounterTransaction){return $http.post(Bahmni.Common.Constants.endVisitAndCreateEncounterUrl+"?visitUuid="+visitUuid,bahmniEncounterTransaction,{withCredentials:!0})},this.updateVisit=function(visitUuid,attributes){return $http.post(Bahmni.Common.Constants.visitUrl+"/"+visitUuid,attributes,{withCredentials:!0})},this.createVisit=function(visitDetails){return $http.post(Bahmni.Common.Constants.visitUrl,visitDetails,{withCredentials:!0})},this.getVisitSummary=function(visitUuid){return $http.get(Bahmni.Common.Constants.visitSummaryUrl,{params:{visitUuid:visitUuid},withCredentials:!0})},this.search=function(parameters){return $http.get(Bahmni.Common.Constants.visitUrl,{params:parameters,withCredentials:!0})},this.getVisitType=function(){return $http.get(Bahmni.Common.Constants.visitTypeUrl,{withCredentials:!0})}}]),angular.module("bahmni.common.domain").service("encounterService",["$http","$q","$rootScope","configurations","$bahmniCookieStore",function($http,$q,$rootScope,configurations,$bahmniCookieStore){function isObsConceptClassVideoOrImage(obs){return"Video"===obs.concept.conceptClass||"Image"===obs.concept.conceptClass}this.buildEncounter=function(encounter){encounter.observations=encounter.observations||[],encounter.observations.forEach(function(obs){stripExtraConceptInfo(obs)});var bacterilogyMembers=getBacteriologyGroupMembers(encounter);bacterilogyMembers=bacterilogyMembers.reduce(function(mem1,mem2){return mem1.concat(mem2)},[]),bacterilogyMembers.forEach(function(mem){deleteIfImageOrVideoObsIsVoided(mem)}),encounter.providers=encounter.providers||[];var providerData=$bahmniCookieStore.get(Bahmni.Common.Constants.grantProviderAccessDataCookieName);return _.isEmpty(encounter.providers)&&(providerData&&providerData.uuid?encounter.providers.push({uuid:providerData.uuid}):$rootScope.currentProvider&&$rootScope.currentProvider.uuid&&encounter.providers.push({uuid:$rootScope.currentProvider.uuid})),encounter};var getBacteriologyGroupMembers=function(encounter){var addBacteriologyMember=function(bacteriologyGroupMembers,member){return bacteriologyGroupMembers=member.groupMembers.length?bacteriologyGroupMembers.concat(member.groupMembers):bacteriologyGroupMembers.concat(member)};return encounter.extensions&&encounter.extensions.mdrtbSpecimen?encounter.extensions.mdrtbSpecimen.map(function(observation){var bacteriologyGroupMembers=[];return observation.sample.additionalAttributes&&observation.sample.additionalAttributes.groupMembers.forEach(function(member){bacteriologyGroupMembers=addBacteriologyMember(bacteriologyGroupMembers,member)}),observation.report.results&&observation.report.results.groupMembers.forEach(function(member){bacteriologyGroupMembers=addBacteriologyMember(bacteriologyGroupMembers,member)}),bacteriologyGroupMembers}):[]},getDefaultEncounterType=function(){var url=Bahmni.Common.Constants.encounterTypeUrl;return $http.get(url+"/"+configurations.defaultEncounterType()).then(function(response){return response.data})},getEncounterTypeBasedOnLoginLocation=function(loginLocationUuid){return $http.get(Bahmni.Common.Constants.entityMappingUrl,{params:{entityUuid:loginLocationUuid,mappingType:"location_encountertype",s:"byEntityAndMappingType"},withCredentials:!0})},getEncounterTypeBasedOnProgramUuid=function(programUuid){return $http.get(Bahmni.Common.Constants.entityMappingUrl,{params:{entityUuid:programUuid,mappingType:"program_encountertype",s:"byEntityAndMappingType"},withCredentials:!0})},getDefaultEncounterTypeIfMappingNotFound=function(entityMappings){var encounterType=entityMappings.data.results[0]&&entityMappings.data.results[0].mappings[0];return encounterType||(encounterType=getDefaultEncounterType()),encounterType};this.getEncounterType=function(programUuid,loginLocationUuid){return programUuid?getEncounterTypeBasedOnProgramUuid(programUuid).then(function(response){return getDefaultEncounterTypeIfMappingNotFound(response)}):loginLocationUuid?getEncounterTypeBasedOnLoginLocation(loginLocationUuid).then(function(response){return getDefaultEncounterTypeIfMappingNotFound(response)}):getDefaultEncounterType()},this.create=function(encounter){return encounter=this.buildEncounter(encounter),$http.post(Bahmni.Common.Constants.bahmniEncounterUrl,encounter,{withCredentials:!0})},this.delete=function(encounterUuid,reason){return $http.delete(Bahmni.Common.Constants.bahmniEncounterUrl+"/"+encounterUuid,{params:{reason:reason}})};var deleteIfImageOrVideoObsIsVoided=function(obs){if(obs.voided&&obs.groupMembers&&!obs.groupMembers.length&&obs.value&&isObsConceptClassVideoOrImage(obs)){var url=Bahmni.Common.Constants.RESTWS_V1+"/bahmnicore/visitDocument?filename="+obs.value;$http.delete(url,{withCredentials:!0})}},stripExtraConceptInfo=function(obs){deleteIfImageOrVideoObsIsVoided(obs),obs.concept={uuid:obs.concept.uuid,name:obs.concept.name,dataType:obs.concept.dataType},obs.groupMembers=obs.groupMembers||[],obs.groupMembers.forEach(function(groupMember){stripExtraConceptInfo(groupMember)})},searchWithoutEncounterDate=function(visitUuid){return $http.post(Bahmni.Common.Constants.bahmniEncounterUrl+"/find",{visitUuids:[visitUuid],includeAll:Bahmni.Common.Constants.includeAllObservations},{withCredentials:!0})};this.search=function(visitUuid,encounterDate){return encounterDate?$http.get(Bahmni.Common.Constants.emrEncounterUrl,{params:{visitUuid:visitUuid,encounterDate:encounterDate,includeAll:Bahmni.Common.Constants.includeAllObservations},withCredentials:!0}):searchWithoutEncounterDate(visitUuid)},this.find=function(params){return $http.post(Bahmni.Common.Constants.bahmniEncounterUrl+"/find",params,{withCredentials:!0})},this.findByEncounterUuid=function(encounterUuid,params){return params=params||{includeAll:!0},$http.get(Bahmni.Common.Constants.bahmniEncounterUrl+"/"+encounterUuid,{params:params,withCredentials:!0})},this.getEncountersForEncounterType=function(patientUuid,encounterTypeUuid){return $http.get(Bahmni.Common.Constants.encounterUrl,{params:{patient:patientUuid,encounterType:encounterTypeUuid,v:"custom:(uuid,provider,visit:(uuid,startDatetime,stopDatetime),obs:(uuid,concept:(uuid,name),groupMembers:(id,uuid,obsDatetime,value,comment)))"},withCredentials:!0})},this.getDigitized=function(patientUuid){var patientDocumentEncounterTypeUuid=configurations.encounterConfig().getPatientDocumentEncounterTypeUuid();return $http.get(Bahmni.Common.Constants.encounterUrl,{params:{patient:patientUuid,encounterType:patientDocumentEncounterTypeUuid,v:"custom:(uuid,obs:(uuid))"},withCredentials:!0})},this.discharge=function(encounterData){var encounter=this.buildEncounter(encounterData);return $http.post(Bahmni.Common.Constants.dischargeUrl,encounter,{withCredentials:!0})}}]),angular.module("bahmni.common.domain").service("observationsService",["$http",function($http){this.fetch=function(patientUuid,conceptNames,scope,numberOfVisits,visitUuid,obsIgnoreList,filterObsWithOrders,patientProgramUuid){var params={concept:conceptNames};return obsIgnoreList&&(params.obsIgnoreList=obsIgnoreList),null!=filterObsWithOrders&&(params.filterObsWithOrders=filterObsWithOrders),visitUuid?(params.visitUuid=visitUuid,params.scope=scope):(params.patientUuid=patientUuid,params.numberOfVisits=numberOfVisits,params.scope=scope,params.patientProgramUuid=patientProgramUuid),$http.get(Bahmni.Common.Constants.observationsUrl,{params:params,withCredentials:!0})},this.getByUuid=function(observationUuid){return $http.get(Bahmni.Common.Constants.observationsUrl,{params:{observationUuid:observationUuid},withCredentials:!0})},this.getRevisedObsByUuid=function(observationUuid){return $http.get(Bahmni.Common.Constants.observationsUrl,{params:{observationUuid:observationUuid,revision:"latest"},withCredentials:!0})},this.fetchForEncounter=function(encounterUuid,conceptNames){return $http.get(Bahmni.Common.Constants.observationsUrl,{params:{encounterUuid:encounterUuid,concept:conceptNames},withCredentials:!0})},this.fetchForPatientProgram=function(patientProgramUuid,conceptNames,scope,obsIgnoreList){return $http.get(Bahmni.Common.Constants.observationsUrl,{params:{patientProgramUuid:patientProgramUuid,concept:conceptNames,scope:scope,obsIgnoreList:obsIgnoreList},withCredentials:!0})},this.getObsRelationship=function(targetObsUuid){return $http.get(Bahmni.Common.Constants.obsRelationshipUrl,{params:{targetObsUuid:targetObsUuid},withCredentials:!0})},this.getObsInFlowSheet=function(patientUuid,conceptSet,groupByConcept,orderByConcept,conceptNames,numberOfVisits,initialCount,latestCount,groovyExtension,startDate,endDate,patientProgramUuid,formNames){var params={patientUuid:patientUuid,conceptSet:conceptSet,groupByConcept:groupByConcept,orderByConcept:orderByConcept,conceptNames:conceptNames,numberOfVisits:numberOfVisits,initialCount:initialCount,latestCount:latestCount,name:groovyExtension,startDate:Bahmni.Common.Util.DateUtil.parseLongDateToServerFormat(startDate),endDate:Bahmni.Common.Util.DateUtil.parseLongDateToServerFormat(endDate),enrollment:patientProgramUuid,formNames:formNames};return $http.get(Bahmni.Common.Constants.observationsUrl+"/flowSheet",{params:params,withCredentials:!0})}}]),angular.module("bahmni.common.domain").factory("locationService",["$http","$bahmniCookieStore",function($http,$bahmniCookieStore){var getAllByTag=function(tags,operator){return $http.get(Bahmni.Common.Constants.locationUrl,{params:{s:"byTags",tags:tags||"",v:"default",operator:operator||"ALL"},cache:!0})},getByUuid=function(locationUuid){return $http.get(Bahmni.Common.Constants.locationUrl+"/"+locationUuid,{cache:!0}).then(function(response){return response.data})},getLoggedInLocation=function(){var cookie=$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName);return getByUuid(cookie.uuid)},getVisitLocation=function(locationUuid){return $http.get(Bahmni.Common.Constants.bahmniVisitLocationUrl+"/"+locationUuid,{headers:{Accept:"application/json"}})};return{getAllByTag:getAllByTag,getLoggedInLocation:getLoggedInLocation,getByUuid:getByUuid,getVisitLocation:getVisitLocation}}]);var EncounterConfig=function(){function EncounterConfig(encounterTypes){this.encounterTypes=encounterTypes}return EncounterConfig.prototype={getConsultationEncounterTypeUuid:function(){return this.getEncounterTypeUuid("Consultation")},getAdmissionEncounterTypeUuid:function(){return this.getEncounterTypeUuid("ADMISSION")},getDischargeEncounterTypeUuid:function(){return this.getEncounterTypeUuid("DISCHARGE")},getTransferEncounterTypeUuid:function(){return this.getEncounterTypeUuid("TRANSFER")},getRadiologyEncounterTypeUuid:function(){return this.getEncounterTypeUuid("RADIOLOGY")},getPatientDocumentEncounterTypeUuid:function(){return this.getEncounterTypeUuid("Patient Document")},getValidationEncounterTypeUuid:function(){return this.getEncounterTypeUuid(Bahmni.Common.Constants.validationNotesEncounterType)},getEncounterTypeUuid:function(encounterTypeName){return this.encounterTypes[encounterTypeName]},getVisitTypes:function(){var visitTypesArray=[];for(var name in this.visitTypes)visitTypesArray.push({name:name,uuid:this.visitTypes[name]});return visitTypesArray},getEncounterTypes:function(){var encounterTypesArray=[];for(var name in this.encounterTypes)encounterTypesArray.push({name:name,uuid:this.encounterTypes[name]});return encounterTypesArray},getVisitTypeByUuid:function(uuid){var visitTypes=this.getVisitTypes();return visitTypes.filter(function(visitType){return visitType.uuid===uuid})[0]},getEncounterTypeByUuid:function(uuid){var encounterType=this.getEncounterTypes();return encounterType.filter(function(encounterType){return encounterType.uuid===uuid})[0]}},EncounterConfig}();Bahmni.Common.Domain.Helper.getHintForNumericConcept=function(concept){if(concept)return null!=concept.hiNormal&&null!=concept.lowNormal?"("+concept.lowNormal+" - "+concept.hiNormal+")":null!=concept.hiNormal&&null==concept.lowNormal?"(< "+concept.hiNormal+")":null==concept.hiNormal&&null!=concept.lowNormal?"(> "+concept.lowNormal+")":""},Bahmni.Common.Domain.ConceptMapper=function(){this.map=function(openMrsConcept){if(!openMrsConcept)return null;if(alreadyMappedConcept(openMrsConcept))return openMrsConcept;var openMrsDescription=openMrsConcept.descriptions?openMrsConcept.descriptions[0]:null,shortConceptName=_.find(openMrsConcept.names,{conceptNameType:"SHORT"});return{uuid:openMrsConcept.uuid,name:openMrsConcept.name.name,shortName:shortConceptName?shortConceptName.name:null,description:openMrsDescription?openMrsDescription.description:null,set:openMrsConcept.set,dataType:openMrsConcept.datatype?openMrsConcept.datatype.name:null,hiAbsolute:openMrsConcept.hiAbsolute,lowAbsolute:openMrsConcept.lowAbsolute,hiNormal:openMrsConcept.hiNormal,handler:openMrsConcept.handler,allowDecimal:openMrsConcept.allowDecimal,lowNormal:openMrsConcept.lowNormal,conceptClass:openMrsConcept.conceptClass?openMrsConcept.conceptClass.name:null,answers:openMrsConcept.answers,units:openMrsConcept.units,displayString:shortConceptName?shortConceptName.name:openMrsConcept.name.name,names:openMrsConcept.names}};var alreadyMappedConcept=function(concept){return!concept.name.name}},function(){var nameFor={Date:function(obs){return moment(obs.value).format("D-MMM-YYYY")},Datetime:function(obs){var date=Bahmni.Common.Util.DateUtil.parseDatetime(obs.value);return null!=date?Bahmni.Common.Util.DateUtil.formatDateWithTime(date):""},Boolean:function(obs){return obs.value===!0?"Yes":obs.value===!1?"No":obs.value},Coded:function(obs){return obs.value.shortName||obs.value.name||obs.value},Object:function(obs){return nameFor.Coded(obs)},MultiSelect:function(obs){return obs.getValues().join(", ")},Default:function(obs){return obs.value}};Bahmni.Common.Domain.ObservationValueMapper={getNameFor:nameFor,map:function(obs){var type=obs.concept&&obs.concept.dataType||obs.type;return type in nameFor||(type="object"==typeof obs.value&&"Object"||obs.isMultiSelect&&"MultiSelect"||"Default"),nameFor[type](obs)}}}(),Bahmni.DiagnosisMapper=function(diagnosisStatus){var self=this,mapDiagnosis=function(diagnosis){diagnosis.codedAnswer||(diagnosis.codedAnswer={name:void 0,uuid:void 0});var mappedDiagnosis=angular.extend(new Bahmni.Common.Domain.Diagnosis,diagnosis);return mappedDiagnosis.firstDiagnosis&&(mappedDiagnosis.firstDiagnosis=mapDiagnosis(mappedDiagnosis.firstDiagnosis)),mappedDiagnosis.latestDiagnosis&&(mappedDiagnosis.latestDiagnosis=mapDiagnosis(mappedDiagnosis.latestDiagnosis)),diagnosis.diagnosisStatusConcept&&Bahmni.Common.Constants.ruledOutdiagnosisStatus===diagnosis.diagnosisStatusConcept.name&&(mappedDiagnosis.diagnosisStatus=diagnosisStatus),mappedDiagnosis};self.mapDiagnosis=mapDiagnosis,self.mapDiagnoses=function(diagnoses){var mappedDiagnoses=[];return _.each(diagnoses,function(diagnosis){mappedDiagnoses.push(mapDiagnosis(diagnosis))}),mappedDiagnoses},self.mapPastDiagnosis=function(diagnoses,currentEncounterUuid){var pastDiagnosesResponse=[];return diagnoses.forEach(function(diagnosis){diagnosis.encounterUuid!==currentEncounterUuid&&(diagnosis.previousObs=diagnosis.existingObs,diagnosis.existingObs=null,diagnosis.inCurrentEncounter=void 0,pastDiagnosesResponse.push(diagnosis))}),pastDiagnosesResponse},self.mapSavedDiagnosesFromCurrentEncounter=function(diagnoses,currentEncounterUuid){var savedDiagnosesFromCurrentEncounter=[];return diagnoses.forEach(function(diagnosis){diagnosis.encounterUuid===currentEncounterUuid&&(diagnosis.inCurrentEncounter=!0,savedDiagnosesFromCurrentEncounter.push(diagnosis))}),savedDiagnosesFromCurrentEncounter}};var Bahmni=Bahmni||{};Bahmni.ConceptSet=Bahmni.ConceptSet||{},Bahmni.ConceptSet.FormConditions=Bahmni.ConceptSet.FormConditions||{},angular.module("bahmni.common.conceptSet",["bahmni.common.uiHelper","ui.select2","pasvaz.bindonce","ngSanitize","ngTagsInput"]),angular.module("bahmni.common.conceptSet").directive("buttonSelect",function(){return{restrict:"E",scope:{observation:"=",abnormalObs:"=?"},link:function(scope,element,attrs){attrs.dirtyCheckFlag&&(scope.hasDirtyFlag=!0)},controller:function($scope){$scope.isSet=function(answer){return $scope.observation.hasValueOf(answer)},$scope.select=function(answer){$scope.observation.toggleSelection(answer),$scope.$parent.observation&&"function"==typeof $scope.$parent.observation.onValueChanged&&$scope.$parent.observation.onValueChanged(),$scope.$parent.handleUpdate()},$scope.getAnswerDisplayName=function(answer){var shortName=answer.names?_.first(answer.names.filter(function(name){return"SHORT"===name.conceptNameType})):null;return shortName?shortName.name:answer.displayString}},templateUrl:"../common/concept-set/views/buttonSelect.html"}}),angular.module("bahmni.common.conceptSet").directive("stepper",function(){return{restrict:"E",require:"ngModel",replace:!0,scope:{ngModel:"=",obs:"=",ngClass:"=",focusMe:"="},template:'<div class="stepper clearfix"><button ng-click="decrement()" class="stepper__btn stepper__minus" ng-disabled="obs.disabled">-</button><input id="{{::obs.uniqueId}}" obs-constraints ng-model="ngModel" obs="::obs" ng-class="ngClass" focus-me="focusMe" type="text" class="stepper__field" ng-disabled="obs.disabled" /><button ng-click="increment()" class="stepper__btn stepper__plus" ng-disabled="obs.disabled">+</button></div> ',link:function(scope,element,attrs,ngModelController){function updateModel(offset){var currValue=0;isNaN(ngModelController.$viewValue)?null!=scope.obs.concept.lowNormal&&(currValue=scope.obs.concept.lowNormal-offset):currValue=parseInt(ngModelController.$viewValue),ngModelController.$setViewValue(currValue+offset)}ngModelController.$render=function(){},ngModelController.$formatters.push(function(value){return parseInt(value,10)}),ngModelController.$parsers.push(function(value){return parseInt(value,10)}),scope.increment=function(){if(null!=scope.obs.concept.hiNormal){var currValue=isNaN(ngModelController.$viewValue)?0:ngModelController.$viewValue;currValue<scope.obs.concept.hiNormal&&updateModel(1)}else updateModel(1)},scope.decrement=function(){if(null!=scope.obs.concept.lowNormal){var currValue=isNaN(ngModelController.$viewValue)?0:ngModelController.$viewValue;currValue>scope.obs.concept.lowNormal&&updateModel(-1)}else updateModel(-1)}}}}),angular.module("bahmni.common.conceptSet").directive("conceptSet",["contextChangeHandler","appService","observationsService","messagingService","conceptSetService","conceptSetUiConfigService","spinner",function(contextChangeHandler,appService,observationsService,messagingService,conceptSetService,conceptSetUiConfigService,spinner){var controller=function($scope){var conceptSetName=$scope.conceptSetName,ObservationUtil=Bahmni.Common.Obs.ObservationUtil,conceptSetUIConfig=conceptSetUiConfigService.getConfig(),observationMapper=new Bahmni.ConceptSet.ObservationMapper,validationHandler=$scope.validationHandler()||contextChangeHandler,id="#"+$scope.sectionId;$scope.atLeastOneValueIsSet=$scope.atLeastOneValueIsSet||!1,$scope.conceptSetRequired=!1,$scope.showTitleValue=$scope.showTitle(),$scope.numberOfVisits=conceptSetUIConfig[conceptSetName]&&conceptSetUIConfig[conceptSetName].numberOfVisits?conceptSetUIConfig[conceptSetName].numberOfVisits:null,$scope.hideAbnormalButton=conceptSetUIConfig[conceptSetName]&&conceptSetUIConfig[conceptSetName].hideAbnormalButton;var focusFirstObs=function(){if($scope.conceptSetFocused&&$scope.rootObservation.groupMembers&&$scope.rootObservation.groupMembers.length>0){var firstObs=_.find($scope.rootObservation.groupMembers,function(obs){return obs.isFormElement&&obs.isFormElement()});firstObs&&(firstObs.isFocused=!0)}},updateObservationsOnRootScope=function(){if($scope.rootObservation){for(var i=0;i<$scope.observations.length;i++)if($scope.observations[i].concept.uuid===$scope.rootObservation.concept.uuid)return void($scope.observations[i]=$scope.rootObservation);$scope.observations.push($scope.rootObservation)}},getObservationsOfCurrentTemplate=function(){return _.filter($scope.observations,function(observation){return _.toLower(observation.conceptSetName)===_.toLower($scope.rootObservation.concept.name)})},getDefaults=function(){var conceptSetUI=appService.getAppDescriptor().getConfigValue("conceptSetUI");if(conceptSetUI&&conceptSetUI.defaults)return conceptSetUI.defaults||{}},getCodedAnswerWithDefaultAnswerString=function(defaults,groupMember){var defaultCodedAnswer,possibleAnswers=groupMember.possibleAnswers,defaultAnswer=defaults[groupMember.concept.name];return defaultAnswer instanceof Array?(defaultCodedAnswer=[],_.each(defaultAnswer,function(answer){defaultCodedAnswer.push(_.find(possibleAnswers,{displayString:answer}))})):defaultCodedAnswer=_.find(possibleAnswers,{displayString:defaultAnswer}),defaultCodedAnswer},setDefaultsForGroupMembers=function(groupMembers,defaults){defaults&&_.each(groupMembers,function(groupMember){var conceptFullName=groupMember.concept.name,present=_.includes(_.keys(defaults),conceptFullName);present&&void 0==groupMember.value&&("Coded"==groupMember.concept.dataType?setDefaultsForCodedObservations(groupMember,defaults):groupMember.value=defaults[conceptFullName]),groupMember.groupMembers&&groupMember.groupMembers.length>0&&(setDefaultsForGroupMembers(groupMember.groupMembers,defaults),groupMember instanceof Bahmni.ConceptSet.ObservationNode&&defaults[groupMember.label]&&groupMember.abnormalObs&&void 0==groupMember.abnormalObs.value&&groupMember.onValueChanged(groupMember.value))})},setDefaultsForCodedObservations=function(observation,defaults){var defaultCodedAnswer=getCodedAnswerWithDefaultAnswerString(defaults,observation);observation.isMultiSelect?observation.hasValue()||_.each(defaultCodedAnswer,function(answer){observation.selectAnswer(answer)}):defaultCodedAnswer instanceof Array||(observation.value=defaultCodedAnswer)},getFlattenedObsValues=function(flattenedObs){return _.reduce(flattenedObs,function(flattenedObsValues,obs){if(void 0==flattenedObsValues[obs.concept.name+"|"+obs.uniqueId])if(obs.isMultiSelect){var selectedObsConceptNames=[];_.each(obs.selectedObs,function(observation){observation.voided||selectedObsConceptNames.push(observation.value.name),observation.voided||selectedObsConceptNames.push(observation.value.name)}),flattenedObsValues[obs.concept.name+"|"+obs.uniqueId]=selectedObsConceptNames}else if(obs.conceptUIConfig.multiSelect){var alreadyProcessedMultiSelect=[];_.each(_.keys(flattenedObsValues),function(eachObsKey){eachObsKey.split("|")[0]==obs.concept.name&&alreadyProcessedMultiSelect.push(eachObsKey)}),alreadyProcessedMultiSelect.length<2&&(flattenedObsValues[obs.concept.name+"|"+obs.uniqueId]=flattenedObsValues[obs.concept.name+"|undefined"])}else obs.value instanceof Object?flattenedObsValues[obs.concept.name+"|"+obs.uniqueId]=obs.value.name instanceof Object?obs.value.name.name:obs.value.name:flattenedObsValues[obs.concept.name+"|"+obs.uniqueId]=obs.value;
return flattenedObsValues},{})},clearFieldValuesOnDisabling=function(obs){if(obs.comment=void 0,obs.value||obs.isBoolean)obs.value=void 0;else if(obs.isMultiSelect)for(var key in obs.selectedObs)obs.selectedObs[key].voided||obs.toggleSelection(obs.selectedObs[key].value)},setObservationState=function(obsArray,disable,error,hide){_.isEmpty(obsArray)||_.each(obsArray,function(obs){obs.disabled=disable||hide,obs.error=error,obs.hide=hide,(hide||obs.disabled)&&clearFieldValuesOnDisabling(obs),obs.groupMembers&&_.each(obs.groupMembers,function(groupMember){groupMember&&setObservationState([groupMember],disable,error,hide)})})},processConditions=function(flattenedObs,fields,disable,error,hide){_.each(fields,function(field){var clonedObsInSameGroup,matchingObsArray=[];flattenedObs.forEach(function(obs){0!=clonedObsInSameGroup&&obs.concept.name==field?(matchingObsArray.push(obs),clonedObsInSameGroup=!0):clonedObsInSameGroup&&obs.concept.name!=field&&(clonedObsInSameGroup=!1)}),_.isEmpty(matchingObsArray)?messagingService.showMessage("error","No element found with name : "+field):setObservationState(matchingObsArray,disable,error,hide)})},runFormConditionForObs=function(enableCase,formName,formCondition,conceptName,flattenedObs){var conceptSetObsValues=getFlattenedObsValues(flattenedObs);_.each(_.keys(conceptSetObsValues),function(eachObsKey){if(eachObsKey.split("|")[0]==conceptName&&"undefined"!=eachObsKey.split("|")[1]){var valueMap=_.reduce(conceptSetObsValues,function(conceptSetValueMap,obsValue,conceptName){return conceptSetValueMap[conceptName.split("|")[0]]=obsValue,conceptSetValueMap},{}),conditions=formCondition(formName,valueMap,$scope.patient);_.isUndefined(conditions)||(conditions.error&&!_.isEmpty(conditions.error)?(messagingService.showMessage("error",conditions.error),processConditions(flattenedObs,[conceptName],!1,!0,!1)):enableCase&&processConditions(flattenedObs,[conceptName],!1,!1,!1),processConditions(flattenedObs,conditions.disable,!0),processConditions(flattenedObs,conditions.enable,!1),processConditions(flattenedObs,conditions.show,!1,void 0,!1),processConditions(flattenedObs,conditions.hide,!1,void 0,!0),_.each(conditions.enable,function(subConditionConceptName){var conditionFn=Bahmni.ConceptSet.FormConditions.rules&&Bahmni.ConceptSet.FormConditions.rules[subConditionConceptName];null!=conditionFn&&runFormConditionForObs(!0,formName,conditionFn,subConditionConceptName,flattenedObs)}),_.each(conditions.disable,function(subConditionConceptName){var conditionFn=Bahmni.ConceptSet.FormConditions.rules&&Bahmni.ConceptSet.FormConditions.rules[subConditionConceptName];null!=conditionFn&&_.each(flattenedObs,function(obs){obs.concept.name==subConditionConceptName&&runFormConditionForObs(!1,formName,conditionFn,subConditionConceptName,flattenedObs)})}),_.each(conditions.show,function(subConditionConceptName){var conditionFn=Bahmni.ConceptSet.FormConditions.rules&&Bahmni.ConceptSet.FormConditions.rules[subConditionConceptName];conditionFn&&runFormConditionForObs(!0,formName,conditionFn,subConditionConceptName,flattenedObs)}),_.each(conditions.hide,function(subConditionConceptName){var conditionFn=Bahmni.ConceptSet.FormConditions.rules&&Bahmni.ConceptSet.FormConditions.rules[subConditionConceptName];conditionFn&&_.each(flattenedObs,function(obs){obs.concept.name==subConditionConceptName&&runFormConditionForObs(!1,formName,conditionFn,subConditionConceptName,flattenedObs)})}))}})},updateFormConditions=function(observationsOfCurrentTemplate,rootObservation){Bahmni.ConceptSet.FormConditions.rules&&runFormConditionForAllObsRecursively(rootObservation.concept.name,rootObservation)},runFormConditionForAllObsRecursively=function(formName,rootObservation){_.each(rootObservation.groupMembers,function(observation){var conditionFn=Bahmni.ConceptSet.FormConditions.rules&&Bahmni.ConceptSet.FormConditions.rules[observation.concept.name];if(null!=conditionFn){var flattenedObs=ObservationUtil.flattenObsToArray([rootObservation]);runFormConditionForObs(!1,formName,conditionFn,observation.concept.name,flattenedObs)}observation.groupMembers&&observation.groupMembers.length>0&&runFormConditionForAllObsRecursively(formName,observation)})},addDummyImage=function(){_.each($scope.rootObservation.groupMembers,function(observation){addDummyImageObservationForSavedObs(observation,$scope.rootObservation)})},addDummyImageObservationForSavedObs=function(observation,rootObservation){if(_.each(observation.groupMembers,function(childObservation){addDummyImageObservationForSavedObs(childObservation,observation)}),"image"===observation.getControlType()&&observation.value&&rootObservation.groupMembers.indexOf(observation)===rootObservation.groupMembers.length-1)return void rootObservation.groupMembers.push(observation.cloneNew())},init=function(){return conceptSetService.getConcept({name:conceptSetName,v:"bahmni"}).then(function(response){if($scope.conceptSet=response.data.results[0],$scope.rootObservation=$scope.conceptSet?observationMapper.map($scope.observations,$scope.conceptSet,conceptSetUIConfig):null,$scope.rootObservation){$scope.rootObservation.conceptSetName=$scope.conceptSetName,focusFirstObs(),updateObservationsOnRootScope();var groupMembers=getObservationsOfCurrentTemplate()[0].groupMembers,defaults=getDefaults();addDummyImage(),setDefaultsForGroupMembers(groupMembers,defaults);var observationsOfCurrentTemplate=getObservationsOfCurrentTemplate();updateFormConditions(observationsOfCurrentTemplate,$scope.rootObservation)}else $scope.showEmptyConceptSetMessage=!0}).catch(function(error){messagingService.showMessage("error",error.message)})};spinner.forPromise(init(),id);var validateObservationTree=function(){if("undefined"==typeof $scope.rootObservation||null===$scope.rootObservation)return{allow:!0,errorMessage:null};$scope.atLeastOneValueIsSet=$scope.rootObservation&&$scope.rootObservation.atLeastOneValueSet(),$scope.conceptSetRequired=!$scope.required||$scope.required;var nodes=$scope.rootObservation&&findInvalidNodes($scope.rootObservation.groupMembers,$scope.rootObservation);return{allow:!nodes.status,errorMessage:nodes.message}},findInvalidNodes=function(members,parentNode){var errorMessage=null,status=members.some(function(childNode){if(childNode.voided)return!1;var groupMembers=childNode.groupMembers||[];for(var index in groupMembers){var information=groupMembers[index].groupMembers&&groupMembers[index].groupMembers.length?findInvalidNodes(groupMembers[index].groupMembers,groupMembers[index]):validateChildNode(groupMembers[index],childNode);if(information.status)return errorMessage=information.message,!0}return information=validateChildNode(childNode,parentNode),information.status?(errorMessage=information.message,!0):!childNode.isValid($scope.atLeastOneValueIsSet,$scope.conceptSetRequired)});return{message:errorMessage,status:status}},validateChildNode=function(childNode,parentNode){var errorMessage;if(childNode.possibleAnswers&&!childNode.possibleAnswers.length){if("function"==typeof childNode.isValueInAbsoluteRange&&!childNode.isValueInAbsoluteRange())return errorMessage="The value you entered (red field) is outside the range of allowable values for that record. Please check the value.",{message:errorMessage,status:!0};if(childNode.isNumeric()){if(!childNode.isValidNumeric())return errorMessage="Please enter Integer value, decimal value is not allowed",{message:errorMessage,status:!0};if(parentNode){if(!childNode.isValidNumericValue()||!parentNode.isValidNumericValue())return errorMessage="Please enter Numeric values",{message:errorMessage,status:!0}}else if(!childNode.isValidNumericValue())return errorMessage="Please enter Numeric values",{message:errorMessage,status:!0}}}return{status:!1}};validationHandler.add(validateObservationTree);var cleanUpListenerShowPrevious=$scope.$on("event:showPrevious"+conceptSetName,function(){return spinner.forPromise(observationsService.fetch($scope.patient.uuid,$scope.conceptSetName,null,$scope.numberOfVisits,null,!0),id).then(function(response){var recentObservations=ObservationUtil.flattenObsToArray(response.data),conceptSetObservation=$scope.observations.filter(function(observation){return observation.conceptSetName===$scope.conceptSetName});ObservationUtil.flattenObsToArray(conceptSetObservation).forEach(function(obs){var correspondingRecentObs=_.filter(recentObservations,function(recentObs){return obs.concept.uuid===recentObs.concept.uuid});null!=correspondingRecentObs&&correspondingRecentObs.length>0&&(correspondingRecentObs.sort(function(obs1,obs2){return new Date(obs2.encounterDateTime)-new Date(obs1.encounterDateTime)}),obs.previous=correspondingRecentObs.map(function(previousObs){return{value:Bahmni.Common.Domain.ObservationValueMapper.map(previousObs),date:previousObs.observationDateTime}}))})})}),deregisterAddMore=$scope.$root.$on("event:addMore",function(event,observation){updateFormConditions([observation],observation)}),deregisterObservationUpdated=$scope.$root.$on("event:observationUpdated-"+conceptSetName,function(event,conceptName,rootObservation){var formName=rootObservation.concept.name,formCondition=Bahmni.ConceptSet.FormConditions.rules&&Bahmni.ConceptSet.FormConditions.rules[conceptName];if(formCondition){var flattenedObs=ObservationUtil.flattenObsToArray([rootObservation]);runFormConditionForObs(!0,formName,formCondition,conceptName,flattenedObs)}});$scope.$on("$destroy",function(){deregisterObservationUpdated(),deregisterAddMore(),cleanUpListenerShowPrevious()})};return{restrict:"E",scope:{conceptSetName:"=",observations:"=?",required:"=?",showTitle:"&",validationHandler:"&",patient:"=",conceptSetFocused:"=?",collapseInnerSections:"=?",atLeastOneValueIsSet:"=?",sectionId:"="},templateUrl:"../common/concept-set/views/conceptSet.html",controller:controller}}]),angular.module("bahmni.common.conceptSet").directive("concept",["RecursionHelper","spinner","$filter","messagingService","$rootScope","$translate",function(RecursionHelper,spinner,$filter,messagingService,$rootScope,$translate){var link=function(scope){var hideAbnormalbuttonConfig=scope.observation&&scope.observation.conceptUIConfig&&scope.observation.conceptUIConfig.hideAbnormalButton;scope.now=moment().format("YYYY-MM-DD hh:mm:ss"),scope.showTitle=void 0===scope.showTitle||scope.showTitle,scope.hideAbnormalButton=void 0==hideAbnormalbuttonConfig?scope.hideAbnormalButton:hideAbnormalbuttonConfig,scope.cloneNew=function(observation,parentObservation){observation.showAddMoreButton=function(){return!1};var newObs=observation.cloneNew();newObs.scrollToElement=!0;var index=parentObservation.groupMembers.indexOf(observation);parentObservation.groupMembers.splice(index+1,0,newObs),messagingService.showMessage("info",$translate.instant("NEW_KEY")+" "+observation.label+" "+$translate.instant("SECTION_ADDED_KEY")),scope.$root.$broadcast("event:addMore",newObs)},scope.removeClonedObs=function(observation,parentObservation){observation.voided=!0;var lastObservationByLabel=_.findLast(parentObservation.groupMembers,function(groupMember){return groupMember.label===observation.label&&!groupMember.voided});lastObservationByLabel.showAddMoreButton=function(){return!0},observation.hidden=!0},scope.isClone=function(observation,parentObservation){if(parentObservation&&parentObservation.groupMembers){var index=parentObservation.groupMembers.indexOf(observation);return index>0&&parentObservation.groupMembers[index].label==parentObservation.groupMembers[index-1].label}return!1},scope.isRemoveValid=function(observation){return"image"!=observation.getControlType()||!observation.value},scope.getStringValue=function(observations){return observations.map(function(observation){return observation.value+" ("+$filter("bahmniDate")(observation.date)+")"}).join(", ")},scope.toggleSection=function(){scope.collapse=!scope.collapse},scope.isCollapsibleSet=function(){return 1==scope.showTitle},scope.hasPDFAsValue=function(){return scope.observation.value&&scope.observation.value.indexOf(".pdf")>0},scope.$watch("collapseInnerSections",function(){scope.collapse=scope.collapseInnerSections&&scope.collapseInnerSections.value}),scope.handleUpdate=function(){scope.$root.$broadcast("event:observationUpdated-"+scope.conceptSetName,scope.observation.concept.name,scope.rootObservation)},scope.update=function(value){scope.getBooleanResult(scope.observation.isObservationNode)?scope.observation.primaryObs.value=value:scope.getBooleanResult(scope.observation.isFormElement())&&(scope.observation.value=value),scope.handleUpdate()},scope.getBooleanResult=function(value){return!!value},scope.translatedLabel=function(observation){if(observation&&observation.concept){var currentLocale=$rootScope.currentUser.userProperties.defaultLocale,conceptNames=observation.concept.names?observation.concept.names:[],shortName=conceptNames.find(function(cn){return cn.locale===currentLocale&&"SHORT"===cn.conceptNameType});if(shortName)return shortName.name;var fsName=conceptNames.find(function(cn){return cn.locale===currentLocale&&"FULLY_SPECIFIED"===cn.conceptNameType});return fsName?fsName.name:observation.concept.shortName||observation.concept.name}return observation?observation.label:"UNKNOWN_OBSERVATION_CONCEPT"}},compile=function(element){return RecursionHelper.compile(element,link)};return{restrict:"E",compile:compile,scope:{conceptSetName:"=",observation:"=",atLeastOneValueIsSet:"=",showTitle:"=",conceptSetRequired:"=",rootObservation:"=",patient:"=",collapseInnerSections:"=",rootConcept:"&",hideAbnormalButton:"="},templateUrl:"../common/concept-set/views/observation.html"}}]),angular.module("bahmni.common.conceptSet").directive("obsConstraints",function(){var attributesMap={Numeric:"number",Date:"date",Datetime:"datetime"},link=function($scope,element){var attributes={},obsConcept=$scope.obs.concept;obsConcept.conceptClass==Bahmni.Common.Constants.conceptDetailsClassName&&(obsConcept=$scope.obs.primaryObs.concept),attributes.type=attributesMap[obsConcept.dataType]||"text","number"===attributes.type&&(attributes.step="any"),obsConcept.hiNormal&&(attributes.max=obsConcept.hiNormal),obsConcept.lowNormal&&(attributes.min=obsConcept.lowNormal),"date"==attributes.type&&(null!=$scope.obs.conceptUIConfig&&$scope.obs.conceptUIConfig.allowFutureDates||(attributes.max=Bahmni.Common.Util.DateTimeFormatter.getDateWithoutTime())),element.attr(attributes)};return{link:link,scope:{obs:"="},require:"ngModel"}}),angular.module("bahmni.common.conceptSet").factory("conceptSetService",["$http","$q","$bahmniTranslate",function($http,$q,$bahmniTranslate){var getConcept=function(params,cache){return params.locale=params.locale||$bahmniTranslate.use(),$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{params:params,cache:cache})},getComputedValue=function(encounterData){var url=Bahmni.Common.Constants.encounterModifierUrl;return $http.post(url,encounterData,{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},getObsTemplatesForProgram=function(programUuid){var url=Bahmni.Common.Constants.entityMappingUrl;return $http.get(url,{params:{entityUuid:programUuid,mappingType:"program_obstemplate",s:"byEntityAndMappingType"}})};return{getConcept:getConcept,getComputedValue:getComputedValue,getObsTemplatesForProgram:getObsTemplatesForProgram}}]),angular.module("bahmni.common.conceptSet").factory("conceptSetUiConfigService",["$http","$q","appService",function($http,$q,appService){var setConceptUuidInsteadOfName=function(config,conceptNameField,uuidField){var conceptName=config[conceptNameField];if(null!=conceptName)return $http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{params:{name:conceptName,v:"custom:(uuid,name)"}}).then(function(response){var concept=response.data.results.filter(function(c){return c.name.name===conceptName});concept.length>0&&(config[uuidField]=concept[0].uuid)})},setExtraData=function(config){Object.getOwnPropertyNames(config).forEach(function(conceptConfigKey){var conceptConfig=config[conceptConfigKey];conceptConfig.freeTextAutocomplete instanceof Object&&(setConceptUuidInsteadOfName(conceptConfig.freeTextAutocomplete,"codedConceptName","codedConceptUuid"),setConceptUuidInsteadOfName(conceptConfig.freeTextAutocomplete,"conceptSetName","conceptSetUuid"))})},getConfig=function(){var config=appService.getAppDescriptor().getConfigValue("conceptSetUI")||{};return setExtraData(config),config};return{getConfig:getConfig}}]),Bahmni.ConceptSet.ObservationMapper=function(){function mapTabularObs(mappedGroupMembers,concept,obs,conceptSetConfig){var tabularObsGroups=_.filter(mappedGroupMembers,function(member){return conceptSetConfig[member.concept.name]&&conceptSetConfig[member.concept.name].isTabular});if(tabularObsGroups.length>0){var array=_.map(concept.setMembers,function(member){return member.name.name});tabularObsGroups.forEach(function(group){group.hidden=!0});var groupedObsGroups=_.groupBy(tabularObsGroups,function(group){return group.concept.name});_.values(groupedObsGroups).forEach(function(groups){var tabularObservations=new Bahmni.ConceptSet.TabularObservations(groups,obs,conceptSetConfig);obs.groupMembers.push(tabularObservations)});var sortedGroupMembers=_.sortBy(obs.groupMembers,function(observation){return array.indexOf(observation.concept.name)});obs.groupMembers.length=0,obs.groupMembers.push.apply(obs.groupMembers,sortedGroupMembers)}}function buildObservation(concept,savedObs,mappedGroupMembers){var comment=savedObs?savedObs.comment:null;return{concept:conceptMapper.map(concept),units:concept.units,label:getLabel(concept),possibleAnswers:concept.answers,groupMembers:mappedGroupMembers,comment:comment,showAddMoreButton:showAddMoreButton}}var conceptMapper=new Bahmni.Common.Domain.ConceptMapper,self=this;this.getObservationsForView=function(observations,conceptSetConfig){return internalMapForDisplay(observations,conceptSetConfig)};var internalMapForDisplay=function(observations,conceptSetConfig){var observationsForDisplay=[];return _.forEach(observations,function(savedObs){if(!savedObs.concept.conceptClass||savedObs.concept.conceptClass!==Bahmni.Common.Constants.conceptDetailsClassName&&savedObs.concept.conceptClass.name!==Bahmni.Common.Constants.conceptDetailsClassName)if(savedObs.concept.set)if(conceptSetConfig[savedObs.concept.name]&&conceptSetConfig[savedObs.concept.name].grid)savedObs.value=self.getGridObservationDisplayValue(savedObs),observationsForDisplay=observationsForDisplay.concat(createObservationForDisplay(savedObs,savedObs.concept));else{var groupMemberObservationsForDisplay=internalMapForDisplay(savedObs.groupMembers,conceptSetConfig);observationsForDisplay=observationsForDisplay.concat(groupMemberObservationsForDisplay)}else{var obsToDisplay=null;if(savedObs.isMultiSelect)obsToDisplay=savedObs;else if(!savedObs.hidden){var observation=newObservation(savedObs.concept,savedObs,[]);obsToDisplay=createObservationForDisplay(observation,observation.concept)}obsToDisplay&&observationsForDisplay.push(obsToDisplay)}else{var observationNode=new Bahmni.ConceptSet.ObservationNode(savedObs,savedObs,[],savedObs.concept),obsToDisplay=createObservationForDisplay(observationNode,observationNode.primaryObs.concept);obsToDisplay&&observationsForDisplay.push(obsToDisplay)}}),observationsForDisplay};this.map=function(observations,rootConcept,conceptSetConfig){var savedObs=findInSavedObservation(rootConcept,observations)[0];return mapObservation(rootConcept,savedObs,conceptSetConfig||{})};var findInSavedObservation=function(concept,observations){return _.filter(observations,function(obs){return obs&&obs.concept&&concept.uuid===obs.concept.uuid})},mapObservation=function(concept,savedObs,conceptSetConfig){var obs=null;if(savedObs&&(savedObs.isObservation||savedObs.isObservationNode))return savedObs;var mappedGroupMembers=concept&&concept.set?mapObservationGroupMembers(savedObs?savedObs.groupMembers:[],concept,conceptSetConfig):[];return concept.conceptClass.name===Bahmni.Common.Constants.conceptDetailsClassName?obs=newObservationNode(concept,savedObs,conceptSetConfig,mappedGroupMembers):(obs=newObservation(concept,savedObs,conceptSetConfig,mappedGroupMembers),new Bahmni.ConceptSet.MultiSelectObservations(conceptSetConfig).map(mappedGroupMembers)),mapTabularObs(mappedGroupMembers,concept,obs,conceptSetConfig),obs},mapObservationGroupMembers=function(observations,parentConcept,conceptSetConfig){var observationGroupMembers=[],conceptSetMembers=parentConcept.setMembers;return conceptSetMembers.forEach(function(memberConcept){for(var savedObservations=findInSavedObservation(memberConcept,observations),configForConcept=conceptSetConfig[memberConcept.name.name]||{},numberOfNodes=configForConcept.multiple||1,i=savedObservations.length-1;i>=0;i--)observationGroupMembers.push(mapObservation(memberConcept,savedObservations[i],conceptSetConfig));for(var i=0;i<numberOfNodes-savedObservations.length;i++)observationGroupMembers.push(mapObservation(memberConcept,null,conceptSetConfig))}),observationGroupMembers},getDatatype=function(concept){return concept.dataType?concept.dataType:concept.datatype&&concept.datatype.name},newObservation=function(concept,savedObs,conceptSetConfig,mappedGroupMembers){var observation=buildObservation(concept,savedObs,mappedGroupMembers),obs=new Bahmni.ConceptSet.Observation(observation,savedObs,conceptSetConfig,mappedGroupMembers);return"Boolean"==getDatatype(concept)&&(obs=new Bahmni.ConceptSet.BooleanObservation(obs,conceptSetConfig)),obs},newObservationNode=function(concept,savedObsNode,conceptSetConfig,mappedGroupMembers){var observation=buildObservation(concept,savedObsNode,mappedGroupMembers);return new Bahmni.ConceptSet.ObservationNode(observation,savedObsNode,conceptSetConfig,concept)},showAddMoreButton=function(rootObservation){var observation=this,lastObservationByLabel=_.findLast(rootObservation.groupMembers,{label:observation.label});return lastObservationByLabel.uuid===observation.uuid},createObservationForDisplay=function(observation,concept){if(null!=observation.value){var observationValue=getObservationDisplayValue(observation);return observationValue=observation.durationObs?observationValue+" "+getDurationDisplayValue(observation.durationObs):observationValue,{value:observationValue,abnormalObs:observation.abnormalObs,duration:observation.durationObs,provider:observation.provider,label:getLabel(observation.concept),observationDateTime:observation.observationDateTime,concept:concept,comment:observation.comment,uuid:observation.uuid}}},getObservationDisplayValue=function(observation){if(observation.isBoolean||"Boolean"===observation.type)return observation.value===!0?"Yes":"No";if(!observation.value)return"";if("object"==typeof observation.value.name){var valueConcept=conceptMapper.map(observation.value);return valueConcept.shortName||valueConcept.name}return observation.value.shortName||observation.value.name||observation.value},getDurationDisplayValue=function(duration){var durationForDisplay=Bahmni.Common.Util.DateUtil.convertToUnits(duration.value);return durationForDisplay.value&&durationForDisplay.unitName?"since "+durationForDisplay.value+" "+durationForDisplay.unitName:""};this.getGridObservationDisplayValue=function(observation){var memberValues=_.compact(_.map(observation.groupMembers,function(member){return getObservationDisplayValue(member)}));return memberValues.join(", ")};var getLabel=function(concept){var mappedConcept=conceptMapper.map(concept);return mappedConcept.shortName||mappedConcept.name}},Bahmni.ConceptSet.Observation=function(observation,savedObs,conceptUIConfig){var self=this;angular.extend(this,observation),this.isObservation=!0,this.conceptUIConfig=conceptUIConfig[this.concept.name]||[],this.uniqueId=_.uniqueId("observation_"),this.erroneousValue=null,savedObs?(this.uuid=savedObs.uuid,this.value=savedObs.value,this.observationDateTime=savedObs.observationDateTime,this.provider=savedObs.provider):this.value=this.conceptUIConfig.defaultValue,Object.defineProperty(this,"autocompleteValue",{enumerable:!0,get:function(){return null!=this.value&&"object"==typeof this.value?this.value.name:this.value},set:function(newValue){this.__prevValue=this.value,this.value=newValue}}),Object.defineProperty(this,"value",{enumerable:!0,get:function(){return null!=self._value?self._value:(savedObs&&"object"==typeof savedObs.value&&savedObs.value&&(savedObs.value.displayString=savedObs.value.shortName?savedObs.value.shortName:savedObs.value.name),savedObs?savedObs.value:void 0)},set:function(newValue){self.__prevValue=this.value,self._value=newValue,newValue||(savedObs=null),self.onValueChanged()}});var cloneNonTabularObs=function(oldObs){var newGroupMembers=[];return oldObs.groupMembers.forEach(function(member){if(void 0===member.isTabularObs){var clone=member.cloneNew();clone.hidden=member.hidden,newGroupMembers.push(clone)}}),newGroupMembers},getTabularObs=function(oldObs){var tabularObsList=[];return oldObs.groupMembers.forEach(function(member){void 0!==member.isTabularObs&&tabularObsList.push(member)}),tabularObsList},cloneTabularObs=function(oldObs,tabularObsList){return tabularObsList=_.map(tabularObsList,function(tabularObs){var matchingObsList=_.filter(oldObs.groupMembers,function(member){return member.concept.name==tabularObs.concept.name});return new Bahmni.ConceptSet.TabularObservations(matchingObsList,oldObs,conceptUIConfig)}),tabularObsList.forEach(function(tabularObs){oldObs.groupMembers.push(tabularObs)}),oldObs};this.cloneNew=function(){var oldObs=angular.copy(observation);if(oldObs.groupMembers&&oldObs.groupMembers.length>0){oldObs.groupMembers=_.filter(oldObs.groupMembers,function(member){return!member.isMultiSelect});var newGroupMembers=cloneNonTabularObs(oldObs),tabularObsList=getTabularObs(oldObs);oldObs.groupMembers=newGroupMembers,_.isEmpty(tabularObsList)||(oldObs=cloneTabularObs(oldObs,tabularObsList))}new Bahmni.ConceptSet.MultiSelectObservations(conceptUIConfig).map(oldObs.groupMembers);var clone=new Bahmni.ConceptSet.Observation(oldObs,null,conceptUIConfig);return clone.comment=void 0,clone.disabled=this.disabled,clone}},Bahmni.ConceptSet.Observation.prototype={displayValue:function(){if(!(this.possibleAnswers.length>0))return this.value;for(var i=0;i<this.possibleAnswers.length;i++)if(this.possibleAnswers[i].uuid===this.value)return this.possibleAnswers[i].display},isGroup:function(){return!!this.groupMembers&&this.groupMembers.length>0},isComputed:function(){return"Computed"===this.concept.conceptClass},isComputedAndEditable:function(){return"Computed/Editable"===this.concept.conceptClass},isNumeric:function(){return"Numeric"===this.getDataTypeName()},isValidNumeric:function(){return!(!this.isDecimalAllowed()&&this.value&&this.value.toString().indexOf(".")>=0)},isValidNumericValue:function(){var element=document.getElementById(this.uniqueId);return""!==this.value||!element||element.checkValidity()},isText:function(){return"Text"===this.getDataTypeName()},isCoded:function(){return"Coded"===this.getDataTypeName()},isDatetime:function(){return"Datetime"===this.getDataTypeName()},isImage:function(){return this.concept.conceptClass==Bahmni.Common.Constants.imageClassName},isVideo:function(){return this.concept.conceptClass==Bahmni.Common.Constants.videoClassName},getDataTypeName:function(){return this.concept.dataType},isDecimalAllowed:function(){return this.concept.allowDecimal},isDateDataType:function(){return"Date".indexOf(this.getDataTypeName())!=-1},isVoided:function(){return void 0!==this.voided&&this.voided},getPossibleAnswers:function(){return this.possibleAnswers},getHighAbsolute:function(){return this.concept.hiAbsolute},getLowAbsolute:function(){return this.concept.lowAbsolute},isHtml5InputDataType:function(){return["Date","Numeric"].indexOf(this.getDataTypeName())!==-1},isGrid:function(){return this.conceptUIConfig.grid},isButtonRadio:function(){return this.conceptUIConfig.buttonRadio},isComplex:function(){return"Complex"===this.concept.dataType},isLocationRef:function(){return this.isComplex()&&"LocationObsHandler"===this.concept.handler},isProviderRef:function(){return this.isComplex()&&"ProviderObsHandler"===this.concept.handler},getControlType:function(){return this.hidden?"hidden":this.conceptUIConfig.freeTextAutocomplete?"freeTextAutocomplete":this.isHtml5InputDataType()?"html5InputDataType":this.isImage()?"image":this.isVideo()?"video":this.isText()?"text":this.isCoded()?this._getCodedControlType():this.isGrid()?"grid":this.isDatetime()?"datetime":this.isLocationRef()?"text":this.isProviderRef()?"text":"unknown"},canHaveComment:function(){return this.conceptUIConfig.disableAddNotes?!this.conceptUIConfig.disableAddNotes:!this.isText()&&!this.isImage()&&!this.isVideo()},canAddMore:function(){return 1==this.conceptUIConfig.allowAddMore},isStepperControl:function(){if(this.isNumeric())return 1==this.conceptUIConfig.stepper},isConciseText:function(){return 1==this.conceptUIConfig.conciseText},_getCodedControlType:function(){var conceptUIConfig=this.conceptUIConfig;return conceptUIConfig.autocomplete?"autocomplete":conceptUIConfig.dropdown?"dropdown":"buttonselect"},onValueChanged:function(){this.isNumeric()&&this.setErroneousValue()},setErroneousValue:function(){if(this.hasValue()){var erroneousValue=this.value>(this.concept.hiAbsolute||1/0)||this.value<(this.concept.lowAbsolute||0);this.erroneousValue=erroneousValue}else this.erroneousValue=void 0},getInputType:function(){return this.getDataTypeName()},atLeastOneValueSet:function(){return this.isGroup()?this.groupMembers.some(function(childNode){return childNode.atLeastOneValueSet()}):this.hasValue()&&!this.isVoided()},hasValue:function(){var value=this.value;return value===!1||(0===value||!(""===value||!value)&&(!(value instanceof Array)||value.length>0))},hasValueOf:function(value){return!(!this.value||!value)&&(this.value==value||this.value.uuid==value.uuid)},toggleSelection:function(answer){this.value&&this.value.uuid===answer.uuid?this.value=null:this.value=answer},isValidDate:function(){if(this.isComputed())return!0;if(!this.hasValue())return!0;var date=Bahmni.Common.Util.DateUtil.parse(this.value);if(!this.conceptUIConfig.allowFutureDates){var today=Bahmni.Common.Util.DateUtil.parse(moment().format("YYYY-MM-DD"));if(today<date)return!1}return date.getUTCFullYear()&&date.getUTCFullYear().toString().length<=4},hasInvalidDateTime:function(){if(this.isComputed())return!1;var date=Bahmni.Common.Util.DateUtil.parse(this.value);return!this.conceptUIConfig.allowFutureDates&&moment()<date||"Invalid Datetime"===this.value},isValid:function(checkRequiredFields,conceptSetRequired){if(this.isNumeric()&&!this.isValidNumeric())return!1;if(this.error)return!1;if(this.hidden)return!0;if(checkRequiredFields){if(this.isGroup())return this._hasValidChildren(checkRequiredFields,conceptSetRequired);if(conceptSetRequired&&this.isRequired()&&!this.hasValue())return!1;if(this.isRequired()&&!this.hasValue())return!1}return this._isDateDataType()?this.isValidDate():this._isDateTimeDataType()?!this.hasInvalidDateTime():!this.erroneousValue&&("autocomplete"!==this.getControlType()||(_.isEmpty(this.value)||_.isObject(this.value)))},isValueInAbsoluteRange:function(){return!this.erroneousValue&&(!this.isGroup()||this._areChildNodesInAbsoluteRange())},_isDateDataType:function(){return"Date"===this.getDataTypeName()},_isDateTimeDataType:function(){return"Datetime"===this.getDataTypeName()},isRequired:function(){return this.disabled=!!this.disabled&&this.disabled,this.conceptUIConfig.required===!0&&this.disabled===!1},isFormElement:function(){return(!this.concept.set||this.isGrid())&&!this.isComputed()},_hasValidChildren:function(checkRequiredFields,conceptSetRequired){return this.groupMembers.every(function(member){return member.isValid(checkRequiredFields,conceptSetRequired)})},_areChildNodesInAbsoluteRange:function(){return this.groupMembers.every(function(member){return"function"!=typeof member.isValueInAbsoluteRange||member.isValueInAbsoluteRange()})},markAsNonCoded:function(){this.markedAsNonCoded=!this.markedAsNonCoded;
},toggleVoidingOfImage:function(){this.voided=!this.voided},assignAddMoreButtonID:function(){return this.concept.name.split(" ").join("_").toLowerCase()+"_addmore_"+this.uniqueId}},Bahmni.ConceptSet.BooleanObservation=function(observation,conceptUIConfig){angular.extend(this,observation),this.isBoolean=!0,this.conceptUIConfig=conceptUIConfig[this.concept.name]||{},this.cloneNew=function(){var clone=new Bahmni.ConceptSet.BooleanObservation(angular.copy(observation),conceptUIConfig);return clone.value=void 0,clone.comment=void 0,clone.uuid=null,clone.disabled=this.disabled,clone};var possibleAnswers=[{displayString:"OBS_BOOLEAN_YES_KEY",value:!0},{displayString:"OBS_BOOLEAN_NO_KEY",value:!1}];this.getPossibleAnswers=function(){return possibleAnswers},this.hasValueOf=function(answer){return this.value===answer.value},this.toggleSelection=function(answer){this.value===answer.value?this.value=null:this.value=answer.value},this.isFormElement=function(){return!0},this.getControlType=function(){return"buttonselect"},this.isRequired=function(){return this.disabled=!!this.disabled&&this.disabled,this.getConceptUIConfig().required===!0&&this.disabled===!1},this.isComputedAndEditable=function(){return"Computed/Editable"===this.concept.conceptClass},this.atLeastOneValueSet=function(){return void 0!=this.value},this.isValid=function(checkRequiredFields,conceptSetRequired){if(this.error)return!1;var notYetSet=function(value){return"undefined"==typeof value||null==value};if(checkRequiredFields){if(conceptSetRequired&&this.isRequired()&&notYetSet(this.value))return!1;if(this.isRequired()&&notYetSet(this.value))return!1}return!0},this.canHaveComment=function(){return!this.getConceptUIConfig().disableAddNotes||!this.getConceptUIConfig().disableAddNotes},this.getConceptUIConfig=function(){return this.conceptUIConfig},this.canAddMore=function(){return 1==this.getConceptUIConfig().allowAddMore},this.isComputed=function(){return"Computed"===this.concept.conceptClass},this.getDataTypeName=function(){return this.concept.dataType},this.hasValue=function(){var value=this.value;return value===!1||(0===value||!(""===value||!value)&&(!(value instanceof Array)||value.length>0))},this.isNumeric=function(){return"Numeric"===this.getDataTypeName()},this.isText=function(){return"Text"===this.getDataTypeName()},this.isCoded=function(){return"Coded"===this.getDataTypeName()},this._isDateTimeDataType=function(){return"Datetime"===this.getDataTypeName()}},function(){var findObservationByClassName=function(groupMembers,conceptClassName){return _.find(groupMembers,function(member){return member.concept.conceptClass.name===conceptClassName||member.concept.conceptClass===conceptClassName})},findObservationByConceptName=function(groupMembers,conceptName){return _.find(groupMembers,{concept:{name:conceptName}})},setNewObservation=function(observation,newValue){observation&&(observation.__prevValue=observation.value,observation.value=newValue,observation.voided=!1)},voidObservation=function(observation){observation&&(observation.uuid?observation.voided=!0:observation.value=void 0)},isFreeTextAutocompleteType=function(conceptUIConfig){return conceptUIConfig.autocomplete&&conceptUIConfig.nonCodedConceptName&&conceptUIConfig.codedConceptName};Bahmni.ConceptSet.ObservationNode=function(observation,savedObs,conceptUIConfig,concept){angular.extend(this,observation),this.conceptUIConfig=conceptUIConfig[concept.name.name]||!_.isEmpty(concept.setMembers)&&conceptUIConfig[concept.setMembers[0].name.name]||{},this.cloneNew=function(){var oldObs=angular.copy(observation);oldObs.groupMembers=_.map(oldObs.groupMembers,function(member){return member.cloneNew()});var clone=new Bahmni.ConceptSet.ObservationNode(oldObs,null,conceptUIConfig,concept);return clone.comment=void 0,clone};var getPrimaryObservationValue=function(){return this.primaryObs&&_.get(this,"primaryObs.value.name")||_.get(this,"primaryObs.value")},setFreeTextPrimaryObservationValue=function(newValue){var codedObservation=findObservationByConceptName(this.groupMembers,this.conceptUIConfig.codedConceptName),nonCodedObservation=findObservationByConceptName(this.groupMembers,this.conceptUIConfig.nonCodedConceptName);"object"==typeof newValue?(setNewObservation(codedObservation,newValue),voidObservation(nonCodedObservation),this.markedAsNonCoded=!1):(setNewObservation(nonCodedObservation,newValue),voidObservation(codedObservation)),this.onValueChanged(newValue)},setFirstObservationValue=function(newValue){setNewObservation(this.primaryObs,newValue),this.onValueChanged(newValue)};Object.defineProperty(this,"value",{enumerable:!0,get:getPrimaryObservationValue,set:isFreeTextAutocompleteType(this.conceptUIConfig)?setFreeTextPrimaryObservationValue:setFirstObservationValue});var getFreeTextPrimaryObservation=function(){var isAlreadySavedObservation=function(observation){return _.isString(_.get(observation,"value"))&&!_.get(observation,"voided")},codedConceptObservation=findObservationByConceptName(this.groupMembers,this.conceptUIConfig.codedConceptName),nonCodedConceptObservation=findObservationByConceptName(this.groupMembers,this.conceptUIConfig.nonCodedConceptName);if(isAlreadySavedObservation(nonCodedConceptObservation))return nonCodedConceptObservation;if(!codedConceptObservation)throw new Error("Configuration Error: Concept '"+this.conceptUIConfig.codedConceptName+"' is not a set member of '"+concept.name.name+"'.");return codedConceptObservation},getGroupMembersWithoutClass=function(groupMembers,classNames){return _.filter(groupMembers,function(member){return!(_.includes(classNames,member.concept.conceptClass.name)||_.includes(classNames,member.concept.conceptClass))})},getFirstObservation=function(){var observations=getGroupMembersWithoutClass(this.groupMembers,[Bahmni.Common.Constants.abnormalConceptClassName,Bahmni.Common.Constants.unknownConceptClassName,Bahmni.Common.Constants.durationConceptClassName]);if(_.isEmpty(observations))return this.groupMembers[0];var primaryObs=observations[1]&&observations[1].uuid&&!observations[1].voided?observations[1]:observations[0];return observations[0].isMultiSelect?observations[0]:primaryObs.uuid&&!primaryObs.voided?primaryObs:!observations[1]||!observations[1].value&&""!==observations[1].value||observations[1].voided?observations[0]:observations[1]};Object.defineProperty(this,"primaryObs",{enumerable:!0,get:isFreeTextAutocompleteType(this.conceptUIConfig)?getFreeTextPrimaryObservation:getFirstObservation}),this.isObservationNode=!0,this.uniqueId=_.uniqueId("observation_"),this.durationObs=findObservationByClassName(this.groupMembers,Bahmni.Common.Constants.durationConceptClassName),this.abnormalObs=findObservationByClassName(this.groupMembers,Bahmni.Common.Constants.abnormalConceptClassName),this.unknownObs=findObservationByClassName(this.groupMembers,Bahmni.Common.Constants.unknownConceptClassName),this.markedAsNonCoded="Coded"!==this.primaryObs.concept.dataType&&this.primaryObs.uuid,savedObs?(this.uuid=savedObs.uuid,this.observationDateTime=savedObs.observationDateTime):this.value=this.conceptUIConfig.defaultValue},Bahmni.ConceptSet.ObservationNode.prototype={canAddMore:function(){return 1==this.conceptUIConfig.allowAddMore},isStepperControl:function(){return!!this.isNumeric()&&1==this.conceptUIConfig.stepper},getPossibleAnswers:function(){return this.primaryObs.concept.answers},getCodedConcept:function(){return findObservationByConceptName(this.groupMembers,this.conceptUIConfig.codedConceptName).concept},onValueChanged:function(){!this.primaryObs.hasValue()&&this.abnormalObs&&(this.abnormalObs.value=void 0,this.abnormalObs.erroneousValue=void 0),this.primaryObs.isNumeric()&&this.primaryObs.hasValue()&&this.abnormalObs&&this.setAbnormal(),this.primaryObs.observationDateTime=null,this.unknownObs&&this.setUnknown()},setAbnormal:function(){if(this.primaryObs.hasValue()){var erroneousValue=this.value>(this.primaryObs.concept.hiAbsolute||1/0)||this.value<(this.primaryObs.concept.lowAbsolute||0),valueInRange=this.value<=(this.primaryObs.concept.hiNormal||1/0)&&this.value>=(this.primaryObs.concept.lowNormal||0);this.abnormalObs.value=!valueInRange,this.abnormalObs.erroneousValue=erroneousValue}else this.abnormalObs.value=void 0,this.abnormalObs.erroneousValue=void 0},setUnknown:function(){this.primaryObs.atLeastOneValueSet()&&this.primaryObs.hasValue()?this.unknownObs.value=!1:0==this.unknownObs.value&&(this.unknownObs.value=void 0)},displayValue:function(){if(!(this.possibleAnswers.length>0))return this.value;for(var i=0;i<this.possibleAnswers.length;i++)if(this.possibleAnswers[i].uuid===this.value)return this.possibleAnswers[i].display},isGroup:function(){return!1},getControlType:function(){return isFreeTextAutocompleteType(this.conceptUIConfig)?"freeTextAutocomplete":this.conceptUIConfig.autocomplete?"autocomplete":this.isHtml5InputDataType()?"html5InputDataType":this.primaryObs.isText()?"text":this.conceptUIConfig.dropdown?"dropdown":"buttonselect"},isHtml5InputDataType:function(){return["Date","Numeric","Datetime"].indexOf(this.primaryObs.getDataTypeName())!=-1},_isDateTimeDataType:function(){return"Datetime"===this.primaryObs.getDataTypeName()},isComputed:function(){return this.primaryObs.isComputed()},isConciseText:function(){return this.conceptUIConfig.conciseText===!0},isComputedAndEditable:function(){return"Computed/Editable"===this.concept.conceptClass},atLeastOneValueSet:function(){return this.primaryObs.hasValue()},doesNotHaveDuration:function(){return!(!this.durationObs||!this.conceptUIConfig.durationRequired)&&(!this.durationObs.value||this.durationObs.value<0)},isValid:function(checkRequiredFields,conceptSetRequired){if(this.isNumeric()&&(!this.isValidNumeric()||!this.isValidNumericValue()))return!1;if(this.isGroup())return this._hasValidChildren(checkRequiredFields,conceptSetRequired);if(checkRequiredFields){if(conceptSetRequired&&this.isRequired()&&!this.primaryObs.hasValue())return!1;if(this.isRequired()&&!this.primaryObs.hasValue())return!1;if("freeTextAutocomplete"===this.getControlType())return this.isValidFreeTextAutocomplete()}return"Date"===this.primaryObs.getDataTypeName()?this.primaryObs.isValidDate():(!this.primaryObs.hasValue()||!this.doesNotHaveDuration())&&((!this.abnormalObs||!this.abnormalObs.erroneousValue)&&(this.primaryObs.hasValue()&&this.primaryObs._isDateTimeDataType()?!this.hasInvalidDateTime():"autocomplete"===this.getControlType()?_.isEmpty(this.primaryObs.value)||_.isObject(this.primaryObs.value):!this.primaryObs.hasValue()||!this.primaryObs.erroneousValue))},isValueInAbsoluteRange:function(){return!(this.abnormalObs&&this.abnormalObs.erroneousValue)},isValidFreeTextAutocomplete:function(){return!("Coded"!==this.primaryObs.concept.dataType&&!this.markedAsNonCoded&&this.primaryObs.value)},isRequired:function(){return this.disabled=!!this.disabled&&this.disabled,this.conceptUIConfig.required===!0&&this.disabled===!1},isDurationRequired:function(){return!!this.conceptUIConfig.durationRequired&&!!this.primaryObs.value},isNumeric:function(){return"Numeric"===this.primaryObs.getDataTypeName()},isDecimalAllowed:function(){return this.primaryObs.concept.allowDecimal},isValidNumeric:function(){return!(!this.isDecimalAllowed()&&this.value&&this.value.toString().indexOf(".")>=0)},isValidNumericValue:function(){var element=document.getElementById(this.uniqueId);return""!==this.value||!element||element.checkValidity()},_hasValidChildren:function(checkRequiredFields,conceptSetRequired){return this.groupMembers.every(function(member){return member.isValid(checkRequiredFields,conceptSetRequired)})},markAsNonCoded:function(){this.markedAsNonCoded=!this.markedAsNonCoded},toggleAbnormal:function(){this.abnormalObs.value=!this.abnormalObs.value},toggleUnknown:function(){this.unknownObs.value?this.unknownObs.value=void 0:this.unknownObs.value=!0},assignAddMoreButtonID:function(){return this.concept.name.split(" ").join("_").toLowerCase()+"_addmore_"+this.uniqueId},canHaveComment:function(){return!this.conceptUIConfig.disableAddNotes||!this.conceptUIConfig.disableAddNotes},hasInvalidDateTime:function(){if(this.isComputed())return!1;var date=Bahmni.Common.Util.DateUtil.parse(this.value);return!this.conceptUIConfig.allowFutureDates&&moment()<date||"Invalid Datetime"===this.value}}}(),Bahmni.ConceptSet.TabularObservations=function(obsGroups,parentObs,conceptUIConfig){this.parentObs=parentObs,this.concept=obsGroups[0]&&obsGroups[0].concept,this.label=obsGroups[0]&&obsGroups[0].label,this.conceptUIConfig=conceptUIConfig[this.concept.name]||{},this.isTabularObs=!0,this.rows=_.map(obsGroups,function(group){return new Bahmni.ConceptSet.ObservationRow(group,conceptUIConfig)}),this.columns=_.map(obsGroups[0].groupMembers,function(group){return group.concept}),this.cloneNew=function(){var old=this,clone=new Bahmni.ConceptSet.TabularObservations(angular.copy(obsGroups),parentObs,conceptUIConfig);return clone.rows=_.map(old.rows,function(row){return row.cloneNew()}),clone.disabled=this.disabled,clone},this.addNew=function(row){var newRow=row.cloneNew();this.rows.push(newRow),this.parentObs.groupMembers.push(newRow.obsGroup)},this.remove=function(row){row.void(),this.rows.splice(this.rows.indexOf(row),1),0==this.rows.length&&this.addNew(row)},this.isFormElement=function(){return!1},this.getControlType=function(){return"tabular"},this.isValid=function(checkRequiredFields,conceptSetRequired){return _.every(this.rows,function(observationRow){return _.every(observationRow.cells,function(conceptSetObservation){return conceptSetObservation.isValid(checkRequiredFields,conceptSetRequired)})})},this.getConceptUIConfig=function(){return this.conceptUIConfig||{}},this.canAddMore=function(){return 1==this.getConceptUIConfig().allowAddMore},this.atLeastOneValueSet=function(){return this.rows.some(function(childNode){return childNode.obsGroup.atLeastOneValueSet()})},this.isNumeric=function(){return"Numeric"===this.concept.dataType},this.isValidNumericValue=function(){var element=document.getElementById(this.uniqueId);return""!==this.value||!element||element.checkValidity()}},Bahmni.ConceptSet.ObservationRow=function(obsGroup,conceptUIConfig){this.obsGroup=obsGroup,this.concept=obsGroup.concept,this.cells=obsGroup.groupMembers,this.void=function(){this.obsGroup.voided=!0},this.cloneNew=function(){var newObsGroup=this.obsGroup.cloneNew();newObsGroup.hidden=!0;var clone=new Bahmni.ConceptSet.ObservationRow(newObsGroup,conceptUIConfig);return clone.disabled=this.disabled,clone}},Bahmni.ConceptSet.MultiSelectObservations=function(conceptSetConfig){var self=this;this.multiSelectObservationsMap={},this.map=function(memberOfCollection){memberOfCollection.forEach(function(member){isMultiSelectable(member.concept,conceptSetConfig)&&add(member.concept,member,memberOfCollection)}),insertMultiSelectObsInExistingOrder(memberOfCollection)};var isMultiSelectable=function(concept,conceptSetConfig){return conceptSetConfig[concept.name]&&conceptSetConfig[concept.name].multiSelect},insertMultiSelectObsInExistingOrder=function(memberOfCollection){getAll().forEach(function(multiObs){var index=_.findIndex(memberOfCollection,function(member){return member.concept.name===multiObs.concept.name});memberOfCollection.splice(index,0,multiObs)})},add=function(concept,obs,memberOfCollection){var conceptName=concept.name.name||concept.name;self.multiSelectObservationsMap[conceptName]=self.multiSelectObservationsMap[conceptName]||new Bahmni.ConceptSet.MultiSelectObservation(concept,memberOfCollection,conceptSetConfig),self.multiSelectObservationsMap[conceptName].add(obs)},getAll=function(){return _.values(self.multiSelectObservationsMap)}},Bahmni.ConceptSet.MultiSelectObservation=function(concept,memberOfCollection,conceptSetConfig){var self=this;this.label=concept.shortName||concept.name,this.isMultiSelect=!0,this.selectedObs={},this.concept=concept,this.concept.answers=this.concept.answers||[],this.groupMembers=[],this.provider=null,this.observationDateTime="",this.conceptUIConfig=conceptSetConfig[this.concept.name]||{},this.possibleAnswers=self.concept.answers.map(function(answer){var cloned=_.cloneDeep(answer);return answer.name.name&&(cloned.name=answer.name.name),cloned}),this.getPossibleAnswers=function(){return this.possibleAnswers},this.cloneNew=function(){var clone=new Bahmni.ConceptSet.MultiSelectObservation(concept,memberOfCollection,conceptSetConfig);return clone.disabled=this.disabled,clone},this.add=function(obs){if(obs.value){self.selectedObs[obs.value.name]=obs,self.provider||(self.provider=self.selectedObs[obs.value.name].provider);var currentObservationDateTime=self.selectedObs[obs.value.name].observationDateTime;self.observationDateTime<currentObservationDateTime&&(self.observationDateTime=currentObservationDateTime)}obs.hidden=!0},this.isComputedAndEditable=function(){return"Computed/Editable"===this.concept.conceptClass},this.hasValueOf=function(answer){return self.selectedObs[answer.name]&&!self.selectedObs[answer.name].voided},this.toggleSelection=function(answer){self.hasValueOf(answer)?unselectAnswer(answer):self.selectAnswer(answer)},this.isFormElement=function(){return!0},this.getControlType=function(){var conceptConfig=this.getConceptUIConfig();return this.isCoded()&&1==conceptConfig.autocomplete&&1==conceptConfig.multiSelect?"autocompleteMultiSelect":1==conceptConfig.autocomplete?"autocomplete":"buttonselect"},this.atLeastOneValueSet=function(){var obsValue=_.filter(this.selectedObs,function(obs){return obs.value});return!_.isEmpty(obsValue)},this.hasValue=function(){return!_.isEmpty(this.selectedObs)},this.hasNonVoidedValue=function(){var hasNonVoidedValue=!1;return this.hasValue()&&angular.forEach(this.selectedObs,function(obs){obs.voided||(hasNonVoidedValue=!0)}),hasNonVoidedValue},this.isValid=function(checkRequiredFields,conceptSetRequired){if(this.error)return!1;if(checkRequiredFields){if(conceptSetRequired&&this.isRequired()&&!this.hasNonVoidedValue())return!1;if(this.isRequired()&&!this.hasNonVoidedValue())return!1}return!0},this.canHaveComment=function(){return!1},this.getConceptUIConfig=function(){return this.conceptUIConfig||{}},this.canAddMore=function(){return 1==this.getConceptUIConfig().allowAddMore},this.isRequired=function(){return this.disabled=!!this.disabled&&this.disabled,this.getConceptUIConfig().required===!0&&this.disabled===!1};var createObsFrom=function(answer){var obs=newObservation(concept,answer,conceptSetConfig);return memberOfCollection.push(obs),obs},removeObsFrom=function(answer){var obs=newObservation(concept,answer,conceptSetConfig);_.remove(memberOfCollection,function(member){return!!member.value&&obs.value.displayString==member.value.displayString})};this.selectAnswer=function(answer){var obs=self.selectedObs[answer.name];obs?(obs.value=answer,obs.voided=!1):(obs=createObsFrom(answer),self.add(obs))};var unselectAnswer=function(answer){var obs=self.selectedObs[answer.name];obs&&obs.uuid?(obs.value=null,obs.voided=!0):(removeObsFrom(answer),delete self.selectedObs[answer.name])},newObservation=function(concept,value,conceptSetConfig){var observation=buildObservation(concept);return new Bahmni.ConceptSet.Observation(observation,{value:value},conceptSetConfig,[])},buildObservation=function(concept){return{concept:concept,units:concept.units,label:concept.shortName||concept.name,possibleAnswers:self.concept.answers,groupMembers:[],comment:null}};this.getValues=function(){var values=[];return _.values(self.selectedObs).forEach(function(obs){obs.value&&values.push(obs.value.shortName||obs.value.name)}),values},this.isComputed=function(){return"Computed"===this.concept.conceptClass},this.getDataTypeName=function(){return this.concept.dataType},this._isDateTimeDataType=function(){return"Datetime"===this.getDataTypeName()},this.isNumeric=function(){return"Numeric"===this.getDataTypeName()},this.isText=function(){return"Text"===this.getDataTypeName()},this.isCoded=function(){return"Coded"===this.getDataTypeName()}},Bahmni.ConceptSet.CustomRepresentationBuilder={build:function(fields,childPropertyName,numberOfLevels){for(var childPropertyRep=childPropertyName+":{{entity_fileds}}",singleEntityString="("+fields.concat(childPropertyRep).join(",")+")",customRepresentation=singleEntityString,i=0;i<numberOfLevels;i++)customRepresentation=customRepresentation.replace("{{entity_fileds}}",singleEntityString);return customRepresentation=customRepresentation.replace(","+childPropertyRep,"")}},angular.module("bahmni.common.patientSearch",["bahmni.common.patient","infinite-scroll"]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.PatientSearch=Bahmni.Common.PatientSearch||{},Bahmni.Common.PatientSearch.Constants={searchExtensionTileViewType:"tile",searchExtensionTabularViewType:"tabular",tabularViewIgnoreHeadingsList:["display","uuid","image","$$hashKey","activeVisitUuid","hasBeenAdmitted","forwardUrl","programUuid","enrollment"],identifierHeading:["ID","Id","id","identifier","DQ_COLUMN_TITLE_ACTION"],nameHeading:["NAME","Name","name"],patientTileHeight:100,patientTileWidth:100,printIgnoreHeadingsList:["DQ_COLUMN_TITLE_ACTION"],tileLoadRatio:.5},Bahmni.Common.PatientSearch.Search=function(searchTypes){function mapPatient(patient){return(patient.name||patient.givenName||patient.familyName)&&(patient.name=patient.name||patient.givenName+(patient.familyName?" "+patient.familyName:"")),patient.display=_.map(self.searchColumns,function(column){return patient[column]}).join(" - "),patient.image=Bahmni.Common.Constants.patientImageUrlByPatientUuid+patient.uuid,patient}var self=this;self.searchTypes=searchTypes||[],self.searchType=this.searchTypes[0],self.searchParameter="",self.noResultsMessage=null,self.searchResults=[],self.activePatients=[],self.navigated=!1,self.links=self.searchType&&self.searchType.links?self.searchType.links:[],self.searchColumns=self.searchType&&self.searchType.searchColumns?self.searchType.searchColumns:["identifier","name"],angular.forEach(searchTypes,function(searchType){searchType.patientCount="..."}),self.switchSearchType=function(searchType){self.noResultsMessage=null,self.isSelectedSearch(searchType)||(self.searchParameter="",self.navigated=!0,self.searchType=searchType,self.activePatients=[],self.searchResults=[],self.links=self.searchType&&self.searchType.links?self.searchType.links:[],self.searchColumns=self.searchType&&self.searchType.searchColumns?self.searchType.searchColumns:["identifier","name"]),self.markPatientEntry()},self.markPatientEntry=function(){self.startPatientSearch=!0,window.setTimeout(function(){self.startPatientSearch=!1})},self.patientsCount=function(){return self.activePatients.length},self.updatePatientList=function(patientList){self.activePatients=patientList.map(mapPatient),self.searchResults=self.activePatients},self.updateSearchResults=function(patientList){self.updatePatientList(patientList),0===self.activePatients.length&&""!=self.searchParameter?self.noResultsMessage="NO_RESULTS_FOUND":self.noResultsMessage=null},self.hasSingleActivePatient=function(){return 1===self.activePatients.length},self.filterPatients=function(matchingCriteria){matchingCriteria=matchingCriteria?matchingCriteria:matchesNameOrId,self.searchResults=self.searchParameter?self.activePatients.filter(matchingCriteria):self.activePatients},self.filterPatientsByIdentifier=function(){self.filterPatients(matchesId)},self.isSelectedSearch=function(searchType){return self.searchType&&self.searchType.id==searchType.id},self.isCurrentSearchLookUp=function(){return self.searchType&&self.searchType.handler},self.isTileView=function(){return self.searchType&&self.searchType.view===Bahmni.Common.PatientSearch.Constants.searchExtensionTileViewType},self.isTabularView=function(){return self.searchType&&self.searchType.view===Bahmni.Common.PatientSearch.Constants.searchExtensionTabularViewType},self.showPatientCountOnSearchParameter=function(searchType){return showPatientCount(searchType)&&self.searchParameter};var matchesNameOrId=function(patient){return patient.display.toLowerCase().indexOf(self.searchParameter.toLowerCase())!==-1},matchesId=function(patient){return patient.identifier.toLowerCase().indexOf(self.searchParameter.toLowerCase())!==-1},showPatientCount=function(searchType){return self.isSelectedSearch(searchType)&&self.isCurrentSearchLookUp()}},angular.module("bahmni.common.patientSearch").directive("resize",["$window",function($window){var controller=function($scope){$scope.storeWindowDimensions=function(){var windowWidth=window.innerWidth,windowHeight=window.innerHeight,tileWidth=Bahmni.Common.PatientSearch.Constants.patientTileWidth,tileHeight=Bahmni.Common.PatientSearch.Constants.patientTileHeight;$scope.tilesToFit=Math.ceil(windowWidth*windowHeight/(tileWidth*tileHeight)),$scope.tilesToLoad=Math.ceil($scope.tilesToFit*Bahmni.Common.PatientSearch.Constants.tileLoadRatio)};var updateVisibleResults=function(){$scope.visibleResults=$scope.searchResults.slice(0,$scope.tilesToLoad)};$scope.loadMore=function(){var last=$scope.visibleResults.length,more=$scope.searchResults.length-last,toShow=more>$scope.tilesToLoad?$scope.tilesToLoad:more;if(toShow>0)for(var i=1;i<=toShow;i++)$scope.visibleResults.push($scope.searchResults[last+i-1])},$scope.$watch("searchResults",updateVisibleResults),$scope.$watch("tilesToFit",updateVisibleResults)},link=function($scope){$scope.storeWindowDimensions(),angular.element($window).bind("resize",function(){$scope.$apply(function(){$scope.storeWindowDimensions()})})};return{restrict:"E",link:link,controller:controller,transclude:!0,scope:{searchResults:"=",visibleResults:"="},template:'<div ng-transclude infinite-scroll="loadMore()"></div>'}}]),angular.module("bahmni.common.patientSearch").directive("scheduler",["$interval",function($interval){var link=function($scope){var promise,cancelSchedule=function(){promise&&($interval.cancel(promise),promise=null)},startSchedule=function(){promise||(promise=$interval($scope.triggerFunction,1e3*$scope.refreshTime))};$scope.$watch(function(){return $scope.watchOn},function(value){$scope.refreshTime>0&&(value?cancelSchedule():startSchedule())}),$scope.triggerFunction(),$scope.$on("$destroy",function(){cancelSchedule()})};return{restrict:"A",link:link,scope:{refreshTime:"=",watchOn:"=",triggerFunction:"&"}}}]),angular.module("bahmni.common.patientSearch").controller("PatientsListController",["$scope","$window","patientService","$rootScope","appService","spinner","$stateParams","$bahmniCookieStore","printer","configurationService",function($scope,$window,patientService,$rootScope,appService,spinner,$stateParams,$bahmniCookieStore,printer,configurationService){const DEFAULT_FETCH_DELAY=2e3;var patientListSpinner,patientSearchConfig=appService.getAppDescriptor().getConfigValue("patientSearch"),initialize=function(){var searchTypes=appService.getAppDescriptor().getExtensions("org.bahmni.patient.search","config").map(mapExtensionToSearchType);$scope.search=new Bahmni.Common.PatientSearch.Search(_.without(searchTypes,void 0)),$scope.search.markPatientEntry(),$scope.$watch("search.searchType",function(currentSearchType){_.isEmpty(currentSearchType)||fetchPatients(currentSearchType)}),$scope.$watch("search.activePatients",function(activePatientsList){activePatientsList.length>0&&patientListSpinner&&hideSpinner(spinner,patientListSpinner,$(".tab-content"))}),patientSearchConfig&&patientSearchConfig.serializeSearch?getPatientCountSeriallyBySearchIndex(0):_.each($scope.search.searchTypes,function(searchType){_.isEmpty(searchType)||$scope.search.searchType!=searchType&&getPatientCount(searchType,null)}),null!=$rootScope.currentSearchType&&$scope.search.switchSearchType($rootScope.currentSearchType),configurationService.getConfigurations(["identifierTypesConfig"]).then(function(response){$scope.primaryIdentifier=_.find(response.identifierTypesConfig,{primary:!0}).name})};$scope.searchPatients=function(){return spinner.forPromise(patientService.search($scope.search.searchParameter)).then(function(response){$scope.search.updateSearchResults(response.data.pageOfResults),$scope.search.hasSingleActivePatient()&&$scope.forwardPatient($scope.search.activePatients[0])})},$scope.filterPatientsAndSubmit=function(){1==$scope.search.searchResults.length&&$scope.forwardPatient($scope.search.searchResults[0])};var getPatientCount=function(searchType,patientListSpinner){if(searchType.handler){var params={q:searchType.handler,v:"full",location_uuid:$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName).uuid,provider_uuid:$rootScope.currentProvider.uuid};searchType.additionalParams&&(params.additionalParams=searchType.additionalParams),patientService.findPatients(params).then(function(response){searchType.patientCount=response.data.length,$scope.search.isSelectedSearch(searchType)&&$scope.search.updatePatientList(response.data),patientListSpinner&&hideSpinner(spinner,patientListSpinner,$(".tab-content"))})}},hideSpinner=function(spinnerObj,data,container){spinnerObj.hide(data,container),$(container).children("patient-list-spinner").hide()};$scope.getHeadings=function(patients){if(patients&&patients.length>0){var headings=_.chain(patients[0]).keys().filter(function(heading){return _.indexOf(Bahmni.Common.PatientSearch.Constants.tabularViewIgnoreHeadingsList,heading)===-1}).value();return headings}return[]},$scope.isHeadingOfLinkColumn=function(heading){var identifierHeading=_.includes(Bahmni.Common.PatientSearch.Constants.identifierHeading,heading);return identifierHeading?identifierHeading:$scope.search.searchType&&$scope.search.searchType.links?_.find($scope.search.searchType.links,{linkColumn:heading}):$scope.search.searchType&&$scope.search.searchType.linkColumn?_.includes([$scope.search.searchType.linkColumn],heading):void 0},$scope.isHeadingOfName=function(heading){return _.includes(Bahmni.Common.PatientSearch.Constants.nameHeading,heading)},$scope.getPrintableHeadings=function(patients){var headings=$scope.getHeadings(patients),printableHeadings=headings.filter(function(heading){return _.indexOf(Bahmni.Common.PatientSearch.Constants.printIgnoreHeadingsList,heading)===-1});return printableHeadings},$scope.printPage=function(){null!=$scope.search.searchType.printHtmlLocation&&printer.printFromScope($scope.search.searchType.printHtmlLocation,$scope)};var mapExtensionToSearchType=function(appExtn){return{name:appExtn.label,display:appExtn.extensionParams.display,handler:appExtn.extensionParams.searchHandler,forwardUrl:appExtn.extensionParams.forwardUrl,id:appExtn.id,params:appExtn.extensionParams.searchParams,refreshTime:appExtn.extensionParams.refreshTime||0,view:appExtn.extensionParams.view||Bahmni.Common.PatientSearch.Constants.searchExtensionTileViewType,showPrint:appExtn.extensionParams.showPrint||!1,printHtmlLocation:appExtn.extensionParams.printHtmlLocation||null,additionalParams:appExtn.extensionParams.additionalParams,searchColumns:appExtn.extensionParams.searchColumns,translationKey:appExtn.extensionParams.translationKey,linkColumn:appExtn.extensionParams.linkColumn,links:appExtn.extensionParams.links}},debounceGetPatientCount=_.debounce(function(currentSearchType,patientListSpinner){getPatientCount(currentSearchType,patientListSpinner)},patientSearchConfig&&patientSearchConfig.fetchDelay||DEFAULT_FETCH_DELAY,{}),showSpinner=function(spinnerObj,container){return $(container).children("patient-list-spinner").show(),spinnerObj.show(container)},fetchPatients=function(currentSearchType){void 0!==patientListSpinner&&hideSpinner(spinner,patientListSpinner,$(".tab-content")),$rootScope.currentSearchType=currentSearchType,$scope.search.isCurrentSearchLookUp()&&(patientListSpinner=showSpinner(spinner,$(".tab-content")),patientSearchConfig&&patientSearchConfig.debounceSearch?debounceGetPatientCount(currentSearchType,patientListSpinner):getPatientCount(currentSearchType,patientListSpinner))};$scope.forwardPatient=function(patient,heading){var options=$.extend({},$stateParams);$rootScope.patientAdmitLocationStatus=patient.Status,$.extend(options,{patientUuid:patient.uuid,
visitUuid:patient.activeVisitUuid||null,encounterUuid:$stateParams.encounterUuid||"active",programUuid:patient.programUuid||null,enrollment:patient.enrollment||null,forwardUrl:patient.forwardUrl||null,dateEnrolled:patient.dateEnrolled||null});var link=options.forwardUrl?{url:options.forwardUrl,newTab:!0}:{url:$scope.search.searchType.forwardUrl,newTab:!1};$scope.search.searchType.links&&(link=_.find($scope.search.searchType.links,{linkColumn:heading})||link),link.url&&null!==link.url&&$window.open(appService.getAppDescriptor().formatUrl(link.url,options,!0),link.newTab?"_blank":"_self")};var getPatientCountSeriallyBySearchIndex=function(index){if(index!==$scope.search.searchTypes.length){var searchType=$scope.search.searchTypes[index];if(searchType.handler){var params={q:searchType.handler,v:"full",location_uuid:$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName).uuid,provider_uuid:$rootScope.currentProvider.uuid};searchType.additionalParams&&(params.additionalParams=searchType.additionalParams),patientService.findPatients(params).then(function(response){return searchType.patientCount=response.data.length,$scope.search.isSelectedSearch(searchType)&&$scope.search.updatePatientList(response.data),getPatientCountSeriallyBySearchIndex(index+1)})}}};initialize()}]),angular.module("bahmni.common.uiHelper",["ngClipboard"]),angular.module("bahmni.common.uiHelper").service("backlinkService",["$window",function($window){var self=this,urls=[];self.reset=function(){urls=[]},self.setUrls=function(backLinks){self.reset(),angular.forEach(backLinks,function(backLink){self.addUrl(backLink)})},self.addUrl=function(backLink){urls.push(backLink)},self.addBackUrl=function(label){var backLabel=label||"Back";urls.push({label:backLabel,action:$window.history.back})},self.getUrlByLabel=function(label){return urls.filter(function(url){return url.label===label})},self.getAllUrls=function(){return urls}}]),angular.module("bahmni.common.uiHelper").service("contextChangeHandler",["$rootScope",function($rootScope){var callbacks=[],self=this;$rootScope.$on("$stateChangeSuccess",function(){self.reset()}),this.reset=function(){callbacks=[]},this.add=function(callback){callbacks.push(callback)},this.execute=function(){var allow=!0,callBackReturn=null,errorMessage=null;return callbacks.forEach(function(callback){callBackReturn=callback(),allow=allow&&callBackReturn.allow,_.isEmpty(errorMessage)&&(errorMessage=callBackReturn.errorMessage)}),callBackReturn&&errorMessage?{allow:allow,errorMessage:errorMessage}:{allow:allow}}}]),angular.module("bahmni.common.uiHelper").directive("bmPopOver",function(){var controller=function($scope){$scope.targetElements=[];var hideTargetElements=function(){$scope.targetElements.forEach(function(el){el.hide()})},showTargetElements=function(){$scope.targetElements.forEach(function(el){el.show()})};this.registerTriggerElement=function(triggerElement){$scope.triggerElement=triggerElement;var docClickHandler=function(){$scope.autoclose&&(hideTargetElements(),$scope.isTargetOpen=!1,$(document).off("click",docClickHandler))};$scope.triggerElement.on("click",function(event){$scope.isTargetOpen?($scope.isTargetOpen=!1,hideTargetElements(0),$(document).off("click",docClickHandler)):($scope.isTargetOpen=!0,showTargetElements(),$(document).on("click",docClickHandler),event.stopImmediatePropagation())}),$scope.$on("$destroy",function(){$(document).off("click",docClickHandler)})},this.registerTargetElement=function(targetElement){targetElement.hide(),$scope.targetElements.push(targetElement)};var hideOrShowTargetElements=function(){$scope.isTargetOpen&&($scope.isTargetOpen=!1,hideTargetElements(0))};$(document).on("click",".reg-wrapper",hideOrShowTargetElements),$scope.$on("$destroy",function(){$(document).off("click",".reg-wrapper",hideOrShowTargetElements)})};return{restrict:"A",controller:controller,scope:{autoclose:"="}}}).directive("bmPopOverTarget",function(){var link=function($scope,element,attrs,popOverController){popOverController.registerTargetElement(element)};return{restrict:"A",require:"^bmPopOver",link:link}}).directive("bmPopOverTrigger",function(){var link=function($scope,element,attrs,popOverController){popOverController.registerTriggerElement(element)};return{restrict:"A",require:"^bmPopOver",link:link}}),angular.module("bahmni.common.uiHelper").directive("splitButton",["$timeout",function($timeout){var controller=function($scope){$scope.primaryOption=$scope.primaryOption||$scope.options[0],$scope.secondaryOptions=_.without($scope.options,$scope.primaryOption),$scope.hasMultipleOptions=function(){return $scope.secondaryOptions.length>0}},link=function(scope,element){var shouldScroll=function(elementPosition,elementHeight){var windowHeight=window.innerHeight+$(window).scrollTop();return windowHeight<elementHeight+elementPosition};scope.scrollToBottom=function(){var timeout=$timeout(function(){var scrollHeight=$(element)[0].scrollHeight;shouldScroll(element.position().top,scrollHeight)&&(window.scrollBy(0,scrollHeight),$timeout.cancel(timeout))})}};return{restrict:"A",template:'<div class="split-button" bm-pop-over><button bm-pop-over-trigger class="toggle-button fa fa-caret-down" ng-show="::hasMultipleOptions()" ng-click="scrollToBottom()" ng-disabled="optionDisabled" type="button"></button><ul class="options"><li class="primaryOption"><button class="buttonClass" ng-click="optionClick()(primaryOption)" accesskey="{{::primaryOption.shortcutKey}}" ng-disabled="optionDisabled" ng-bind-html="::optionText()(primaryOption,\'primary\') | translate "></button></li><ul class="hidden-options"><li bm-pop-over-target ng-repeat="option in ::secondaryOptions" class="secondaryOption"><button class="buttonClass" ng-click="optionClick()(option)" accesskey="{{::option.shortcutKey}}" ng-disabled="optionDisabled" ng-bind-html="::optionText()(option) | translate"></button></li></ul></ul></div>',controller:controller,link:link,scope:{options:"=",primaryOption:"=",optionText:"&",optionClick:"&",optionDisabled:"="}}}]),angular.module("bahmni.common.uiHelper").directive("bmBackLinks",function(){return{template:'<ul><li ng-repeat="backLink in backLinks"><a class="back-btn" ng-if="backLink.action" accesskey="{{backLink.accessKey}}" ng-click="closeAllDialogs();backLink.action()" id="{{backLink.id}}"> <span ng-bind-html="backLink.label"></span> </a><a class="back-btn" ng-class="{\'dashboard-link\':backLink.image}" ng-if="backLink.url" accesskey="{{backLink.accessKey}}" ng-href="{{backLink.url}}" ng-click="closeAllDialogs()" id="{{backLink.id}}" title="{{backLink.title}}"> <img ng-if="backLink.image" ng-src="{{backLink.image}}" onerror="this.onerror=null; this.src=\'../images/blank-user.gif\'"/><i ng-if="backLink.icon && !backLink.image" class="fa {{backLink.icon}}"></i></a><a class="back-btn" ng-if="backLink.state && !backLink.text" accesskey="{{backLink.accessKey}}" ui-sref="{{backLink.state}}" ng-click="displayConfirmationDialog($event);closeAllDialogs()" id="{{backLink.id}}"><i ng-if="backLink.icon" class="fa {{backLink.icon}}"></i></a><a ng-if="backLink.text && backLink.requiredPrivilege" show-if-privilege="{{backLink.requiredPrivilege}}" accesskey="{{backLink.accessKey}}" ui-sref="{{backLink.state}}" id="{{backLink.id}}" class="back-btn-noIcon" ui-sref-active="active"><span>{{backLink.text | translate}}</span> </a><a ng-if="backLink.text && !backLink.requiredPrivilege" accesskey="{{backLink.accessKey}}" ui-sref="{{backLink.state}}" id="{{backLink.id}}" class="back-btn-noIcon" ui-sref-active="active"><span>{{backLink.text | translate}}</span> </a></li></ul>',controller:function($scope,backlinkService){$scope.backLinks=backlinkService.getAllUrls(),$scope.$on("$stateChangeSuccess",function(event,state){state.data&&state.data.backLinks&&(backlinkService.setUrls(state.data.backLinks),$scope.backLinks=backlinkService.getAllUrls())}),$scope.$on("$destroy",function(){window.onbeforeunload=void 0})},restrict:"E"}}),angular.module("bahmni.common.uiHelper").directive("focusOn",["$timeout",function($timeout){return function(scope,elem,attrs){Modernizr.ios||scope.$watch(attrs.focusOn,function(value){value&&$timeout(function(){$(elem).focus()})})}}]),angular.module("bahmni.common.uiHelper").directive("bmShow",["$rootScope",function($rootScope){var link=function($scope,element){$scope.$watch("bmShow",function(){$rootScope.isBeingPrinted||$scope.bmShow?element.removeClass("ng-hide"):element.addClass("ng-hide")})};return{scope:{bmShow:"="},link:link}}]),angular.module("bahmni.common.uiHelper").factory("spinner",["messagingService","$timeout",function(messagingService,$timeout){var tokens=[],topLevelDiv=function(element){return $(element).find("div").eq(0)},showSpinnerForElement=function(element){return 0===$(element).find(".dashboard-section-loader").length&&topLevelDiv(element).addClass("spinnable").append('<div class="dashboard-section-loader"></div>'),{element:$(element).find(".dashboard-section-loader")}},showSpinnerForOverlay=function(){var token=Math.random();tokens.push(token),0===$("#overlay").length&&$("body").prepend('<div id="overlay"><div></div></div>');var spinnerElement=$("#overlay");return spinnerElement.stop().show(),{element:spinnerElement,token:token}},show=function(element){return void 0!==element?showSpinnerForElement(element):showSpinnerForOverlay()},hide=function(spinner,parentElement){var spinnerElement=spinner.element;spinner.token?(_.pull(tokens,spinner.token),0===tokens.length&&spinnerElement.fadeOut(300)):(topLevelDiv(parentElement).removeClass("spinnable"),spinnerElement&&spinnerElement.remove())},forPromise=function(promise,element){return $timeout(function(){var spinner=show(element);return promise.finally(function(){hide(spinner,element)}),promise})},forAjaxPromise=function(promise,element){var spinner=show(element);return promise.always(function(){hide(spinner,element)}),promise};return{forPromise:forPromise,forAjaxPromise:forAjaxPromise,show:show,hide:hide}}]),angular.module("bahmni.common.uiHelper").factory("printer",["$rootScope","$compile","$http","$timeout","$q","spinner",function($rootScope,$compile,$http,$timeout,$q,spinner){var printHtml=function(html){var deferred=$q.defer(),hiddenFrame=$('<iframe style="visibility: hidden"></iframe>').appendTo("body")[0];hiddenFrame.contentWindow.printAndRemove=function(){hiddenFrame.contentWindow.print(),$(hiddenFrame).remove(),deferred.resolve()};var htmlContent='<!doctype html><html><body onload="printAndRemove();">'+html+"</body></html>",doc=hiddenFrame.contentWindow.document.open("text/html","replace");return doc.write(htmlContent),doc.close(),deferred.promise},print=function(templateUrl,data){$rootScope.isBeingPrinted=!0,$http.get(templateUrl).then(function(templateData){var template=templateData.data,printScope=$rootScope.$new();angular.extend(printScope,data);var element=$compile($("<div>"+template+"</div>"))(printScope),renderAndPrintPromise=$q.defer(),waitForRenderAndPrint=function(){return printScope.$$phase||$http.pendingRequests.length?$timeout(waitForRenderAndPrint,1e3):(printHtml(element.html()).then(function(){$rootScope.isBeingPrinted=!1,renderAndPrintPromise.resolve()}),printScope.$destroy()),renderAndPrintPromise.promise};spinner.forPromise(waitForRenderAndPrint())})},printFromScope=function(templateUrl,scope,afterPrint){$rootScope.isBeingPrinted=!0,$http.get(templateUrl).then(function(response){var template=response.data,printScope=scope,element=$compile($("<div>"+template+"</div>"))(printScope),renderAndPrintPromise=$q.defer(),waitForRenderAndPrint=function(){return printScope.$$phase||$http.pendingRequests.length?$timeout(waitForRenderAndPrint):printHtml(element.html()).then(function(){$rootScope.isBeingPrinted=!1,afterPrint&&afterPrint(),renderAndPrintPromise.resolve()}),renderAndPrintPromise.promise};spinner.forPromise(waitForRenderAndPrint())})};return{print:print,printFromScope:printFromScope}}]),angular.module("bahmni.common.uiHelper").directive("toggle",function(){var link=function($scope,element){$scope.toggle=void 0!==$scope.toggle&&$scope.toggle,$(element).click(function(){$scope.$apply(function(){$scope.toggle=!$scope.toggle})}),$scope.$watch("toggle",function(){$(element).toggleClass("active",$scope.toggle)}),$scope.$on("$destroy",function(){element.off("click")})};return{scope:{toggle:"="},link:link}}),angular.module("bahmni.common.uiHelper").filter("thumbnail",function(){return function(url,extension){if(url)return extension?Bahmni.Common.Constants.documentsPath+"/"+url.replace(/(.*)\.(.*)$/,"$1_thumbnail."+extension)||null:Bahmni.Common.Constants.documentsPath+"/"+url.replace(/(.*)\.(.*)$/,"$1_thumbnail.$2")||null}}),angular.module("bahmni.common.uiHelper").filter("days",function(){return function(startDate,endDate){return Bahmni.Common.Util.DateUtil.diffInDays(startDate,endDate)}}).filter("bahmniDateTime",function(){return function(date){return Bahmni.Common.Util.DateUtil.formatDateWithTime(date)}}).filter("bahmniDate",function(){return function(date){return Bahmni.Common.Util.DateUtil.formatDateWithoutTime(date)}}).filter("bahmniTime",function(){return function(date){return Bahmni.Common.Util.DateUtil.formatTime(date)}}).filter("bahmniDateInStrictMode",function(){return function(date){return Bahmni.Common.Util.DateUtil.formatDateInStrictMode(date)}}).filter("bahmniDateTimeWithFormat",function(){return function(date,format){return Bahmni.Common.Util.DateUtil.getDateTimeInSpecifiedFormat(date,format)}}).filter("addDays",function(){return function(date,numberOfDays){return Bahmni.Common.Util.DateUtil.addDays(date,numberOfDays)}}),angular.module("bahmni.common.uiHelper").controller("MessageController",["$scope","messagingService",function($scope,messagingService){$scope.messages=messagingService.messages,$scope.getMessageText=function(level){var string="";return $scope.messages[level].forEach(function(message){string=string.concat(message.value)}),string},$scope.hideMessage=function(level){messagingService.hideMessages(level)},$scope.isErrorMessagePresent=function(){return $scope.messages.error.length>0},$scope.isInfoMessagePresent=function(){return $scope.messages.info.length>0}}]),angular.module("bahmni.common.uiHelper").service("messagingService",["$rootScope","$timeout",function($rootScope,$timeout){this.messages={error:[],info:[]};var self=this;$rootScope.$on("event:serverError",function(event,errorMessage){self.showMessage("error",errorMessage,"serverError")}),this.showMessage=function(level,message,errorEvent){var messageObject={value:"",isServerError:!1};messageObject.value=message,errorEvent?messageObject.isServerError=!0:"info"==level&&this.createTimeout("info",4e3);var index=_.findIndex(this.messages[level],function(msg){return msg.value==messageObject.value});index>=0&&this.messages[level].splice(index,1),this.messages[level].push(messageObject)},this.createTimeout=function(level,time){$timeout(function(){self.messages[level]=[]},time,!0)},this.hideMessages=function(level){self.messages[level].length=0},this.clearAll=function(){self.messages.error=[],self.messages.info=[]}}]),angular.module("bahmni.common.uiHelper").directive("monthyearpicker",["$translate",function($translate){var link=function($scope){var monthNames=$translate.instant("MONTHS");$scope.monthNames=monthNames.split(",");var getYearList=function(){for(var minYear=$scope.minYear?$scope.minYear:moment().toDate().getFullYear()-15,maxYear=$scope.maxYear?$scope.maxYear:moment().toDate().getFullYear()+5,yearList=[],i=maxYear;i>=minYear;i--)yearList.push(i);return yearList};$scope.years=getYearList();var valueCompletelyFilled=function(){return null!=$scope.selectedMonth&&null!=$scope.selectedYear},valueNotFilled=function(){return null==$scope.selectedMonth&&null==$scope.selectedYear},getCompleteDate=function(){var month=$scope.selectedMonth+1;return $scope.selectedYear+"-"+month+"-01"};if($scope.updateModel=function(){valueCompletelyFilled()?$scope.model=getCompleteDate():$scope.isValid()?$scope.model="":$scope.model="Invalid Date"},$scope.isValid=function(){return valueNotFilled()||valueCompletelyFilled()},$scope.illegalMonth=function(){return(void 0===$scope.selectedMonth||null===$scope.selectedMonth)&&null!==$scope.selectedYear&&void 0!==$scope.selectedYear},$scope.illegalYear=function(){return null!==$scope.selectedMonth&&void 0!==$scope.selectedMonth&&(void 0===$scope.selectedYear||null===$scope.selectedYear)},$scope.model){var date=moment($scope.model).toDate();$scope.selectedMonth=date.getMonth(),$scope.selectedYear=date.getFullYear()}};return{restrict:"E",link:link,scope:{observation:"=",minYear:"=",maxYear:"=",illegalValue:"=",model:"="},template:'<span><select ng-model=\'selectedMonth\' ng-class="{\'illegalValue\': illegalMonth() || illegalValue}" ng-change="updateModel()" ng-options="monthNames.indexOf(month) as month for month in monthNames" ><option value="">{{\'CHOOSE_MONTH_KEY\' | translate}}</option>></select></span><span><select ng-model=\'selectedYear\' ng-class="{\'illegalValue\': illegalYear() || illegalValue}" ng-change="updateModel()" ng-options="year as year for year in years"><option value="">{{\'CHOOSE_YEAR_KEY\' | translate}}</option>></select></span>'}}]),angular.module("bahmni.common.uiHelper").directive("providerDirective",function(){var template='<span><span ng-if=":: creatorName && providerName && (creatorName != providerName)">{{::creatorName}} {{"ON_BEHALF_OF_TRANSLATION_KEY"|translate}} </span>{{::providerName}} <span ng-if=":: providerDate"> {{::providerDate | bahmniTime}} </span></span>';return{restrict:"EA",replace:!0,scope:{creatorName:"@",providerName:"@",providerDate:"=?"},template:template}}),angular.module("bahmni.common.uiHelper").directive("compileHtml",["$compile",function($compile){return function(scope,element,attrs){scope.$watch(function(scope){return scope.$eval(attrs.compileHtml)},function(value){element.html(value),$compile(element.contents())(scope)})}}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Logging=Bahmni.Common.Logging||{},angular.module("bahmni.common.logging",[]),angular.module("bahmni.common.logging").config(["$provide",function($provide){$provide.decorator("$exceptionHandler",function($delegate,$injector,$window,$log){var logError=function(exception,cause){try{var messagingService=$injector.get("messagingService"),loggingService=$injector.get("loggingService"),errorMessage=exception.toString(),stackTrace=printStackTrace({e:exception}),errorDetails={timestamp:new Date,browser:$window.navigator.userAgent,errorUrl:$window.location.href,errorMessage:errorMessage,stackTrace:stackTrace,cause:cause||""};loggingService.log(errorDetails),messagingService.showMessage("error",errorMessage),exposeException(errorDetails)}catch(loggingError){$log.warn("Error logging failed"),$log.log(loggingError)}},exposeException=function(exceptionDetails){window.angular_exception=window.angular_exception||[],window.angular_exception.push(exceptionDetails)};return function(exception,cause){$delegate(exception,cause),logError(exception,cause)}})}]),angular.module("bahmni.common.logging").service("loggingService",function(){var log=function(errorDetails){$.ajax({type:"POST",url:"/log",contentType:"application/json",data:angular.toJson(errorDetails)})};return{log:log}});var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Obs=Bahmni.Common.Obs||{},angular.module("bahmni.common.obs",[]),Bahmni.Common.Obs.Observation=function(){var Observation=function(obs,conceptConfig){angular.extend(this,obs),this.concept=obs.concept,this.conceptConfig=conceptConfig};return Observation.prototype={isFormElement:function(){return this.groupMembers&&this.groupMembers.length<=0},isImageConcept:function(){return"Image"===this.concept.conceptClass},isVideoConcept:function(){return"Video"===this.concept.conceptClass},hasPDFAsValue:function(){return this.value.indexOf(".pdf")>0},isComplexConcept:function(){return"Complex"===this.concept.dataType},getComplexDataType:function(){return this.complexData?this.complexData.dataType:null},isLocationRef:function(){return this.isComplexConcept()&&"Location"===this.getComplexDataType()},isProviderRef:function(){return this.isComplexConcept()&&"Provider"===this.getComplexDataType()},getDisplayValue:function(){var value;if("Boolean"===this.type||this.concept&&"Boolean"===this.concept.dataType)return this.value===!0?"OBS_BOOLEAN_YES_KEY":"OBS_BOOLEAN_NO_KEY";if("Datetime"===this.type||this.concept&&"Datetime"===this.concept.dataType){var date=Bahmni.Common.Util.DateUtil.parseDatetime(this.value);return null!=date?Bahmni.Common.Util.DateUtil.formatDateWithTime(date):""}if(this.conceptConfig&&this.conceptConfig.displayMonthAndYear&&(value=Bahmni.Common.Util.DateUtil.getDateInMonthsAndYears(this.value),null!=value))return value;if("Date"===this.type||this.concept&&"Date"===this.concept.dataType)return this.value?Bahmni.Common.Util.DateUtil.formatDateWithoutTime(this.value):"";if(this.isLocationRef())return this.complexData.display;if(this.isProviderRef())return this.complexData.display;value=this.value;var displayValue=value&&(value.shortName||value.name&&(value.name.name||value.name)||value);return this.duration&&(displayValue=displayValue+" "+this.getDurationDisplayValue()),displayValue},getDurationDisplayValue:function(){var durationForDisplay=Bahmni.Common.Util.DateUtil.convertToUnits(this.duration);return"since "+durationForDisplay.value+" "+durationForDisplay.unitName}},Observation}(),Bahmni.Common.Obs.MultiSelectObservation=function(){var MultiSelectObservation=function(groupMembers,conceptConfig){this.type="multiSelect",this.concept=groupMembers[0].concept,this.encounterDateTime=groupMembers[0].encounterDateTime,this.groupMembers=groupMembers,this.conceptConfig=conceptConfig,this.observationDateTime=getLatestObservationDateTime(this.groupMembers),this.providers=groupMembers[0].providers,this.creatorName=groupMembers[0].creatorName},getLatestObservationDateTime=function(groupMembers){var latestObservationDateTime=groupMembers[0].observationDateTime;return groupMembers.forEach(function(member){latestObservationDateTime=latestObservationDateTime<member.observationDateTime?member.observationDateTime:latestObservationDateTime}),latestObservationDateTime};return MultiSelectObservation.prototype={isFormElement:function(){return!0},getDisplayValue:function(){var getName=Bahmni.Common.Domain.ObservationValueMapper.getNameFor.Object;return _.map(this.groupMembers,getName).join(", ")}},MultiSelectObservation}(),Bahmni.Common.Obs.GridObservation=function(){var conceptMapper=new Bahmni.Common.Domain.ConceptMapper,GridObservation=function(obs,conceptConfig){angular.extend(this,obs),this.type="grid",this.conceptConfig=conceptConfig},getObservationDisplayValue=function(observation){if(observation.isBoolean||"Boolean"===observation.type)return observation.value===!0?"OBS_BOOLEAN_YES_KEY":"OBS_BOOLEAN_NO_KEY";if(!observation.value)return"";if("object"==typeof observation.value.name){var valueConcept=conceptMapper.map(observation.value);return valueConcept.shortName||valueConcept.name}return observation.value.shortName||observation.value.name||observation.value};return GridObservation.prototype={isFormElement:function(){return!0},getDisplayValue:function(){var gridObservationDisplayValue=_.compact(_.map(this.groupMembers,function(member){return getObservationDisplayValue(member)})).join(", ");return gridObservationDisplayValue||this.value}},GridObservation}(),Bahmni.Common.Obs.ObservationMapper=function(){var conceptMapper=new Bahmni.Common.Domain.ConceptMapper;this.map=function(bahmniObservations,allConceptsConfig,dontSortByObsDateTime){var mappedObservations=mapObservations(bahmniObservations,allConceptsConfig,dontSortByObsDateTime);return mapUIObservations(mappedObservations,allConceptsConfig)};var mapObservations=function(bahmniObservations,allConceptsConfig,dontSortByObsDateTime){var mappedObservations=[];return bahmniObservations=dontSortByObsDateTime?_.flatten(bahmniObservations):Bahmni.Common.Obs.ObservationUtil.sortSameConceptsWithObsDateTime(bahmniObservations),$.each(bahmniObservations,function(i,bahmniObservation){var conceptConfig=bahmniObservation.formFieldPath?[]:allConceptsConfig[bahmniObservation.concept.name]||[],observation=new Bahmni.Common.Obs.Observation(bahmniObservation,conceptConfig);observation.groupMembers&&observation.groupMembers.length>=0&&(observation.groupMembers=mapObservations(observation.groupMembers,allConceptsConfig,dontSortByObsDateTime)),mappedObservations.push(observation)}),mappedObservations},mapUIObservations=function(observations,allConceptsConfig){var groupedObservations=_.groupBy(observations,function(observation){return observation.formFieldPath+"#"+observation.concept.name}),mappedObservations=[];return $.each(groupedObservations,function(i,obsGroup){var conceptConfig=obsGroup[0].formFieldPath?[]:allConceptsConfig[obsGroup[0].concept.name]||[];if(conceptConfig.multiSelect){var multiSelectObservations={};$.each(obsGroup,function(i,observation){if(multiSelectObservations[observation.encounterDateTime])multiSelectObservations[observation.encounterDateTime].push(observation);else{var observations=[];observations.push(observation),multiSelectObservations[observation.encounterDateTime]=observations}}),$.each(multiSelectObservations,function(i,observations){mappedObservations.push(new Bahmni.Common.Obs.MultiSelectObservation(observations,conceptConfig))})}else conceptConfig.grid?mappedObservations.push(new Bahmni.Common.Obs.GridObservation(obsGroup[0],conceptConfig)):$.each(obsGroup,function(i,obs){obs.groupMembers=mapUIObservations(obs.groupMembers,allConceptsConfig),mappedObservations.push(obs)})}),mappedObservations};this.getGridObservationDisplayValue=function(observationTemplate){var memberValues=_.compact(_.map(observationTemplate.bahmniObservations,function(observation){return getObservationDisplayValue(observation)}));return memberValues.join(", ")};var getObservationDisplayValue=function(observation){if(observation.isBoolean||"Boolean"===observation.type)return observation.value===!0?"Yes":"No";if(!observation.value)return"";if("object"==typeof observation.value.name){var valueConcept=conceptMapper.map(observation.value);return valueConcept.shortName||valueConcept.name}return observation.value.shortName||observation.value.name||observation.value}},angular.module("bahmni.common.obs").directive("showObservation",["ngDialog",function(ngDialog){var controller=function($scope,$rootScope,$filter){$scope.toggle=function(observation){observation.showDetails=!observation.showDetails},$scope.print=$rootScope.isBeingPrinted||!1,$scope.dateString=function(observation){var filterName;if($scope.showDate&&$scope.showTime)filterName="bahmniDateTime";else{if($scope.showDate||!$scope.showTime&&void 0!==$scope.showTime)return null;filterName="bahmniTime"}return $filter(filterName)(observation.observationDateTime)},$scope.openVideoInPopup=function(observation){ngDialog.open({template:"../common/obs/views/showVideo.html",closeByDocument:!1,className:"ngdialog-theme-default",showClose:!0,data:{observation:observation}})}};return{restrict:"E",scope:{observation:"=?",patient:"=",showDate:"=?",showTime:"=?",showDetailsButton:"=?"},controller:controller,template:"<ng-include src=\"'../common/obs/views/showObservation.html'\" />"}}]),Bahmni.Common.Obs.ObservationUtil=function(){var sortSameConceptsWithObsDateTime=function(observation){for(var sortedObservations=[],i=0;i<observation.length;i++)if(i!==observation.length-1)if(observation[i].conceptUuid!==observation[i+1].conceptUuid)sortedObservations.push(observation[i]);else{var sameConceptsSubArray=[],j=i+1;for(sameConceptsSubArray.push(observation[i]);j<observation.length&&observation[i].conceptUuid===observation[j].conceptUuid;)sameConceptsSubArray.push(observation[j++]);sameConceptsSubArray=_.sortBy(sameConceptsSubArray,"observationDateTime"),sortedObservations.push(sameConceptsSubArray),i=j-1}else sortedObservations.push(observation[i]);return _.flatten(sortedObservations)},getValue=function(observation){if(observation.selectedObs)return observation.getValues();var obsValue;return obsValue=observation.value&&observation.value.name&&observation.value.name.name?observation.value.name.name:observation.value&&observation.value.name&&!observation.value.name.name?observation.value.name:observation.value,void 0===obsValue||null===obsValue?obsValue:obsValue.displayString||obsValue},collect=function(flattenedObservations,key,value){void 0!=value&&(flattenedObservations[key]=flattenedObservations[key]?_.uniq(_.flatten(_.union([flattenedObservations[key]],[value]))):value)},findLeafObservations=function(flattenedObservations,observation){_.isEmpty(observation.groupMembers)?collect(flattenedObservations,observation.concept.name,getValue(observation)):_.each(observation.groupMembers,function(member){findLeafObservations(flattenedObservations,member)})},flatten=function(observation){var flattenedObservation={};return _.isEmpty(observation)||findLeafObservations(flattenedObservation,observation),flattenedObservation},flattenObsToArray=function(observations){var flattened=[];return flattened.push.apply(flattened,observations),observations.forEach(function(obs){obs.groupMembers&&obs.groupMembers.length>0&&flattened.push.apply(flattened,flattenObsToArray(obs.groupMembers))}),flattened};return{sortSameConceptsWithObsDateTime:sortSameConceptsWithObsDateTime,flatten:flatten,flattenObsToArray:flattenObsToArray}}();var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.DisplayControl=Bahmni.Common.DisplayControl||{},Bahmni.Common.DisplayControl.Dashboard=Bahmni.Common.DisplayControl.Dashboard||{},angular.module("bahmni.common.displaycontrol.dashboard",[]),angular.module("bahmni.common.displaycontrol.dashboard").directive("dashboard",[function(){var controller=function($scope,$filter){var init=function(){$scope.dashboard=Bahmni.Common.DisplayControl.Dashboard.create($scope.config||{},$filter)},checkDisplayType=function(sections,typeToCheck,index){return sections[index]&&sections[index].displayType&&sections[index].displayType===typeToCheck},isDisplayTypeWrong=function(sections){var allDisplayTypes=["Full-Page","LAYOUT_75_25","LAYOUT_25_75","Half-Page"];return allDisplayTypes.indexOf(sections[0].displayType)<=-1};$scope.isFullPageSection=function(sections){return checkDisplayType(sections,"Full-Page",0)},$scope.hasThreeFourthPageSection=function(sections,index){return checkDisplayType(sections,"LAYOUT_75_25",index)},$scope.isOneFourthPageSection=function(sections){return checkDisplayType(sections,"LAYOUT_25_75",0)},$scope.isHalfPageSection=function(sections){return sections[0]&&(checkDisplayType(sections,"Half-Page",0)||isDisplayTypeWrong(sections)||!sections[0].displayType)},$scope.containsThreeFourthPageSection=function(sections){var hasThreeFourthSection=this.hasThreeFourthPageSection(sections,0)||this.hasThreeFourthPageSection(sections,1);return 1==sections.length?this.hasThreeFourthPageSection(sections,0):hasThreeFourthSection},$scope.filterOdd=function(index){return function(){return index++%2===0}},$scope.filterEven=function(index){return function(){return index++%2===1}};var unbindWatch=$scope.$watch("config",init);$scope.$on("$stateChangeStart",unbindWatch)};return{restrict:"E",controller:controller,templateUrl:"../common/displaycontrols/dashboard/views/dashboard.html",scope:{config:"=",patient:"=",diseaseTemplates:"=",sectionGroups:"=",visitHistory:"=",activeVisitUuid:"=",visitSummary:"=",enrollment:"="}}}]),angular.module("bahmni.common.displaycontrol.dashboard").directive("dashboardSection",function(){var controller=function($scope){$scope.$on("no-data-present-event",function(){$scope.section.isDataAvailable=!$scope.section.hideEmptyDisplayControl})};return{restrict:"E",controller:controller,templateUrl:"../common/displaycontrols/dashboard/views/dashboardSection.html"}}),Bahmni.Common.DisplayControl.Dashboard=function(config,$filter){(config.startDate||config.endDate)&&_.each(config.sections,function(section){
section.startDate=config.startDate,section.endDate=config.endDate});var _sections=_.sortBy(_.map(config.sections,function(section){return Bahmni.Common.DisplayControl.Dashboard.Section.create(section,$filter)}),function(section){return section.displayOrder});this.getSectionByType=function(name){return _.find(_sections,function(section){return section.type===name})||{}},this.getSections=function(diseaseTemplates){var sections=_.filter(_sections,function(section){return"diseaseTemplate"!==section.type||_.find(diseaseTemplates,function(diseaseTemplate){return diseaseTemplate.name===section.templateName&&diseaseTemplate.obsTemplates.length>0})});return this.groupSectionsByType(sections)},this.groupSectionsByType=function(sections){var sectionGroups=[[]];for(var sectionId in sections){var section=sections[sectionId],nextSection=sectionId<sections.length?sections[++sectionId]:null,lastElement=sectionGroups.length-1;this.isFullPageSection(section)?(_.isEmpty(sectionGroups[lastElement])&&sectionGroups.pop(),sectionGroups.push([section]),sectionGroups.push([])):sectionGroups=this.groupSectionsIfNotFullPage(section,sectionGroups,lastElement,nextSection)}return sectionGroups},this.isFullPageSection=function(section){return this.checkDisplayType(section,"Full-Page")},this.isThreeFourthPageSection=function(section){return this.checkDisplayType(section,"LAYOUT_75_25")},this.isOneFourthPageSection=function(section){return this.checkDisplayType(section,"LAYOUT_25_75")},this.isHalfPageSection=function(section){return this.checkDisplayType(section,"Half-Page")||this.isDisplayTypeWrong(section)||!section.displayType},this.isDisplayTypeWrong=function(section){var allDisplayTypes=["Full-Page","LAYOUT_75_25","LAYOUT_25_75","Half-Page"];return allDisplayTypes.indexOf(section.displayType)<=-1},this.checkDisplayType=function(section,typeToCheck){return section&&section.displayType&&section.displayType===typeToCheck},this.groupSectionsIfNotFullPage=function(section,sectionGroups,lastElement,nextSection){var lastSection=sectionGroups[lastElement],lastSectionIndex=_.isEmpty(lastSection)?0:lastSection.length-1;return sectionGroups=this.isThreeFourthPageSection(section)?this.groupThreeFourthPageSection(lastSection,lastElement,lastSectionIndex,section,sectionGroups):this.isOneFourthPageSection(section)?this.groupOneFourthPageSection(lastSection,lastElement,lastSectionIndex,section,sectionGroups,nextSection):this.groupHalfPageSection(lastSection,lastElement,lastSectionIndex,section,sectionGroups)},this.groupThreeFourthPageSection=function(lastSection,lastElement,lastSectionIndex,section,sectionGroups){var lastSectionLength=lastSection.length,isLastSectionOneFourth=1==lastSectionLength&&this.isOneFourthPageSection(lastSection[lastSectionIndex]);return _.isEmpty(lastSection)||isLastSectionOneFourth?sectionGroups[lastElement].push(section):sectionGroups.push([section]),sectionGroups},this.groupOneFourthPageSection=function(lastSection,lastElement,lastSectionIndex,section,sectionGroups,nextSection){return this.addOneFourthElementToLastSection(lastSection,lastElement,lastSectionIndex,nextSection)?sectionGroups[lastElement].push(section):sectionGroups.push([section]),sectionGroups},this.addOneFourthElementToLastSection=function(lastSection,lastElement,lastSectionIndex,nextSection){var lastSectionLength=lastSection.length,isNextSectionThreeFourth=!!nextSection&&this.isThreeFourthPageSection(nextSection),isLastSectionNotThreeFourth=!this.isThreeFourthPageSection(lastSection[lastSectionIndex])&&!this.isThreeFourthPageSection(lastSection[0]);return lastSection.length<=1&&(this.isThreeFourthPageSection(lastSection[0])||!isNextSectionThreeFourth)||lastSectionLength>=2&&isLastSectionNotThreeFourth&&!isNextSectionThreeFourth},this.groupHalfPageSection=function(lastSection,lastElement,lastSectionIndex,section,sectionGroups){var lastSectionLength=lastSection.length,isLastSectionNotThreeFourth=!this.isThreeFourthPageSection(lastSection[lastSectionIndex])&&!this.isThreeFourthPageSection(lastSection[0]);return _.isEmpty(lastSection)||lastSectionLength>2||isLastSectionNotThreeFourth?sectionGroups[lastElement].push(section):sectionGroups.push([section]),sectionGroups}},Bahmni.Common.DisplayControl.Dashboard.create=function(config,$filter){return new Bahmni.Common.DisplayControl.Dashboard(config,$filter)},function(){var OBSERVATION_SECTION_URL="../common/displaycontrols/dashboard/views/sections/observationSection.html",COMMON_DISPLAY_CONTROL_URL="../common/displaycontrols/dashboard/views/sections/SECTION_NAME.html",CLINICAL_DISPLAY_CONTROL_URL="../clinical/dashboard/views/dashboardSections/SECTION_NAME.html",commonDisplayControlNames=["admissionDetails","bacteriologyResultsControl","chronicTreatmentChart","custom","diagnosis","disposition","drugOrderDetails","forms","formsV2","observationGraph","obsToObsFlowSheet","pacsOrders","patientInformation","conditionsList"],getViewUrl=function(section){if(section.isObservation)return OBSERVATION_SECTION_URL;var isCommonDisplayControl=_.includes(commonDisplayControlNames,section.type);return isCommonDisplayControl?COMMON_DISPLAY_CONTROL_URL.replace("SECTION_NAME",section.type):CLINICAL_DISPLAY_CONTROL_URL.replace("SECTION_NAME",section.type)},getId=function(section,$filter){if("custom"!==section.type){var key=section.translationKey||section.title;return!_.isUndefined($filter)&&key?$filter("titleTranslate")(key).toValidId():key}};Bahmni.Common.DisplayControl.Dashboard.Section=function(section,$filter){angular.extend(this,section),this.displayOrder=section.displayOrder,this.data=section.data||{},this.isObservation=!!section.isObservation,this.patientAttributes=section.patientAttributes||[],this.viewName=getViewUrl(this),this.hideEmptyDisplayControl=void 0!=section.hideEmptyDisplayControl&&section.hideEmptyDisplayControl,this.isDataAvailable=!0,this.id=getId(this,$filter)},Bahmni.Common.DisplayControl.Dashboard.Section.create=function(section,$filter){return new Bahmni.Common.DisplayControl.Dashboard.Section(section,$filter)}}(),angular.module("bahmni.common.displaycontrol.dashboard").controller("PatientDashboardDiagnosisController",["$scope","ngDialog",function($scope,ngDialog){$scope.section=$scope.dashboard.getSectionByType("diagnosis")||{},$scope.openSummaryDialog=function(){ngDialog.open({template:"../common/displaycontrols/dashboard/views/sections/diagnosisSummary.html",className:"ngdialog-theme-default ng-dialog-all-details-page",scope:$scope})};var cleanUpListener=$scope.$on("ngDialog.closing",function(){$("body").removeClass("ngdialog-open")});$scope.$on("$destroy",cleanUpListener)}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.DisplayControl=Bahmni.Common.DisplayControl||{},Bahmni.Common.DisplayControl.Observation=Bahmni.Common.DisplayControl.Observation||{},angular.module("bahmni.common.displaycontrol.observation",["bahmni.common.conceptSet","pascalprecht.translate"]),angular.module("bahmni.common.displaycontrol.observation").service("formHierarchyService",["formService",function(formService){var self=this;self.build=function(observations){var obs=self.preProcessMultipleSelectObsToObs(observations);obs=self.createDummyObsGroupForObservationsForForm(obs),self.createDummyObsGroupForSectionsForForm(obs)},self.preProcessMultipleSelectObsToObs=function(observations){return _.forEach(observations,function(obs){_.forEach(obs.value,function(value,index){"multiSelect"==value.type&&(obs.value.push(value.groupMembers[0]),obs.value.splice(index,1))})}),observations},self.createDummyObsGroupForObservationsForForm=function(observations){return _.forEach(observations,function(obs){var newValues=[];_.forEach(obs.value,function(value){if(!value.formFieldPath)return void newValues.push(value);var dummyObsGroup={groupMembers:[],concept:{shortName:"",conceptClass:null},encounterUuid:""};dummyObsGroup.concept.shortName=value.formFieldPath.split(".")[0],dummyObsGroup.encounterUuid=value.encounterUuid;var previousDummyObsGroupFound;_.forEach(newValues,function(newValue){dummyObsGroup.concept.shortName==newValue.concept.shortName&&(newValue.groupMembers.push(value),previousDummyObsGroupFound=!0)}),previousDummyObsGroupFound||(dummyObsGroup.groupMembers.push(value),newValues.push(dummyObsGroup))}),obs.value=newValues}),observations},self.getFormVersion=function(members){var formVersion;return _.forEach(members,function(member){if(member.formFieldPath)return formVersion=member.formFieldPath.split(".")[1].split("/")[0],!1}),formVersion},self.getMemberFromFormByFormFieldPath=function(members,id){return _.filter(members,function(member){return member.formFieldPath.split(".")[1].split("/")[1].split("-")[0]==id})},self.getFormByFormName=function(formList,formName,formVersion){return _.find(formList,function(form){return form.name==formName&&form.version==formVersion})},self.parseSection=function(members,controls,value){var sectionIsEmpty=!0;return _.forEach(controls,function(control){var dummyObsGroup={groupMembers:[],concept:{shortName:"",conceptClass:null}};if("section"==control.type)dummyObsGroup.concept.shortName=control.label.value,value.groupMembers.push(dummyObsGroup),self.parseSection(members,control.controls,dummyObsGroup)?sectionIsEmpty=!1:value.groupMembers.pop();else{var member=self.getMemberFromFormByFormFieldPath(members,control.id);0!=member.length&&(0!=member[0].formFieldPath.split("-")[1]&&_.reverse(member),_.map(member,function(m){value.groupMembers.push(m)}),sectionIsEmpty=!1)}}),sectionIsEmpty?null:value},self.createSectionForSingleForm=function(obsFromSameForm,formDetails){var members=obsFromSameForm.groupMembers.slice();return obsFromSameForm.groupMembers.splice(0,obsFromSameForm.groupMembers.length),self.parseSection(members,formDetails.controls,obsFromSameForm)},self.createDummyObsGroupForSectionsForForm=function(bahmniObservations){_.isEmpty(bahmniObservations)||formService.getAllForms().then(function(response){var allForms=response.data;_.forEach(bahmniObservations,function(observation){var forms=[];_.forEach(observation.value,function(form){if(form.concept.conceptClass)return void forms.push(form);var observationForm=self.getFormByFormName(allForms,form.concept.shortName,self.getFormVersion(form.groupMembers));observationForm&&formService.getFormDetail(observationForm.uuid,{v:"custom:(resources:(value))"}).then(function(response){var formDetailsAsString=_.get(response,"data.resources[0].value");if(formDetailsAsString){var formDetails=JSON.parse(formDetailsAsString);forms.push(self.createSectionForSingleForm(form,formDetails))}observation.value=forms})})})})}}]),angular.module("bahmni.common.displaycontrol.observation").service("formRecordTreeBuildService",["formService","$window",function(formService,$window){var self=this;self.formBuildFroms=[],self.build=function(bahmniObservations,hasNoHierarchy){_.forEach(bahmniObservations,function(obs){obs.value=self.preProcessMultiSelectObs(obs.value)}),hasNoHierarchy||formService.getAllForms().then(function(response){var formBuildFroms=response.data,obs=self.createObsGroupForForm(bahmniObservations,formBuildFroms);updateObservationsWithFormDefinition(obs,formBuildFroms)})},self.createMultiSelectObservation=function(observations){var multiSelectObject=new Bahmni.Common.Obs.MultiSelectObservation(observations,{multiSelect:!0});return multiSelectObject.formFieldPath=observations[0].formFieldPath,multiSelectObject.encounterUuid=observations[0].encounterUuid,multiSelectObject},self.preProcessMultiSelectObs=function(value){var clonedGroupMembers=_.cloneDeep(value);return _.forEach(clonedGroupMembers,function(member){if(member&&0===member.groupMembers.length){var obsWithSameFormFieldPath=self.getRecordObservations(member.formFieldPath,value);if(obsWithSameFormFieldPath.length>1){var multiSelectObject=self.createMultiSelectObservation(obsWithSameFormFieldPath);value.push(multiSelectObject)}else 1===obsWithSameFormFieldPath.length&&value.push(obsWithSameFormFieldPath[0])}else if(member.groupMembers.length>0){var obsGroups=self.getRecordObservations(member.formFieldPath,value);_.forEach(obsGroups,function(obsGroup){obsGroup.groupMembers=self.preProcessMultiSelectObs(obsGroup.groupMembers),value.push(obsGroup)})}}),value},self.createObsGroupForForm=function(observations,formBuilderFroms){return _.forEach(observations,function(obs){var newValues=[];_.forEach(obs.value,function(value){if(!value.formFieldPath)return void newValues.push(value);var obsGroup={groupMembers:[],concept:{shortName:"",conceptClass:null},encounterUuid:""},formName=value.formFieldPath.split(".")[0],formBuilderForm=formBuilderFroms.find(function(form){return form.name===formName});obsGroup.concept.shortName=formName;var locale=localStorage.getItem("NG_TRANSLATE_LANG_KEY")||"en",formNameTranslations=formBuilderForm&&formBuilderForm.nameTranslation?JSON.parse(formBuilderForm.nameTranslation):[];if(formNameTranslations.length>0){var currentLabel=formNameTranslations.find(function(formNameTranslation){return formNameTranslation.locale===locale});currentLabel&&(obsGroup.concept.shortName=currentLabel.display)}obsGroup.encounterUuid=value.encounterUuid;var previousObsGroupFound;_.forEach(newValues,function(newValue){obsGroup.concept.shortName===newValue.concept.shortName&&(newValue.groupMembers.push(value),previousObsGroupFound=!0)}),previousObsGroupFound||(obsGroup.groupMembers.push(value),newValues.push(obsGroup))}),obs.value=newValues}),observations};var updateObservationsWithFormDefinition=function(observations,formBuildFroms){var allForms=formBuildFroms;_.forEach(observations,function(observation){var forms=[];_.forEach(observation.value,function(form){if(form.concept.conceptClass)return void forms.push(form);var observationForm=self.getFormByFormName(allForms,self.getFormName(form.groupMembers),self.getFormVersion(form.groupMembers));observationForm&&formService.getFormDetail(observationForm.uuid,{v:"custom:(resources:(value))"}).then(function(response){var formDetailsAsString=_.get(response,"data.resources[0].value");if(formDetailsAsString){var formDef=JSON.parse(formDetailsAsString);formDef.version=observationForm.version;var locale=$window.localStorage.NG_TRANSLATE_LANG_KEY||"en";return formService.getFormTranslate(formDef.name,formDef.version,locale,formDef.uuid).then(function(response){var translationData=response.data;forms.push(self.updateObservationsWithRecordTree(formDef,form,translationData)),observation.value=forms})}observation.value=forms})})})};self.getFormByFormName=function(formList,formName,formVersion){return _.find(formList,function(form){return form.name===formName&&form.version===formVersion})},self.getFormName=function(members){var member=_.find(members,function(member){return null!==member.formFieldPath});return member?member.formFieldPath.split(".")[0]:void 0},self.getFormVersion=function(members){var member=_.find(members,function(member){return null!==member.formFieldPath});return member?member.formFieldPath.split(".")[1].split("/")[0]:void 0},self.updateObservationsWithRecordTree=function(formDef,form,translationData){var recordTree=getRecordTree(formDef,form.groupMembers);return recordTree=JSON.parse(JSON.stringify(recordTree)),self.createGroupMembers(recordTree,form,form.groupMembers,translationData),form},self.createColumnGroupsForTable=function(record,columns,tableGroup,obsList,translationData){_.forEach(columns,function(column,index){var obsGroup={groupMembers:[],concept:{shortName:"",conceptClass:null}},translationKey=column.translationKey,defaultShortName=column.value;obsGroup.concept.shortName=self.getTranslatedShortName(translationData,translationKey,obsGroup,defaultShortName);var columnRecord=self.getColumnObs(index,record);column.children=columnRecord,self.createGroupMembers(column,obsGroup,obsList,translationData),obsGroup.groupMembers.length>0&&tableGroup.groupMembers.push(obsGroup)})},self.getTranslatedShortName=function(translationData,translationKey,obsGroup,defaultShortName){return self.isTranslationKeyPresent(translationData,translationKey)?translationData.labels[translationKey][0]:defaultShortName},self.isTranslationKeyPresent=function(translationData,translationKey){return translationData&&translationData.labels&&translationData.labels[translationKey][0]!==translationKey},self.getColumnObs=function(columnIndex,record){var columnChildren=[];return _.map(record.children,function(child){child.control.properties&&child.control.properties.location.column===columnIndex&&columnChildren.push(child)}),columnChildren},self.createGroupMembers=function(recordTree,obsGroup,obsList,translationData){_.forEach(recordTree.children,function(record){if("obsControl"===record.control.type||"obsGroupControl"===record.control.type){var recordObservations=self.getRecordObservations(record.formFieldPath,obsList);_.forEach(recordObservations,function(recordObservation){obsGroup.groupMembers.push(recordObservation)})}else if("section"===record.control.type){var sectionGroup=self.createObsGroup(record,translationData);self.createGroupMembers(record,sectionGroup,obsList,translationData),sectionGroup.groupMembers.length>0&&obsGroup.groupMembers.push(sectionGroup)}else if("table"===record.control.type){var tableGroup=self.createObsGroup(record,translationData),columns=record.control.columnHeaders;self.createColumnGroupsForTable(record,columns,tableGroup,obsList,translationData),tableGroup.groupMembers.length>0&&obsGroup.groupMembers.push(tableGroup)}})},self.getTableColumns=function(record){return _.filter(record.control.columnHeaders,function(child){return"label"===child.type})},self.getRecordObservations=function(obsFormFieldPath,obsList){return _.remove(obsList,function(obs){return obs.formFieldPath&&obs.formFieldPath===obsFormFieldPath})},self.createObsGroup=function(record,translationData){var obsGroup={groupMembers:[],concept:{shortName:"",conceptClass:null}},translationKey=record.control.label.translationKey,defaultShortName=record.control.label.value;return obsGroup.concept.shortName=self.getTranslatedShortName(translationData,translationKey,obsGroup,defaultShortName),obsGroup}}]),angular.module("bahmni.common.displaycontrol.observation").directive("bahmniObservation",["encounterService","observationsService","appService","$q","spinner","$rootScope","formRecordTreeBuildService","$translate",function(encounterService,observationsService,appService,$q,spinner,$rootScope,formRecordTreeBuildService,$translate){var controller=function($scope){$scope.print=$rootScope.isBeingPrinted||!1,$scope.showGroupDateTime=$scope.config.showGroupDateTime!==!1;var mapObservation=function(observations){var conceptsConfig=$scope.config.formType===Bahmni.Common.Constants.forms2Type?{}:appService.getAppDescriptor().getConfigValue("conceptSetUI")||{};observations=(new Bahmni.Common.Obs.ObservationMapper).map(observations,conceptsConfig),$scope.config.conceptNames&&(observations=_.filter(observations,function(observation){return _.some($scope.config.conceptNames,function(conceptName){return _.toLower(conceptName)===_.toLower(_.get(observation,"concept.name"))})})),$scope.config.persistOrderOfConcepts?$scope.bahmniObservations=(new Bahmni.Common.DisplayControl.Observation.GroupingFunctions).persistOrderOfConceptNames(observations):$scope.bahmniObservations=(new Bahmni.Common.DisplayControl.Observation.GroupingFunctions).groupByEncounterDate(observations),_.isEmpty($scope.bahmniObservations)?($scope.noObsMessage=$translate.instant(Bahmni.Common.Constants.messageForNoObservation),$scope.$emit("no-data-present-event")):$scope.showGroupDateTime?$scope.bahmniObservations[0].isOpen=!0:_.forEach($scope.bahmniObservations,function(bahmniObs){bahmniObs.isOpen=!0});var formObservations=_.filter(observations,function(obs){return obs.formFieldPath});formObservations.length>0&&formRecordTreeBuildService.build($scope.bahmniObservations,$scope.hasNoHierarchy)},fetchObservations=function(){if($scope.config.formType===Bahmni.Common.Constants.formBuilderDisplayControlType){var getFormNameAndVersion=Bahmni.Common.Util.FormFieldPathUtil.getFormNameAndVersion;encounterService.findByEncounterUuid($scope.config.encounterUuid,{includeAll:!1}).then(function(reponse){var encounterTransaction=reponse.data,observationsForSelectedForm=_.filter(encounterTransaction.observations,function(obs){if(obs.formFieldPath){var obsFormNameAndVersion=getFormNameAndVersion(obs.formFieldPath);return obsFormNameAndVersion.formName===$scope.config.formName}});mapObservation(observationsForSelectedForm)}),$scope.title=$scope.config.formDisplayName}else if($scope.observations)mapObservation($scope.observations,$scope.config),$scope.isFulfilmentDisplayControl=!0;else if($scope.config.observationUuid)$scope.initialization=observationsService.getByUuid($scope.config.observationUuid).then(function(response){mapObservation([response.data],$scope.config)});else if($scope.config.encounterUuid){var fetchForEncounter=observationsService.fetchForEncounter($scope.config.encounterUuid,$scope.config.conceptNames);$scope.initialization=fetchForEncounter.then(function(response){mapObservation(response.data,$scope.config)})}else $scope.enrollment?$scope.initialization=observationsService.fetchForPatientProgram($scope.enrollment,$scope.config.conceptNames,$scope.config.scope,$scope.config.obsIgnoreList).then(function(response){mapObservation(response.data,$scope.config)}):$scope.initialization=observationsService.fetch($scope.patient.uuid,$scope.config.conceptNames,$scope.config.scope,$scope.config.numberOfVisits,$scope.visitUuid,$scope.config.obsIgnoreList,null).then(function(response){mapObservation(response.data,$scope.config)})};$scope.translateAttributeName=function(attribute){var keyName=attribute.toUpperCase().replace(/\s\s+/g," ").replace(/[^a-zA-Z0-9 _]/g,"").trim().replace(/ /g,"_"),translationKey=keyName,translation=$translate.instant(translationKey);return translation==translationKey?translation:translation},$scope.toggle=function(element){element.isOpen=!element.isOpen},$scope.isClickable=function(){return $scope.isOnDashboard&&$scope.section.expandedViewConfig&&($scope.section.expandedViewConfig.pivotTable||$scope.section.expandedViewConfig.observationGraph)},fetchObservations(),$scope.dialogData={patient:$scope.patient,section:$scope.section}},link=function($scope,element){$scope.initialization&&spinner.forPromise($scope.initialization,element)};return{restrict:"E",controller:controller,link:link,templateUrl:"../common/displaycontrols/observation/views/observationDisplayControl.html",scope:{patient:"=",visitUuid:"@",section:"=?",config:"=",title:"=sectionTitle",isOnDashboard:"=?",observations:"=?",message:"=?",enrollment:"=?",hasNoHierarchy:"@"}}}]),angular.module("bahmni.common.displaycontrol.observation").controller("AllObservationDetailsController",["$scope",function($scope){$scope.patient=$scope.ngDialogData.patient,$scope.section=$scope.ngDialogData.section,$scope.config=$scope.ngDialogData.section?$scope.ngDialogData.section.expandedViewConfig:{}}]),Bahmni.Common.DisplayControl.Observation.GroupingFunctions=function(){var self=this,observationGroupingFunction=function(obs){return Bahmni.Common.Util.DateUtil.getDateTimeWithoutSeconds(obs.encounterDateTime)};return self.groupByEncounterDate=function(bahmniObservations){var obsArray=[];bahmniObservations=_.groupBy(bahmniObservations,observationGroupingFunction);var sortWithInAConceptDateCombination=function(anObs,challengerObs){return anObs.encounterDateTime<challengerObs.encounterDateTime?1:anObs.encounterDateTime>challengerObs.encounterDateTime?-1:anObs.conceptSortWeight<challengerObs.conceptSortWeight?-1:anObs.conceptSortWeight>challengerObs.conceptSortWeight?1:0};for(var obsKey in bahmniObservations){var dateTime=obsKey,anObs={key:dateTime,value:bahmniObservations[dateTime].sort(sortWithInAConceptDateCombination),date:dateTime};obsArray.push(anObs)}return _.sortBy(obsArray,"date").reverse()},self.persistOrderOfConceptNames=function(bahmniObservations){var obsArray=[];for(var obsKey in bahmniObservations){var anObs={key:obsKey,value:[bahmniObservations[obsKey]],date:bahmniObservations[obsKey].encounterDateTime};obsArray.push(anObs)}return obsArray},self};var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.DisplayControl=Bahmni.Common.DisplayControl||{},Bahmni.Common.DisplayControl.Disposition=Bahmni.Common.DisplayControl.Disposition||{},angular.module("bahmni.common.displaycontrol.disposition",[]),angular.module("bahmni.common.displaycontrol.disposition").directive("disposition",["dispositionService","spinner",function(dispositionService,spinner){var controller=function($scope){var fetchDispositionByPatient=function(patientUuid,numOfVisits){return dispositionService.getDispositionByPatient(patientUuid,numOfVisits).then(handleDispositionResponse)},handleDispositionResponse=function(response){$scope.dispositions=response.data,_.isEmpty($scope.dispositions)&&($scope.noDispositionsMessage=Bahmni.Common.Constants.messageForNoDisposition,$scope.$emit("no-data-present-event"))},fetchDispositionsByVisit=function(visitUuid){return dispositionService.getDispositionByVisit(visitUuid).then(handleDispositionResponse)};$scope.getNotes=function(disposition){return disposition.additionalObs[0]&&disposition.additionalObs[0].value?disposition.additionalObs[0].value:""},$scope.getDisplayName=function(disposition){return null!=disposition.preferredName?disposition.preferredName:disposition.conceptName},$scope.showDetailsButton=function(disposition){return!$scope.getNotes(disposition)&&$scope.params.showDetailsButton},$scope.toggle=function(element){return $scope.showDetailsButton(element)?element.show=!element.show:element.show=!0,!1},$scope.visitUuid?$scope.fetchDispositionPromise=fetchDispositionsByVisit($scope.visitUuid):$scope.params.numberOfVisits&&$scope.patientUuid&&($scope.fetchDispositionPromise=fetchDispositionByPatient($scope.patientUuid,$scope.params.numberOfVisits))},link=function(scope,element){spinner.forPromise(scope.fetchDispositionPromise,element)};return{restrict:"E",controller:controller,link:link,templateUrl:"../common/displaycontrols/disposition/views/disposition.html",scope:{params:"=",patientUuid:"=?",visitUuid:"=?"}}}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.DisplayControl=Bahmni.Common.DisplayControl||{},Bahmni.Common.DisplayControl.AdmissionDetails=Bahmni.Common.DisplayControl.AdmissionDetails||{},angular.module("bahmni.common.displaycontrol.admissiondetails",[]),angular.module("bahmni.common.displaycontrol.admissiondetails").directive("admissionDetails",["bedService",function(bedService){var controller=function($scope){$scope.showDetailsButton=function(encounter){return $scope.params&&$scope.params.showDetailsButton&&!encounter.notes},$scope.toggle=function(element){element.show=!element.show},init($scope)},isReady=function($scope){return!_.isUndefined($scope.patientUuid)&&!_.isUndefined($scope.visitSummary)},onReady=function($scope){var visitUuid=_.get($scope.visitSummary,"uuid");bedService.getAssignedBedForPatient($scope.patientUuid,visitUuid).then(function(bedDetails){$scope.bedDetails=bedDetails})},init=function($scope){var stopWatching=$scope.$watchGroup(["patientUuid","visitSummary"],function(){isReady($scope)&&(stopWatching(),onReady($scope))});$scope.isDataPresent=function(){return!(!$scope.visitSummary||!$scope.visitSummary.admissionDetails&&!$scope.visitSummary.dischargeDetails)||$scope.$emit("no-data-present-event")&&!1}};return{restrict:"E",controller:controller,templateUrl:"../common/displaycontrols/admissiondetails/views/admissionDetails.html",scope:{params:"=",patientUuid:"=",visitSummary:"="}}}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.DisplayControl=Bahmni.Common.DisplayControl||{},Bahmni.Common.DisplayControl.PatientProfile=Bahmni.Common.DisplayControl.PatientProfile||{},angular.module("bahmni.common.displaycontrol.patientprofile",[]),angular.module("bahmni.common.displaycontrol.patientprofile").filter("titleCase",function(){return function(input){return input=input||"",input.replace(/\w\S*/g,function(txt){return txt.charAt(0).toUpperCase()+txt.substr(1).toLowerCase()})}}),angular.module("bahmni.common.displaycontrol.patientprofile").filter("booleanFilter",function(){return function(value){return value===!0?"Yes":value===!1?"No":value}}),function(){var getAddress=function($scope){var patient=$scope.patient,address=[];return void 0!=$scope.config.addressFields&&0!=$scope.config.addressFields.length?$scope.config.addressFields.forEach(function(addressField){patient.address[addressField]&&address.push(patient.address[addressField])}):_.includes($scope.config,"cityVillage")||address.push(patient.address.cityVillage),address.join(", ")},getPatientAttributeTypes=function($scope){var patient=$scope.patient;$scope.config.hasOwnProperty("ageLimit")&&patient.age>=$scope.config.ageLimit&&(patient.ageText=patient.age.toString()+" <span> years </span>");var patientAttributeTypes=[patient.genderText,patient.ageText];return patient.bloodGroupText&&patientAttributeTypes.push(patient.bloodGroupText),patientAttributeTypes.join(", ")},isAdmitted=function(admissionStatus){return"Admitted"===_.get(admissionStatus,"value")};angular.module("bahmni.common.displaycontrol.patientprofile").directive("patientProfile",["patientService","spinner","$sce","$rootScope","$stateParams","$window","$translate","configurations","$q","visitService",function(patientService,spinner,$sce,$rootScope,$stateParams,$window,$translate,configurations,$q,visitService){var controller=function($scope){$scope.isProviderRelationship=function(relationship){return _.includes($rootScope.relationshipTypeMap.provider,relationship.relationshipType.aIsToB)},$scope.openPatientDashboard=function(patientUuid){var configName=$stateParams.configName||Bahmni.Common.Constants.defaultExtensionName;$window.open("../clinical/#/"+configName+"/patient/"+patientUuid+"/dashboard")};var assignPatientDetails=function(){var patientMapper=new Bahmni.PatientMapper(configurations.patientConfig(),$rootScope,$translate);return patientService.getPatient($scope.patientUuid).then(function(response){var openMrsPatient=response.data;$scope.patient=patientMapper.map(openMrsPatient)})},assignRelationshipDetails=function(){return patientService.getRelationships($scope.patientUuid).then(function(response){$scope.relationships=response.data.results})},assignAdmissionDetails=function(){var REP="custom:(attributes:(value,attributeType:(display,name)))",ADMISSION_STATUS_ATTRIBUTE="Admission Status";return visitService.getVisit($scope.visitUuid,REP).then(function(response){var attributes=response.data.attributes,admissionStatus=_.find(attributes,{attributeType:{name:ADMISSION_STATUS_ATTRIBUTE}});$scope.hasBeenAdmitted=isAdmitted(admissionStatus)})},setHasBeenAdmittedOnVisitUuidChange=function(){$scope.$watch("visitUuid",function(visitUuid){_.isEmpty(visitUuid)||assignAdmissionDetails()})},setDirectiveAsReady=function(){$scope.isDirectiveReady=!0},onDirectiveReady=function(){$scope.addressLine=getAddress($scope),$scope.patientAttributeTypes=$sce.trustAsHtml(getPatientAttributeTypes($scope)),$scope.showBirthDate=$scope.config.showDOB!==!1,$scope.showBirthDate=$scope.showBirthDate&&!!$scope.patient.birthdate},initPromise=$q.all([assignPatientDetails(),assignRelationshipDetails()]);initPromise.then(onDirectiveReady),initPromise.then(setHasBeenAdmittedOnVisitUuidChange),initPromise.then(setDirectiveAsReady),$scope.initialization=initPromise},link=function($scope,element){spinner.forPromise($scope.initialization,element)};return{restrict:"E",controller:controller,link:link,scope:{patientUuid:"@",visitUuid:"@",config:"="},templateUrl:"../common/displaycontrols/patientprofile/views/patientProfile.html"}}])}();var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.DisplayControl=Bahmni.Common.DisplayControl||{},Bahmni.Common.DisplayControl.Diagnosis=Bahmni.Common.DisplayControl.Diagnosis||{},angular.module("bahmni.common.displaycontrol.diagnosis",[]),angular.module("bahmni.common.displaycontrol.diagnosis").filter("primaryDiagnosisFirst",function(){
return function(diagnoses){var primaryDiagnoses=_.filter(diagnoses,function(diagnosis){return diagnosis.isPrimary()}),otherDiagnoses=_.filter(diagnoses,function(diagnosis){return!diagnosis.isPrimary()});return primaryDiagnoses.concat(otherDiagnoses)}}),angular.module("bahmni.common.displaycontrol.diagnosis").directive("bahmniDiagnosis",["diagnosisService","$q","spinner","$rootScope","$filter","$translate",function(diagnosisService,$q,spinner,$rootScope,$filter,$translate){var controller=function($scope){var getAllDiagnosis=function(){return diagnosisService.getDiagnoses($scope.patientUuid,$scope.visitUuid).then(function(response){var diagnosisMapper=new Bahmni.DiagnosisMapper($rootScope.diagnosisStatus);$scope.allDiagnoses=diagnosisMapper.mapDiagnoses(response.data),0==$scope.showRuledOutDiagnoses&&($scope.allDiagnoses=_.filter($scope.allDiagnoses,function(diagnoses){return diagnoses.diagnosisStatus!==$rootScope.diagnosisStatus})),$scope.isDataPresent=function(){return!$scope.allDiagnoses||0!=$scope.allDiagnoses.length||($scope.$emit("no-data-present-event"),!1)}})};$scope.title=$scope.config.title,$scope.toggle=function(diagnosis,toggleLatest){toggleLatest?(diagnosis.showDetails=!1,diagnosis.showLatestDetails=!diagnosis.showLatestDetails):(diagnosis.showLatestDetails=!1,diagnosis.showDetails=!diagnosis.showDetails)};var getPromises=function(){return[getAllDiagnosis()]};$scope.isLatestDiagnosis=function(diagnosis){return!!diagnosis.latestDiagnosis&&diagnosis.existingObs==diagnosis.latestDiagnosis.existingObs},$scope.translateDiagnosisLabels=function(key,type){if(key){var translationKey="CLINICAL_DIAGNOSIS_"+type+"_"+key.toUpperCase(),translation=$translate.instant(translationKey);if(translation!=translationKey)return translation}return key},$scope.initialization=$q.all(getPromises())},link=function($scope,element){spinner.forPromise($scope.initialization,element)};return{restrict:"E",controller:controller,link:link,templateUrl:"../common/displaycontrols/diagnosis/views/diagnosisDisplayControl.html",scope:{patientUuid:"=",config:"=",visitUuid:"=?",showRuledOutDiagnoses:"=?",hideTitle:"=?",showLatestDiagnosis:"@showLatestDiagnosis"}}}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.DisplayControl=Bahmni.Common.DisplayControl||{},Bahmni.Common.DisplayControl.navigationLinks=Bahmni.Common.DisplayControl.navigationLinks||{},angular.module("bahmni.common.displaycontrol.navigationlinks",["ui.router","ui.router.util"]),angular.module("bahmni.common.displaycontrol.navigationlinks").directive("navigationLinks",["$state","appService",function($state,appService){var controller=function($scope){(!$scope.params.showLinks&&!$scope.params.customLinks||$scope.params.showLinks&&$scope.params.customLinks&&0==$scope.params.showLinks.length&&0==$scope.params.customLinks.length)&&($scope.noNavigationLinksMessage=Bahmni.Common.Constants.noNavigationLinksMessage),$scope.standardLinks=[{name:"home",translationKey:"HOME_DASHBOARD_KEY",url:"../home/#/dashboard"},{name:"visit",url:"../clinical/#/default/patient/{{patientUuid}}/dashboard/visit/{{visitUuid}}/?encounterUuid=active",translationKey:"PATIENT_VISIT_PAGE_KEY"},{name:"inpatient",translationKey:"PATIENT_ADT_PAGE_KEY",url:"../adt/#/patient/{{patientUuid}}/visit/{{visitUuid}}/"},{name:"enrolment",translationKey:"PROGRAM_MANAGEMENT_PAGE_KEY",url:"../clinical/#/programs/patient/{{patientUuid}}/consultationContext"},{name:"visitAttribute",translationKey:"PATIENT_VISIT_ATTRIBUTES_PAGE_KEY",url:"../registration/#/patient/{{patientUuid}}/visit"},{name:"registration",translationKey:"PATIENT_REGISTRATION_PAGE_KEY",url:"../registration/#/patient/{{patientUuid}}"}];var filterLinks=function(links,showLinks){var linksSpecifiedInShowLinks=function(){return _.filter(links,function(link){return showLinks.indexOf(link.name)>-1})};return showLinks&&linksSpecifiedInShowLinks()};$scope.getLinks=function(){return _.union(filterLinks($scope.standardLinks,$scope.params.showLinks),$scope.params.customLinks)},$scope.getUrl=function(link){var url=getFormattedURL(link);window.open(url,link.title)},$scope.showUrl=function(link){var isPropertyNotPresentInLinkParams,params=getParamsToBeReplaced(link.url);for(var i in params){var property=params[i];if(isPropertyNotPresentInLinkParams=_.isEmpty($scope.linkParams[property]))return!1}return!0};var getFormattedURL=function(link){return appService.getAppDescriptor().formatUrl(link.url,$scope.linkParams)},getParamsToBeReplaced=function(link){var pattern=/{{([^}]*)}}/g,matches=link.match(pattern),params=[];return matches&&matches.forEach(function(el){var key=el.replace("{{","").replace("}}","");params.push(key)}),params}};return{restrict:"E",controller:controller,templateUrl:"../common/displaycontrols/navigationlinks/views/navigationLinks.html",scope:{params:"=",linkParams:"="}}}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.DisplayControl=Bahmni.Common.DisplayControl||{},Bahmni.Common.DisplayControl.Custom=Bahmni.Common.DisplayControl.Custom||{},angular.module("bahmni.common.displaycontrol.custom",[]),angular.module("bahmni.common.displaycontrol.custom").directive("customDisplayControl",[function(){return{restrict:"E",template:'<div compile-html="config.template"></div>',scope:{patient:"=",visitUuid:"=",section:"=",config:"=",enrollment:"=",params:"=",visitSummary:"="}}}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.I18n=Bahmni.Common.I18n||{},angular.module("bahmni.common.i18n",[]),angular.module("bahmni.common.i18n",["pascalprecht.translate"]).provider("$bahmniTranslate",["$translateProvider",function($translateProvider){this.init=function(options){var preferredLanguage=window.localStorage.NG_TRANSLATE_LANG_KEY||"en";$translateProvider.useLoader("mergeLocaleFilesService",options),$translateProvider.useSanitizeValueStrategy("escaped"),$translateProvider.preferredLanguage(preferredLanguage),$translateProvider.useLocalStorage()},this.$get=[function(){return $translateProvider}]}]).filter("titleTranslate",["$translate",function($translate){return function(input){return input?input.translationKey?$translate.instant(input.translationKey):input.dashboardName?input.dashboardName:input.title?input.title:input.label?input.label:input.display?input.display:$translate.instant(input):input}}]),angular.module("bahmni.common.i18n").service("mergeLocaleFilesService",["$http","$q","mergeService",function($http,$q,mergeService){return function(options){var baseLocaleUrl="../i18n/",customLocaleUrl=Bahmni.Common.Constants.rootDir+"/bahmni_config/openmrs/i18n/",loadFile=function(url){return $http.get(url,{withCredentials:!0})},mergeLocaleFile=function(options){var fileURL=options.app+"/locale_"+options.key+".json",loadBahmniTranslations=function(){return loadFile(baseLocaleUrl+fileURL).then(function(result){return result},function(){})},loadCustomTranslations=function(){return loadFile(customLocaleUrl+fileURL).then(function(result){return result},function(){})},mergeTranslations=function(result){var baseFileData=result[0]?result[0].data:void 0,customFileData=result[1]?result[1].data:void 0;return options.shouldMerge||void 0===options.shouldMerge?mergeService.merge(baseFileData,customFileData):[baseFileData,customFileData]};return $q.all([loadBahmniTranslations(),loadCustomTranslations()]).then(mergeTranslations)};return mergeLocaleFile(options)}}]),angular.module("bahmni.common.uiHelper").directive("singleClick",function(){var ignoreClick=!1,link=function(scope,element){var clickHandler=function(){ignoreClick||(ignoreClick=!0,scope.singleClick().finally(function(){ignoreClick=!1}))};element.on("click",clickHandler),scope.$on("$destroy",function(){element.off("click",clickHandler)})};return{scope:{singleClick:"&"},restrict:"A",link:link}}),angular.module("bahmni.common.conceptSet").factory("formService",["$http",function($http){var getFormList=function(encounterUuid){return $http.get(Bahmni.Common.Constants.latestPublishedForms,{params:{encounterUuid:encounterUuid}})},getAllForms=function(){return $http.get(Bahmni.Common.Constants.allFormsUrl,{params:{v:"custom:(version,name,uuid)"}})},getFormDetail=function(formUuid,params){return $http.get(Bahmni.Common.Constants.formUrl+"/"+formUuid,{params:params})};const getUrlWithUuid=function(url,patientUuid){return url.replace("{patientUuid}",patientUuid)};var getAllPatientForms=function(patientUuid,numberOfVisits,patientProgramUuid){const patientFormsUrl=getUrlWithUuid(Bahmni.Common.Constants.patientFormsUrl,patientUuid),params={numberOfVisits:numberOfVisits,formType:"v2",patientProgramUuid:patientProgramUuid};return $http.get(patientFormsUrl,{params:params})},getFormTranslations=function(url,form){return url&&url!==Bahmni.Common.Constants.formTranslationsUrl?$http.get(url):$http.get(Bahmni.Common.Constants.formTranslationsUrl,{params:form})},getFormTranslate=function(formName,formVersion,locale,formUuid){return $http.get(Bahmni.Common.Constants.formBuilderTranslationApi,{params:{formName:formName,formVersion:formVersion,locale:locale,formUuid:formUuid}})};return{getFormList:getFormList,getAllForms:getAllForms,getFormDetail:getFormDetail,getFormTranslations:getFormTranslations,getFormTranslate:getFormTranslate,getAllPatientForms:getAllPatientForms}}]);var Bahmni=Bahmni||{};Bahmni.IPD=Bahmni.IPD||{},angular.module("bahmni.ipd",["bahmni.common.conceptSet","bahmni.common.logging"]);var Bahmni=Bahmni||{};Bahmni.IPD=Bahmni.IPD||{},Bahmni.IPD.Constants=function(){return{patientsListUrl:"/patient/search",ipdDashboard:"#/patient/{{patientUuid}}/visit/{{visitUuid}}/",admissionLocationUrl:"/openmrs/ws/rest/v1/admissionLocation/",getAllBedTags:"/openmrs/ws/rest/v1/bedTag",bedTagMapUrl:"/openmrs/ws/rest/v1/bedTagMap/",visitRepresentation:"custom:(uuid,startDatetime,stopDatetime,visitType,patient)",editTagsPrivilege:"Edit Bed Tags",assignBedsPrivilege:"Assign Beds"}}(),angular.module("ipd",["bahmni.common.patient","bahmni.common.patientSearch","bahmni.common.uiHelper","bahmni.common.conceptSet","authentication","bahmni.common.appFramework","httpErrorInterceptor","bahmni.ipd","bahmni.common.domain","bahmni.common.config","ui.router","bahmni.common.util","bahmni.common.routeErrorHandler","bahmni.common.i18n","bahmni.common.displaycontrol.dashboard","bahmni.common.displaycontrol.observation","bahmni.common.displaycontrol.disposition","bahmni.common.displaycontrol.admissiondetails","bahmni.common.displaycontrol.custom","bahmni.common.obs","bahmni.common.displaycontrol.patientprofile","bahmni.common.displaycontrol.diagnosis","RecursionHelper","ngSanitize","bahmni.common.uiHelper","bahmni.common.displaycontrol.navigationlinks","pascalprecht.translate","bahmni.common.displaycontrol.dashboard","ngCookies","ngDialog","angularFileUpload","monospaced.elastic"]),angular.module("ipd").config(["$stateProvider","$httpProvider","$urlRouterProvider","$bahmniTranslateProvider","$compileProvider",function($stateProvider,$httpProvider,$urlRouterProvider,$bahmniTranslateProvider,$compileProvider){$urlRouterProvider.otherwise("/home");var homeBackLink={type:"link",name:"Home",value:"../home/",accessKey:"h",icon:"fa-home"},admitLink={type:"state",name:"ADMIT_HOME_KEY",value:"home",accessKey:"a"},bedManagementLink={type:"state",name:"BED_MANAGEMENT_KEY",value:"bedManagement",accessKey:"b"},navigationLinks=[admitLink,bedManagementLink];$compileProvider.debugInfoEnabled(!1),$stateProvider.state("home",{url:"/home",data:{homeBackLink:homeBackLink,navigationLinks:navigationLinks},views:{content:{templateUrl:"views/home.html",controller:function($scope,appService){$scope.isBedManagementEnabled=appService.getAppDescriptor().getConfig("isBedManagementEnabled").value}},"additional-header":{templateUrl:" views/header.html",controller:"HeaderController"}},resolve:{initialization:"initialization"}}).state("bedManagement",{url:"/bedManagement",data:{homeBackLink:homeBackLink,navigationLinks:navigationLinks},params:{dashboardCachebuster:null,context:null},views:{content:{templateUrl:"views/bedManagement.html",controller:"BedManagementController"},"additional-header":{templateUrl:"views/header.html",controller:"HeaderController"}},resolve:{initialization:"initialization",init:function($rootScope){$rootScope.patient=void 0,$rootScope.bedDetails=void 0}}}).state("bedManagement.bed",{url:"/bed/:bedId",templateUrl:"views/bedManagement.html",controller:"BedManagementController",params:{dashboardCachebuster:null,context:null},resolve:{bedResolution:function($stateParams,bedInitialization,patientInitialization){return bedInitialization($stateParams.bedId).then(function(response){if(response.patients.length)return patientInitialization(response.patients[0].uuid)})}}}).state("bedManagement.patient",{url:"/patient/:patientUuid",templateUrl:"views/bedManagement.html",controller:"BedManagementController",resolve:{patientResolution:function($stateParams,bedInitialization,patientInitialization){return patientInitialization($stateParams.patientUuid).then(function(){return bedInitialization(void 0,$stateParams.patientUuid)})}}}).state("dashboard",{url:"/patient/:patientUuid/visit/:visitUuid/dashboard",data:{homeBackLink:homeBackLink,navigationLinks:navigationLinks},views:{content:{templateUrl:"views/dashboard.html",controller:"AdtController"},"additional-header":{templateUrl:" views/header.html",controller:"HeaderController"}},resolve:{initialization:"initialization",patientResolution:function($stateParams,bedInitialization,patientInitialization){return patientInitialization($stateParams.patientUuid).then(function(){return bedInitialization(void 0,$stateParams.patientUuid)})}}}),$bahmniTranslateProvider.init({app:"ipd",shouldMerge:!0})}]),angular.module("bahmni.ipd").factory("initialization",["$rootScope","$q","$bahmniCookieStore","appService","configurations","authenticator","spinner","locationService",function($rootScope,$q,$bahmniCookieStore,appService,configurations,authenticator,spinner,locationService){var getConfigs=function(){var config=$q.defer(),configNames=["encounterConfig","patientConfig","genderMap","relationshipTypeMap"];return configurations.load(configNames).then(function(){$rootScope.encounterConfig=angular.extend(new EncounterConfig,configurations.encounterConfig()),$rootScope.patientConfig=configurations.patientConfig(),$rootScope.genderMap=configurations.genderMap(),$rootScope.relationshipTypeMap=configurations.relationshipTypeMap(),$rootScope.diagnosisStatus=appService.getAppDescriptor().getConfig("diagnosisStatus")&&appService.getAppDescriptor().getConfig("diagnosisStatus").value||"RULED OUT",config.resolve()}),config.promise},initApp=function(){return appService.initApp("ipd",{app:!0,extension:!0}).then(function(data){var config=data.getConfig("onAdmissionForwardTo",!1);data.baseConfigs.dashboard.value.sections=_.sortBy(data.baseConfigs.dashboard.value.sections,function(section){return section.displayOrder}),data.baseConfigs.isBedManagementEnabled={name:"isBedManagementEnabled",value:_.includes(config[0].value,"bed")},config[1]&&(data.customConfigs.isBedManagementEnabled={name:"isBedManagementEnabled",value:_.includes(config[1].value,"bed")}),initVisitLocation()})},initVisitLocation=function(){var loginLocationUuid=$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName).uuid;locationService.getVisitLocation(loginLocationUuid).then(function(response){response.data&&($rootScope.visitLocationUuid=response.data.uuid)})};return spinner.forPromise(authenticator.authenticateUser().then(initApp).then(getConfigs))}]),angular.module("bahmni.ipd").factory("patientInitialization",["$rootScope","$q","patientService","initialization","bedService","spinner","$translate",function($rootScope,$q,patientService,initialization,bedService,spinner,$translate){return function(patientUuid){var getPatient=function(){var patientMapper=new Bahmni.PatientMapper($rootScope.patientConfig,$rootScope,$translate),patientPromise=$q.defer();return patientService.getPatient(patientUuid).then(function(response){$rootScope.patient=patientMapper.map(response.data),patientPromise.resolve()}),patientPromise.promise};return spinner.forPromise(initialization.then(getPatient))}}]),angular.module("bahmni.ipd").factory("bedInitialization",["$rootScope","$q","patientService","initialization","bedService","spinner",function($rootScope,$q,patientService,initialization,bedService,spinner){return function(bedId,patientUuid){var initializeBedInfo=function(){return bedId?bedService.getCompleteBedDetailsByBedId(bedId).then(function(response){var bedInfo=response.data;return bedInfo.wardName=response.data.physicalLocation.parentLocation.display,bedInfo.wardUuid=response.data.physicalLocation.parentLocation.uuid,bedInfo.physicalLocationName=response.data.physicalLocation.name,$rootScope.bedDetails=bedInfo,bedInfo}):bedService.setBedDetailsForPatientOnRootScope(patientUuid)};return spinner.forPromise(initializeBedInfo())}}]),angular.module("bahmni.ipd").controller("BedManagementController",["$scope","$rootScope","$stateParams","$state","spinner","wardService","bedManagementService","visitService","messagingService","appService","ngDialog",function($scope,$rootScope,$stateParams,$state,spinner,wardService,bedManagementService,visitService,messagingService,appService,ngDialog){$scope.wards=null,$scope.ward={},$scope.editTagsPrivilege=Bahmni.IPD.Constants.editTagsPrivilege;var links={dashboard:{name:"inpatient",translationKey:"PATIENT_ADT_PAGE_KEY",url:"../bedmanagement/#/patient/{{patientUuid}}/visit/{{visitUuid}}/dashboard"}},patientForwardUrl=appService.getAppDescriptor().getConfigValue("patientForwardUrl")||links.dashboard.url,isDepartmentPresent=function(department){return!!department&&_.values(department).indexOf()===-1},init=function(){$rootScope.selectedBedInfo=$rootScope.selectedBedInfo||{},loadAllWards().then(function(){var context=$stateParams.context||{};context&&isDepartmentPresent(context.department)?expandAdmissionMasterForDepartment(context.department):$rootScope.bedDetails&&expandAdmissionMasterForDepartment({uuid:$rootScope.bedDetails.wardUuid,name:$rootScope.bedDetails.wardName}),resetDepartments(),resetBedInfo()})},loadAllWards=function(){return spinner.forPromise(wardService.getWardsList().success(function(wardsList){$scope.wards=wardsList.results}))},mapRoomInfo=function(roomsInfo){var mappedRooms=[];return _.forIn(roomsInfo,function(value,key){var bedsGroupedByBedStatus=_.groupBy(value,"status"),availableBeds=bedsGroupedByBedStatus.AVAILABLE?bedsGroupedByBedStatus.AVAILABLE.length:0;mappedRooms.push({name:key,beds:value,totalBeds:value.length,availableBeds:availableBeds})}),mappedRooms},getRoomsForWard=function(bedLayouts){var rooms=mapRoomInfo(_.groupBy(bedLayouts,"location"));return _.each(rooms,function(room){room.beds=bedManagementService.createLayoutGrid(room.beds)}),rooms},getWardDetails=function(department){return _.filter($scope.wards,function(entry){return entry.ward.uuid===department.uuid})},selectCurrentDepartment=function(department){_.each($scope.wards,function(wardElement){wardElement.ward.uuid===department.uuid&&(wardElement.ward.isSelected=!0,wardElement.ward.selected=!0)})},loadBedsInfoForWard=function(department){return wardService.bedsForWard(department.uuid).then(function(response){var wardDetails=getWardDetails(department),rooms=getRoomsForWard(response.data.bedLayouts);$scope.ward={rooms:rooms,uuid:department.uuid,name:department.name,totalBeds:wardDetails[0].totalBeds,occupiedBeds:wardDetails[0].occupiedBeds},$scope.departmentSelected=!0,$rootScope.selectedBedInfo.wardName=department.name,$rootScope.selectedBedInfo.wardUuid=department.uuid,selectCurrentDepartment(department),$scope.$broadcast("event:departmentChanged")})},expandAdmissionMasterForDepartment=function(department){spinner.forPromise(loadBedsInfoForWard(department))};$scope.onSelectDepartment=function(department){spinner.forPromise(loadBedsInfoForWard(department).then(function(){resetPatientAndBedInfo(),resetDepartments(),$scope.$broadcast("event:deselectWards"),department.isSelected=!0}))};var resetDepartments=function(){_.each($scope.wards,function(option){option.ward.isSelected=!1})},resetBedInfo=function(){$rootScope.selectedBedInfo.roomName=void 0,$rootScope.selectedBedInfo.bed=void 0},resetPatientAndBedInfo=function(){resetBedInfo(),goToBedManagement()};$scope.$on("event:patientAssignedToBed",function(event,bed){$scope.ward.occupiedBeds=$scope.ward.occupiedBeds+1,_.map($scope.ward.rooms,function(room){room.name===$scope.roomName&&(room.availableBeds=room.availableBeds-1)})}),$scope.$on("event:updateSelectedBedInfoForCurrentPatientVisit",function(event,patientUuid){getVisitInfoByPatientUuid(patientUuid).then(function(visitUuid){var options={patientUuid:patientUuid,visitUuid:visitUuid};$state.go("bedManagement.patient",options)})});var goToBedManagement=function(){if("bedManagement.bed"===$state.current.name){var options={};options.context={department:{uuid:$scope.ward.uuid,name:$scope.ward.name},roomName:$scope.roomName},options.dashboardCachebuster=Math.random(),$state.go("bedManagement",options)}},getVisitInfoByPatientUuid=function(patientUuid){return visitService.search({patient:patientUuid,includeInactive:!1,v:"custom:(uuid,location:(uuid))"}).then(function(response){var activeVisitForCurrentLoginLocation,results=response.data.results;results&&(activeVisitForCurrentLoginLocation=_.filter(results,function(result){return result.location.uuid===$rootScope.visitLocationUuid}));var hasActiveVisit=activeVisitForCurrentLoginLocation.length>0;return hasActiveVisit?activeVisitForCurrentLoginLocation[0].uuid:""})};$scope.goToAdtPatientDashboard=function(){getVisitInfoByPatientUuid($scope.patient.uuid).then(function(visitUuid){var options={patientUuid:$scope.patient.uuid,visitUuid:visitUuid},url=appService.getAppDescriptor().formatUrl(patientForwardUrl,options);window.open(url)}),window.scrollY>0&&window.scrollTo(0,0)},$scope.canEditTags=function(){return $rootScope.selectedBedInfo.bed&&"bedManagement.bed"===$state.current.name},$scope.editTagsOnTheBed=function(){ngDialog.openConfirm({template:"views/editTags.html",scope:$scope,closeByEscape:!0,className:"ngdialog-theme-default ng-dialog-adt-popUp"})},init()}]),angular.module("bahmni.ipd").controller("HeaderController",["$scope","$rootScope","$state",function($scope,$rootScope,$state){$scope.goToAdmitState=function(){var options={};options.dashboardCachebuster=Math.random(),$state.go("home",options)},$scope.goToBedManagementState=function(){var options={};options.dashboardCachebuster=Math.random(),$state.go("bedManagement",options)}}]),angular.module("bahmni.ipd").controller("AdtController",["$scope","$q","$rootScope","spinner","dispositionService","encounterService","bedService","appService","visitService","$location","$window","sessionService","messagingService","$anchorScroll","$stateParams","ngDialog","$filter","$state","$translate",function($scope,$q,$rootScope,spinner,dispositionService,encounterService,bedService,appService,visitService,$location,$window,sessionService,messagingService,$anchorScroll,$stateParams,ngDialog,$filter,$state,$translate){var actionConfigs={},encounterConfig=$rootScope.encounterConfig,locationUuid=sessionService.getLoginLocationUuid(),visitTypes=encounterConfig.getVisitTypes(),customVisitParams=Bahmni.IPD.Constants.visitRepresentation;$scope.assignBedsPrivilege=Bahmni.IPD.Constants.assignBedsPrivilege,$scope.defaultVisitTypeName=appService.getAppDescriptor().getConfigValue("defaultVisitType");var hideStartNewVisitPopUp=appService.getAppDescriptor().getConfigValue("hideStartNewVisitPopUp");$scope.adtObservations=[],$scope.dashboardConfig=appService.getAppDescriptor().getConfigValue("dashboard"),$scope.expectedDateOfDischargeConceptName=appService.getAppDescriptor().getConfigValue("expectedDateOfDischarge")||"",$scope.getAdtConceptConfig=$scope.dashboardConfig.conceptName,$scope.editMode=!1,$scope.buttonClicked=!1;var getVisitTypeUuid=function(visitTypeName){var visitType=_.find(visitTypes,{name:visitTypeName});return visitType&&visitType.uuid||null},defaultVisitTypeUuid=getVisitTypeUuid($scope.defaultVisitTypeName),getCurrentVisitTypeUuid=function(){return $scope.visitSummary&&null===$scope.visitSummary.dateCompleted?getVisitTypeUuid($scope.visitSummary.visitType):defaultVisitTypeUuid},initializeActionConfig=function(){var admitActions=appService.getAppDescriptor().getExtensions("org.bahmni.ipd.admit.action","config"),transferActions=appService.getAppDescriptor().getExtensions("org.bahmni.ipd.transfer.action","config"),dischargeActions=appService.getAppDescriptor().getExtensions("org.bahmni.ipd.discharge.action","config"),undoDischargeActions=appService.getAppDescriptor().getExtensions("org.bahmni.ipd.undo.discharge.action","config");if(encounterConfig){var Constants=Bahmni.Common.Constants;actionConfigs[Constants.admissionCode]={encounterTypeUuid:encounterConfig.getAdmissionEncounterTypeUuid(),allowedActions:admitActions},actionConfigs[Constants.dischargeCode]={encounterTypeUuid:encounterConfig.getDischargeEncounterTypeUuid(),allowedActions:dischargeActions},actionConfigs[Constants.transferCode]={encounterTypeUuid:encounterConfig.getTransferEncounterTypeUuid(),allowedActions:transferActions},actionConfigs[Constants.undoDischargeCode]={encounterTypeUuid:encounterConfig.getDischargeEncounterTypeUuid(),allowedActions:undoDischargeActions}}},filterAction=function(actions,actionTypes){return _.filter(actions,function(action){return actionTypes.indexOf(action.name.name)>=0})},getDispositionActions=function(actions){var visitSummary=$scope.visitSummary,stopDate=visitSummary&&visitSummary.stopDateTime,isVisitOpen=null===stopDate;return visitSummary&&visitSummary.isDischarged()&&isVisitOpen?filterAction(actions,["Undo Discharge"]):visitSummary&&visitSummary.isAdmitted()&&isVisitOpen?filterAction(actions,["Transfer Patient","Discharge Patient"]):filterAction(actions,["Admit Patient"])},getPatientSpecificActiveVisits=function(response){var currentActiveVisit=_.last(response.data.results);return currentActiveVisit?currentActiveVisit.uuid:null},getVisit=function(){var getNoVisitPromise=function(){return $scope.visitSummary=null,$q.when({id:1,status:"Returned from service.",promiseComplete:!0})};return $scope.patient?visitService.search({patient:$scope.patient.uuid,v:customVisitParams,includeInactive:!1}).then(function(visitsResponse){var visitUuid=getPatientSpecificActiveVisits(visitsResponse);return visitUuid?visitService.getVisitSummary(visitUuid).then(function(response){$scope.visitSummary=new Bahmni.Common.VisitSummary(response.data)}):getNoVisitPromise()}):getNoVisitPromise()};$scope.showAdtButtons=function(){return"bedManagement.patient"===$state.current.name&&!$scope.editMode};var init=function(){initializeActionConfig(),$scope.encounterConfig=$scope.$parent.encounterConfig,$scope.currentVisitTypeUuid=getCurrentVisitTypeUuid();var defaultVisitType=appService.getAppDescriptor().getConfigValue("defaultVisitType"),visitTypes=encounterConfig.getVisitTypes();return $scope.visitControl=new Bahmni.Common.VisitControl(visitTypes,defaultVisitType,visitService),$scope.dashboard=Bahmni.Common.DisplayControl.Dashboard.create($scope.dashboardConfig||{},$filter),$scope.sectionGroups=$scope.dashboard.getSections($scope.diseaseTemplates),getVisit().then(dispositionService.getDispositionActions).then(function(response){response.data&&response.data.results&&response.data.results.length&&($scope.dispositionActions=getDispositionActions(response.data.results[0].answers),$scope.visitSummary&&($scope.currentVisitType=$scope.visitSummary.visitType))})},getEncounterData=function(encounterTypeUuid,visitTypeUuid){var encounterData={};return encounterData.patientUuid=$scope.patient.uuid,encounterData.encounterTypeUuid=encounterTypeUuid,encounterData.visitTypeUuid=visitTypeUuid,encounterData.observations=$scope.adtObservations,encounterData.observations=_.filter(encounterData.observations,function(observation){return!_.isEmpty(observation.value)}),encounterData.locationUuid=locationUuid,encounterData},forwardUrl=function(response,option){var appDescriptor=appService.getAppDescriptor(),forwardLink=appDescriptor.getConfig(option);forwardLink=forwardLink&&forwardLink.value;var bedId=_.get($rootScope.bedDetails,"bedId")||_.get($rootScope.selectedBedInfo,"bed.bedId"),options={patientUuid:$scope.patient.uuid,encounterUuid:response.encounterUuid,visitUuid:response.visitUuid,bedId:bedId};forwardLink&&$state.transitionTo("bedManagement.patient",options,{reload:!0,inherit:!1,notify:!0})},createEncounterAndContinue=function(){var currentVisitTypeUuid=getCurrentVisitTypeUuid();if(null!==currentVisitTypeUuid){var encounterData=getEncounterData($scope.encounterConfig.getAdmissionEncounterTypeUuid(),currentVisitTypeUuid);return spinner.forPromise(encounterService.create(encounterData).then(function(response){null===$scope.visitSummary&&visitService.getVisitSummary(response.data.visitUuid).then(function(response){$scope.visitSummary=new Bahmni.Common.VisitSummary(response.data)}),assignBedToPatient($rootScope.selectedBedInfo.bed,response.data.patientUuid,response.data.encounterUuid),forwardUrl(response.data,"onAdmissionForwardTo")}))}return null===$scope.defaultVisitTypeName?messagingService.showMessage("error","MESSAGE_DEFAULT_VISIT_TYPE_NOT_FOUND_KEY"):messagingService.showMessage("error","MESSAGE_DEFAULT_VISIT_TYPE_INVALID_KEY"),$q.when({})},assignBedToPatient=function(bed,patientUuid,encounterUuid){spinner.forPromise(bedService.assignBed(bed.bedId,patientUuid,encounterUuid).then(function(){bed.status="OCCUPIED",$scope.$emit("event:patientAssignedToBed",$rootScope.selectedBedInfo.bed),messagingService.showMessage("info",$translate.instant("BED")+" "+bed.bedNumber+" "+$translate.instant("IS_SUCCESSFULLY_ASSIGNED_MESSAGE"))}))},setButtonClicked=function(){$scope.buttonClicked=!0},unsetButtonClicked=function(){$scope.buttonClicked=!1};$scope.admit=function(){return setButtonClicked(),angular.isUndefined($rootScope.selectedBedInfo.bed)?(messagingService.showMessage("error","SELECT_BED_TO_ADMIT_PATIENT_DEFAULT_MESSAGE"),unsetButtonClicked()):$scope.visitSummary&&$scope.visitSummary.visitType!==$scope.defaultVisitTypeName&&!hideStartNewVisitPopUp?ngDialog.openConfirm({template:"views/visitChangeConfirmation.html",scope:$scope,closeByEscape:!0,preCloseCallback:unsetButtonClicked}):ngDialog.openConfirm({template:"views/admitConfirmation.html",scope:$scope,closeByEscape:!0,className:"ngdialog-theme-default ng-dialog-adt-popUp",preCloseCallback:unsetButtonClicked}),$q.when({})},$scope.cancelConfirmationDialog=function(){ngDialog.close()},$scope.closeCurrentVisitAndStartNewVisit=function(){if(null!==defaultVisitTypeUuid){var encounter=getEncounterData($scope.encounterConfig.getAdmissionEncounterTypeUuid(),defaultVisitTypeUuid);spinner.forPromise(visitService.endVisitAndCreateEncounter($scope.visitSummary.uuid,encounterService.buildEncounter(encounter)).then(function(response){spinner.forPromise(visitService.getVisitSummary(response.data.visitUuid).then(function(response){$scope.visitSummary=new Bahmni.Common.VisitSummary(response.data)})),assignBedToPatient($rootScope.selectedBedInfo.bed,response.data.patientUuid,response.data.encounterUuid),forwardUrl(response.data,"onAdmissionForwardTo")}))}else null===$scope.defaultVisitTypeName?messagingService.showMessage("error","MESSAGE_DEFAULT_VISIT_TYPE_NOT_FOUND_KEY"):messagingService.showMessage("error","MESSAGE_DEFAULT_VISIT_TYPE_INVALID_KEY");return ngDialog.close(),$q.when({})},$scope.continueWithCurrentVisit=function(){createEncounterAndContinue(),ngDialog.close()},spinner.forPromise(init()),$scope.disableAdmitButton=function(){return!($rootScope.patient&&!$rootScope.bedDetails)||$scope.buttonClicked},$scope.disableTransfer=function(){return!($rootScope.patient&&$rootScope.bedDetails&&!isCurrentPatientPresentOnSelectedBed())||$scope.buttonClicked};var isCurrentPatientPresentOnSelectedBed=function(){return!!$rootScope.selectedBedInfo.bed&&$rootScope.selectedBedInfo.bed.bedId===$rootScope.bedDetails.bedId;
};$scope.disableDischargeButton=function(){return!($rootScope.patient&&$rootScope.bedDetails&&isCurrentPatientPresentOnSelectedBed())||$scope.buttonClicked},$scope.transfer=function(){setButtonClicked(),angular.isUndefined($rootScope.selectedBedInfo.bed)||$rootScope.selectedBedInfo.bed.bedId===$rootScope.bedDetails.bedId?messagingService.showMessage("error","SELECT_BED_TO_TRANSFER_MESSAGE"):ngDialog.openConfirm({template:"views/transferConfirmation.html",scope:$scope,closeByEscape:!0,className:"ngdialog-theme-default ng-dialog-adt-popUp",preCloseCallback:unsetButtonClicked})};var reloadStateWithContextParams=function(){var selectedBedInfo=$rootScope.selectedBedInfo,options={patientUuid:$scope.patient.uuid,context:{roomName:selectedBedInfo.roomName,department:{uuid:selectedBedInfo.wardUuid,name:selectedBedInfo.wardName,roomName:selectedBedInfo.roomName}}};$state.transitionTo("bedManagement.patient",options,{reload:!0,inherit:!1,notify:!0})},disableButton=function(){$scope.isDisabled=!0};$scope.transferConfirmation=function(){var encounterData=getEncounterData($scope.encounterConfig.getTransferEncounterTypeUuid(),getCurrentVisitTypeUuid());disableButton(),spinner.forPromise(bedService.getCompleteBedDetailsByBedId($rootScope.selectedBedInfo.bed.bedId).then(function(response){var bedDetails=response.data;bedDetails.patients.length?(showErrorMessage(bedDetails),reloadStateWithContextParams()):spinner.forPromise(encounterService.create(encounterData).then(function(response){assignBedToPatient($rootScope.selectedBedInfo.bed,response.data.patientUuid,response.data.encounterUuid),ngDialog.close(),forwardUrl(response.data,"onTransferForwardTo")}))}))},$scope.discharge=function(){setButtonClicked(),$rootScope.bedDetails.bedNumber?visitService.search({patient:$scope.patient.uuid,v:customVisitParams,includeInactive:!1}).then(function(visitResponse){var visitUuid=getPatientSpecificActiveVisits(visitResponse);visitUuid?ngDialog.openConfirm({template:"views/dischargeConfirmation.html",scope:$scope,closeByEscape:!0,className:"ngdialog-theme-default ng-dialog-adt-popUp",preCloseCallback:unsetButtonClicked}):messagingService.showMessage("error","NO_ACTIVE_VISIT_MESSAGE")}):messagingService.showMessage("error","SELECT_BED_TO_DISCHARGE_MESSAGE")},$scope.dischargeConfirmation=function(){var encounterData=getEncounterData($scope.encounterConfig.getDischargeEncounterTypeUuid());return spinner.forPromise(encounterService.discharge(encounterData).then(function(response){ngDialog.close(),forwardUrl(response.data,"onDischargeForwardTo");var bedNumber=_.get($rootScope.bedDetails,"bedNumber")||_.get($rootScope.selectedBedInfo,"bed.bedNumber");messagingService.showMessage("info",$translate.instant("SUCCESSFULLY_DISCHARGED_MESSAGE",{bed:bedNumber}))}))};var showErrorMessage=function(bedDetails){var patient=bedDetails.patients[0],identifier=patient.display&&patient.display.split(" - ")[0];patient.identifiers[0].identifier=identifier,messagingService.showMessage("error",$translate.instant("SELECT_AVAILABLE_BED_DEFAULT_MESSAGE",{identifier:identifier})),$scope.cancelConfirmationDialog()};$scope.admitConfirmation=function(){spinner.forPromise(bedService.getCompleteBedDetailsByBedId($rootScope.selectedBedInfo.bed.bedId).then(function(response){var bedDetails=response.data;return bedDetails.patients.length?(showErrorMessage(bedDetails),void reloadStateWithContextParams()):void(hideStartNewVisitPopUp&&$scope.visitSummary&&getVisitTypeUuid($scope.visitSummary.visitType)!==defaultVisitTypeUuid?$scope.closeCurrentVisitAndStartNewVisit():(createEncounterAndContinue(),$scope.cancelConfirmationDialog()))}))}}]),angular.module("bahmni.ipd").controller("WardController",["$scope","$rootScope","$stateParams","$state",function($scope,$rootScope,$stateParams,$state){var init=function(){$stateParams.context&&$stateParams.context.roomName?expandAdmissionMasterForRoom($stateParams.context.roomName):$rootScope.bedDetails&&expandAdmissionMasterForRoom($rootScope.bedDetails.physicalLocationName)},getSelectedRoom=function(roomName){var admissionRoom=_.filter($scope.ward.rooms,function(room){return room.name===roomName});$scope.room=admissionRoom[0],$scope.activeRoom=$scope.room.name,$scope.roomSelected=!0};$scope.$on("event:deselectWards",function(event,ward){$scope.activeRoom=null});var updateSelectedBedInfo=function(roomName){$rootScope.selectedBedInfo.roomName=roomName,$rootScope.selectedBedInfo.bed=void 0};$scope.onSelectRoom=function(roomName){updateSelectedBedInfo(roomName),getSelectedRoom(roomName),$scope.$emit("event:roomSelected",roomName),$scope.$broadcast("event:changeBedList",roomName),$scope.activeRoom=roomName,goToBedManagement(),window.scrollY>0&&window.scrollTo(0,0)};var expandAdmissionMasterForRoom=function(roomName){updateSelectedBedInfo(roomName),getSelectedRoom(roomName)};$scope.$on("event:departmentChanged",function(event){$scope.roomSelected=!1});var goToBedManagement=function(){if("bedManagement.bed"===$state.current.name){var options={};options.context={department:{uuid:$scope.ward.uuid,name:$scope.ward.name},roomName:$rootScope.selectedBedInfo.roomName},options.dashboardCachebuster=Math.random(),$state.go("bedManagement",options)}};init()}]),angular.module("bahmni.ipd").controller("RoomController",["$scope","$rootScope","$state","$translate","appService","printer",function($scope,$rootScope,$state,$translate,appService,printer){var init=function(){$scope.defaultTags=["AVAILABLE","OCCUPIED"];var appDescriptor=appService.getAppDescriptor();$rootScope.bedTagsColorConfig=appDescriptor.getConfigValue("colorForTags")||[],$rootScope.currentView=$rootScope.currentView||"Grid",$scope.showPrintIcon=appDescriptor.getConfigValue("wardListPrintEnabled")||!1,$scope.currentView=$rootScope.currentView,$rootScope.bedDetails&&($scope.oldBedNumber=$rootScope.bedDetails.bedNumber,_.some($scope.room.beds,function(row){var selectedBed=_.filter(row,function(bed){return bed.bed.bedId===$rootScope.bedDetails.bedId});if(selectedBed.length)return $scope.selectedBed=selectedBed[0].bed,!0}),$rootScope.selectedBedInfo.bed=$scope.selectedBed,"bedManagement.patient"!==$state.current.name&&($scope.oldBedNumber=void 0))};$scope.toggleWardView=function(){$rootScope.currentView="Grid"===$rootScope.currentView?"List":"Grid",$scope.currentView=$rootScope.currentView},$scope.printWardList=function(){var printTemplateUrl=appService.getAppDescriptor().getConfigValue("wardListPrintViewTemplateUrl")||"views/wardListPrint.html",configuredTableHeader=appService.getAppDescriptor().getConfigValue("wardListPrintAttributes");configuredTableHeader&&configuredTableHeader.length>0&&($scope.tableHeader=configuredTableHeader),printer.print(printTemplateUrl,{wardName:$scope.room.name,date:moment().format("DD-MMM-YYYY"),totalBeds:$scope.room.totalBeds,occupiedBeds:$scope.room.totalBeds-$scope.room.availableBeds,tableData:$scope.tableData,tableHeader:$scope.tableHeader,isEmptyRow:$scope.isEmptyRow})},$scope.isEmptyRow=function(row){for(var i=0;i<$scope.tableHeader.length;i++){var header=$scope.tableHeader[i];if(row[header])return!1}return!0},$scope.$on("event:getTableData",function(event,data){$scope.tableData=data.tableData,$scope.tableHeader=data.tableHeader}),$scope.getTagName=function(tag){return"AVAILABLE"===tag?$translate.instant("KEY_AVAILABLE"):"OCCUPIED"===tag?$translate.instant("KEY_OCCUPIED"):void 0},init()}]),angular.module("bahmni.ipd").controller("editTagsController",["$scope","$rootScope","$q","ngDialog","spinner","messagingService","bedTagMapService",function($scope,$rootScope,$q,ngDialog,spinner,messagingService,bedTagMapService){$scope.allTags=[];var assignedTags=[],unAssignedTags=[],deltaDeSelected=[],selectedValues=[],deltaSelected=[];$scope.values=[];var getTagsInfo=function(){var bedTagMaps=_.map($rootScope.selectedBedInfo.bed.bedTagMaps,function(tagMap){return{tagMapUuid:tagMap.uuid,id:tagMap.bedTag.id,name:tagMap.bedTag.name,uuid:tagMap.bedTag.uuid}});return bedTagMaps},init=function(){assignedTags=getTagsInfo(),bedTagMapService.getAllBedTags().then(function(response){$scope.allTags=response.data.results,selectedValues=getTagsInfo(),unAssignedTags=_.xorBy($scope.allTags,assignedTags,"uuid"),$scope.values=selectedValues})};$scope.search=function(query){var matchingAnswers=[],unselectedValues=_.xorBy($scope.allTags,selectedValues,"uuid");return _.forEach(unselectedValues,function(answer){"object"!=typeof answer.name&&answer.name.toLowerCase().indexOf(query.toLowerCase())!==-1&&matchingAnswers.push(answer)}),_.uniqBy(matchingAnswers,"uuid")},$scope.focusOnTheTest=function(){var autoSelectInput=$("input.input");autoSelectInput[0].focus()},$scope.addItem=function(item){var find=_.find(unAssignedTags,{uuid:item.uuid}),itemList=find?[find]:[];deltaSelected=_.xorBy(deltaSelected,itemList,"uuid"),selectedValues=_.union(assignedTags,deltaSelected,"uuid"),deltaDeSelected=_.remove(deltaDeSelected,function(value){return value.uuid!==item.uuid}),selectedValues=_.xorBy(selectedValues,deltaDeSelected,"uuid")},$scope.removeItem=function(item){var find=_.find(assignedTags,{uuid:item.uuid}),itemList=find?[find]:[];deltaDeSelected=_.xorBy(deltaDeSelected,itemList,"uuid"),deltaSelected=_.filter(deltaSelected,function(value){return value.uuid!==item.uuid}),selectedValues=_.filter(selectedValues,function(value){return value.uuid!==item.uuid})},$scope.removeFreeTextItem=function(){var value=$("input.input").val();_.isEmpty($scope.search(value))&&$("input.input").val("")};var assignTagsToBed=function(){_.each(deltaSelected,function(bedTag){bedTagMapService.assignTagToABed(bedTag.id,$rootScope.selectedBedInfo.bed.bedId).then(function(response){var bedTags=$rootScope.selectedBedInfo.bed.bedTagMaps||[],bedTagMapEntry={uuid:response.data.uuid,bedTag:bedTag};bedTags.push(bedTagMapEntry)})}),ngDialog.close()},unAssignTagsFromBed=function(){_.each(deltaDeSelected,function(bedTag){bedTagMapService.unAssignTagFromTheBed(bedTag.tagMapUuid).then(function(){$rootScope.selectedBedInfo.bed.bedTagMaps=_.filter($rootScope.selectedBedInfo.bed.bedTagMaps,function(bedTagMap){return bedTagMap.bedTag.uuid!==bedTag.uuid})})})};$scope.updateTagsForTheSelectedBed=function(){spinner.forPromise($q.all(unAssignTagsFromBed(),assignTagsToBed()).then(function(){messagingService.showMessage("info","TAGS_UPDATED_SUCCESSFULLY_MESSAGE")}))},$scope.cancelConfirmationDialog=function(){ngDialog.close()},$scope.disableTagButton=function(tag){var selectedTag=_.filter($scope.values,function(tagEntry){return _.isMatch(tagEntry,{uuid:tag.uuid})});return selectedTag.length>0},$scope.onClickingTheTag=function(tag){$scope.addItem(tag),$scope.values=selectedValues},init()}]),angular.module("bahmni.ipd").controller("RoomListController",["$scope","queryService","appService",function($scope,queryService,appService){var getRoomListDetails=function(roomName){var wardListSqlSearchHandler=appService.getAppDescriptor().getConfigValue("wardListSqlSearchHandler"),params={q:wardListSqlSearchHandler,v:"full",location_name:roomName};return queryService.getResponseFromQuery(params).then(function(response){$scope.tableDetails=response.data,$scope.tableHeadings=$scope.tableDetails.length>0?Object.keys($scope.tableDetails[0]):[],$scope.$emit("event:getTableData",{tableData:$scope.tableDetails,tableHeader:$scope.tableHeadings})})};$scope.$on("event:changeBedList",function(event,roomName){getRoomListDetails(roomName)}),$scope.sortTableDataBy=function(sortColumn){var nonEmptyObjects=_.filter($scope.tableDetails,function(entry){return entry[sortColumn]}),emptyObjects=_.difference($scope.tableDetails,nonEmptyObjects),sortedNonEmptyObjects=_.sortBy(nonEmptyObjects,sortColumn);$scope.reverseSort&&sortedNonEmptyObjects.reverse(),$scope.tableDetails=sortedNonEmptyObjects.concat(emptyObjects),$scope.sortColumn=sortColumn,$scope.reverseSort=!$scope.reverseSort};var init=function(){return $scope.reverseSort=!1,getRoomListDetails($scope.room.name)};init()}]),angular.module("bahmni.ipd").controller("RoomGridController",["$scope","$rootScope","$state","$translate",function($scope,$rootScope,$state,$translate){$scope.getColorForTheTag=function(bed){_.forEach($rootScope.bedTagsColorConfig,function(tagConfig){bed.bedTagMaps.length>=2?"MultiTag"===$translate.instant(tagConfig.name)&&(bed.bedTagMaps[0].bedTag.color=tagConfig.color):angular.isDefined(bed.bedTagMaps[0])&&$translate.instant(tagConfig.name)===bed.bedTagMaps[0].bedTag.name&&(bed.bedTagMaps[0].bedTag.color=tagConfig.color)}),setDefaultTagColor(bed)};var setDefaultTagColor=function(bed){angular.isDefined(bed.bedTagMaps[0])&&void 0===bed.bedTagMaps[0].bedTag.color&&(bed.bedTagMaps[0].bedTag.color="#D3D3D3")};$scope.onSelectBed=function(bed){if("bedManagement.bed"===$state.current.name||"bedManagement"===$state.current.name){"AVAILABLE"===bed.status&&($rootScope.patient=void 0),$rootScope.selectedBedInfo.bed=bed;var options={bedId:bed.bedId};$state.go("bedManagement.bed",options)}else"bedManagement.patient"===$state.current.name&&($rootScope.selectedBedInfo.bed=bed,bed.patient&&$scope.$emit("event:updateSelectedBedInfoForCurrentPatientVisit",bed.patient.uuid))}}]),angular.module("bahmni.ipd").directive("adtPatientSearch",["$timeout",function($timeout){return{restrict:"E",controller:"PatientsListController",templateUrl:"../common/patient-search/views/patientsList.html"}}]),angular.module("bahmni.ipd").directive("adt",[function(){return{restrict:"E",controller:"AdtController",scope:{patient:"=",encounterConfig:"=?bind",bed:"="},templateUrl:"../bedmanagement/views/adt.html"}}]),angular.module("bahmni.ipd").directive("ward",[function(){return{restrict:"E",controller:"WardController",scope:{ward:"="},templateUrl:"../bedmanagement/views/ward.html"}}]),angular.module("bahmni.ipd").directive("room",[function(){return{restrict:"E",controller:"RoomController",scope:{room:"="},templateUrl:"../bedmanagement/views/room.html"}}]),angular.module("bahmni.ipd").directive("editAdtObservations",["$rootScope","$state","spinner","encounterService","observationsService","sessionService","conceptSetService","conceptSetUiConfigService","messagingService",function($rootScope,$state,spinner,encounterService,observationsService,sessionService,conceptSetService,conceptSetUiConfigService,messagingService){var controller=function($scope){$scope.assignBedsPrivilege=Bahmni.IPD.Constants.assignBedsPrivilege;var getEncounterDataFor=function(obs,encounterTypeUuid,visitTypeUuid){var encounterData={};return encounterData.patientUuid=$scope.patient.uuid,encounterData.encounterTypeUuid=encounterTypeUuid,encounterData.visitTypeUuid=visitTypeUuid,encounterData.observations=angular.copy(obs),encounterData.locationUuid=sessionService.getLoginLocationUuid(),encounterData},toggleDisabledObservation=function(editMode){$scope.editMode=editMode,_.each($scope.observations[0].groupMembers,function(member){member.disabled=!editMode})},getNonEmptyObservations=function(){var observations=angular.copy($scope.observations[0]);return observations.groupMembers=_.filter(observations.groupMembers,function(member){return!_.isEmpty(member.value)}),_.isEmpty(observations.groupMembers)?(messagingService.showMessage("error","DATE_OF_DISCHARGE_AND_REASON_FOR_DISCHARGE_CANNOT_BE_EMPTY_MESSAGE"),setValuesForObservations($scope.savedObservations),[]):[observations]};$scope.edit=function(){$scope.savedObservations=angular.copy($scope.observations[0]),toggleDisabledObservation(!0)},$scope.save=function(){toggleDisabledObservation(!1);var observations=getNonEmptyObservations();if(null!==$scope.visitTypeUuid&&!_.isEmpty(observations)){var encounterData=getEncounterDataFor(observations,$rootScope.encounterConfig.getConsultationEncounterTypeUuid(),$scope.visitTypeUuid);return encounterService.create(encounterData).then(function(){toggleDisabledObservation(!1)})}},$scope.cancel=function(){setValuesForObservations($scope.savedObservations),toggleDisabledObservation(!1)};var resetObservationValues=function(){_.each($scope.observations[0].groupMembers,function(member){member.value=void 0})},fetchLatestObsFor=function(conceptNames){return observationsService.fetch($scope.patient.uuid,conceptNames,"latest",null,null,null,null,null).then(function(response){resetObservationValues(),toggleDisabledObservation(!1),response.data.length&&setValuesForObservations(response.data[0])})};$scope.$watch("patient",function(oldValue,newValue){if(oldValue!==newValue)return fetchLatestObsFor($scope.conceptSetName)});var getConceptSetByConceptName=function(conceptSetName){return conceptSetService.getConcept({name:conceptSetName,v:"bahmni"}).then(function(response){return response.data.results[0]})},constructObservationTemplate=function(conceptSetName){return getConceptSetByConceptName(conceptSetName).then(function(conceptSet){var observationMapper=new Bahmni.ConceptSet.ObservationMapper;return observationMapper.map([],conceptSet,conceptSetUiConfigService.getConfig())})},setValuesForObservations=function(obsGroup){$scope.observations[0].value=obsGroup.value,_.each(obsGroup.groupMembers,function(obsGroupMember){_.each($scope.observations[0].groupMembers,function(member){member.concept.uuid===obsGroupMember.concept.uuid&&(member.value=obsGroupMember.value,member.disabled=!0)})})},init=function(){return $scope.promiseResolved=!1,$scope.observations=[],$scope.editMode=!1,$scope.onBedManagement=$state.current&&"bedManagement.bed"===$state.current.name,constructObservationTemplate($scope.conceptSetName).then(function(observation){if($scope.observations[0]=observation,toggleDisabledObservation(!1),$scope.promiseResolved=!0,$rootScope.patient&&$rootScope.bedDetails)return observationsService.fetch($scope.patient.uuid,[$scope.conceptSetName],"latest",1,null,null,null,null).then(function(response){response.data.length&&setValuesForObservations(response.data[0])})})};spinner.forPromise(init())};return{restrict:"E",scope:{patient:"=",conceptSetName:"=",editMode:"=",visitTypeUuid:"="},controller:controller,templateUrl:"views/editAdtObservations.html"}}]),angular.module("bahmni.ipd").directive("roomList",[function(){return{restrict:"E",controller:"RoomListController",scope:{room:"="},templateUrl:"../bedmanagement/views/roomList.html"}}]),angular.module("bahmni.ipd").directive("roomGrid",[function(){return{restrict:"E",controller:"RoomGridController",scope:{room:"="},templateUrl:"../bedmanagement/views/roomGrid.html"}}]),angular.module("bahmni.ipd").directive("backLinksCacheBuster",["$state","$window",function($state,$window){var controller=function($scope,$state,$window){$scope.navigationLinks=$state.current.data.navigationLinks,$scope.homeBackLink=$state.current.data.homeBackLink,$scope.isCurrentState=function(link){return("home"===$state.current.name||"bedManagement.patient"===$state.current.name)&&"ADMIT_HOME_KEY"===link.name||(("bedManagement"===$state.current.name||"bedManagement.bed"===$state.current.name)&&"BED_MANAGEMENT_KEY"===link.name||void 0)},$scope.linkAction=function(type,value,params){"state"===type?onClickState(value,params):$window.location.href=value};var onClickState=function(value,params){params||(params={}),params.dashboardCachebuster=Math.random(),$state.go(value,params)}};return{restrict:"E",controller:controller,templateUrl:"views/backLinks.html",scope:{type:"=",name:"=",value:"=",params:"=",icon:"=",accessKey:"="}}}]),angular.module("bahmni.ipd").service("wardService",["$http",function($http){this.bedsForWard=function(uuid){return $http.get(Bahmni.IPD.Constants.admissionLocationUrl+uuid,{method:"GET",params:{v:"full"},withCredentials:!0})},this.getWardsList=function(){return $http.get(Bahmni.IPD.Constants.admissionLocationUrl)}}]),angular.module("bahmni.ipd").service("bedManagementService",[function(){var maxX,maxY,minX,minY,initialiseMinMaxRowColumnNumbers=function(){maxX=1,maxY=1,minX=1,minY=1};this.createLayoutGrid=function(bedLayouts){initialiseMinMaxRowColumnNumbers(),self.layout=[],findMaxYMaxX(bedLayouts);for(var bedLayout,rowLayout=[],i=minX;i<=maxX;i++){rowLayout=[];for(var j=minY;j<=maxY;j++)bedLayout=getBedLayoutWithCoordinates(i,j,bedLayouts),rowLayout.push({empty:isEmpty(bedLayout),available:isAvailable(bedLayout),bed:{bedId:null!==bedLayout&&bedLayout.bedId,bedNumber:null!==bedLayout&&bedLayout.bedNumber,bedType:null!==bedLayout&&null!==bedLayout.bedType&&bedLayout.bedType.displayName,bedTagMaps:null!==bedLayout&&bedLayout.bedTagMaps,status:null!==bedLayout&&bedLayout.status,patient:null!==bedLayout&&bedLayout.patient}});self.layout.push(rowLayout)}return self.layout};var findMaxYMaxX=function(bedLayouts){for(var i=0;i<bedLayouts.length;i++){var bedLayout=bedLayouts[i];bedLayout.rowNumber>maxX&&(maxX=bedLayout.rowNumber),bedLayout.columnNumber>maxY&&(maxY=bedLayout.columnNumber)}},getBedLayoutWithCoordinates=function(rowNumber,columnNumber,bedLayouts){for(var i=0,len=bedLayouts.length;i<len;i++)if(bedLayouts[i].rowNumber===rowNumber&&bedLayouts[i].columnNumber===columnNumber)return bedLayouts[i];return null},isEmpty=function(bedLayout){return null===bedLayout||null===bedLayout.bedId},isAvailable=function(bedLayout){return null!==bedLayout&&"AVAILABLE"===bedLayout.status}}]),angular.module("bahmni.ipd").service("queryService",["$http",function($http){this.getResponseFromQuery=function(params){return $http.get(Bahmni.Common.Constants.sqlUrl,{method:"GET",params:params,withCredentials:!0})}}]),angular.module("bahmni.ipd").service("bedTagMapService",["$http",function($http){this.getAllBedTags=function(){return $http.get(Bahmni.IPD.Constants.getAllBedTags,{params:{},withCredentials:!0})},this.assignTagToABed=function(bedTagId,bedId){var requestPayload={bedTag:{id:bedTagId},bed:{id:bedId}},headers={"Content-Type":"application/json",Accept:"application/json"};return $http.post(Bahmni.IPD.Constants.bedTagMapUrl,requestPayload,headers)},this.unAssignTagFromTheBed=function(bedTagMapUuid){return $http.delete(Bahmni.IPD.Constants.bedTagMapUrl+bedTagMapUuid)}}]);