"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.Common=Bahmni.Common||{},Bahmni.Common.Models=Bahmni.Common.Models||{},angular.module("bahmni.common.models",[]);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})}}]),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.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,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","Incorrect Configuration: "+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:'
',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&¤tExtensions){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})}}]),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.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()}}}]);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/",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/visit",bahmniDispositionByPatientUrl:BAHMNI_CORE+"/disposition/patient",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",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",defaultPossibleRelativeSearchLimit:10}}(),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+" "+$translate.instant("CLINICAL_YEARS_TRANSLATION_KEY")+" "),age.months&&(ageInString+=age.months+" "+$translate.instant("CLINICAL_MONTHS_TRANSLATION_KEY")+" "),age.days&&(ageInString+=age.days+" "+$translate.instant("CLINICAL_DAYS_TRANSLATION_KEY")+" "),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:""+$rootScope.genderMap[angular.uppercase(genderChar)]+""},getPatientBloodGroupText=function(openmrsPatient){if(openmrsPatient.person.bloodGroup)return""+openmrsPatient.person.bloodGroup+"";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""+bloodGroup+""}},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){var patient=$http.get(Bahmni.Common.Constants.openmrsUrl+"/ws/rest/v1/patient/"+uuid,{method:"GET",params:{v:"full"},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.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:"&"}}});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",[]);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}}),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.logging").service("auditLogService",["$http","$translate","configurationService",function($http,$translate,configurationService){var DateUtil=Bahmni.Common.Util.DateUtil,convertToLocalDate=function(date){var localDate=DateUtil.parseLongDateToServerFormat(date);return DateUtil.getDateTimeInSpecifiedFormat(localDate,"MMMM Do, YYYY [at] h:mm:ss A")};this.getLogs=function(params){return params=params||{},$http.get(Bahmni.Common.Constants.auditLogUrl,{params:params}).then(function(response){return response.data.map(function(log){log.dateCreated=convertToLocalDate(log.dateCreated);var entity=log.message?log.message.split("~")[1]:void 0;return log.params=entity?JSON.parse(entity):entity,log.message=log.message.split("~")[0],log.displayMessage=$translate.instant(log.message,log),log})})},this.log=function(patientUuid,eventType,messageParams,module){return configurationService.getConfigurations(["enableAuditLog"]).then(function(result){if(result.enableAuditLog){var params={};return params.patientUuid=patientUuid,params.eventType=Bahmni.Common.AuditLogEventDetails[eventType].eventType,params.message=Bahmni.Common.AuditLogEventDetails[eventType].message,params.message=messageParams?params.message+"~"+JSON.stringify(messageParams):params.message,params.module=module,$http.post(Bahmni.Common.Constants.auditLogUrl,params,{withCredentials:!0})}})}}]),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},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("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)}),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 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){return $http.get(Bahmni.Common.Constants.bahmniEncounterUrl+"/"+encounterUuid,{params:{includeAll:!0},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){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};return $http.get(Bahmni.Common.Constants.observationsUrl+"/flowSheet",{params:params,withCredentials:!0})}}]);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}();angular.module("bahmni.common.domain").service("visitDocumentService",["$http","auditLogService","configurations","$q",function($http,auditLogService,configurations,$q){var removeVoidedDocuments=function(documents){documents.forEach(function(document){if(document.voided&&document.image){var url=Bahmni.Common.Constants.RESTWS_V1+"/bahmnicore/visitDocument?filename="+document.image;$http["delete"](url,{withCredentials:!0})}})};this.save=function(visitDocument){var url=Bahmni.Common.Constants.RESTWS_V1+"/bahmnicore/visitDocument",isNewVisit=!visitDocument.visitUuid;removeVoidedDocuments(visitDocument.documents);var visitTypeName=configurations.encounterConfig().getVisitTypeByUuid(visitDocument.visitTypeUuid).name,encounterTypeName=configurations.encounterConfig().getEncounterTypeByUuid(visitDocument.encounterTypeUuid).name;return $http.post(url,visitDocument).then(function(response){var promise=isNewVisit?auditLogService.log(visitDocument.patientUuid,"OPEN_VISIT",{visitUuid:response.data.visitUuid,visitType:visitTypeName},encounterTypeName):$q.when();return promise.then(function(){return auditLogService.log(visitDocument.patientUuid,"EDIT_ENCOUNTER",{encounterUuid:response.data.encounterUuid,encounterType:encounterTypeName},encounterTypeName).then(function(){return response})})})},this.saveFile=function(file,patientUuid,encounterTypeName,fileName,fileType){var searchStr=";base64",format=file.split(searchStr)[0].split("/")[1];"video"===fileType&&(format=_.last(_.split(fileName,".")));var url=Bahmni.Common.Constants.RESTWS_V1+"/bahmnicore/visitDocument/uploadDocument";return $http.post(url,{content:file.substring(file.indexOf(searchStr)+searchStr.length,file.length),format:format,patientUuid:patientUuid,encounterTypeName:encounterTypeName,fileType:fileType||"file"},{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.getFileType=function(fileType){var pdfType="pdf",imageType="image";return fileType.indexOf(pdfType)!==-1?pdfType:fileType.indexOf(imageType)!==-1?imageType:"not_supported"}}]),Bahmni.Common.Domain.ProviderMapper=function(){this.map=function(openMrsProvider){return openMrsProvider?{uuid:openMrsProvider.uuid,name:openMrsProvider.preferredName?openMrsProvider.preferredName.display:openMrsProvider.person.preferredName.display}:null}},angular.module("bahmni.common.gallery",[]),angular.module("bahmni.common.gallery").directive("bmGalleryPane",["$rootScope","$document","observationsService","encounterService","spinner","configurations","ngDialog",function($rootScope,$document,observationsService,encounterService,spinner,configurations,ngDialog){function close(){$("body #gallery-pane").remove(),$body.removeClass("gallery-open"),keyboardJS.releaseKey("right"),keyboardJS.releaseKey("left")}var $body=$document.find("body");$rootScope.$on("$stateChangeStart",function(){close()});var link=function($scope,element){$scope.galleryElement=element,$body.prepend($scope.galleryElement).addClass("gallery-open"),keyboardJS.on("right",function(){$scope.$apply(function(){$scope.getTotalLength()>1&&$scope.showNext()})}),keyboardJS.on("left",function(){$scope.$apply(function(){$scope.getTotalLength()>1&&$scope.showPrev()})})},controller=function($scope){$scope.imageIndex=$scope.imagePosition.index?$scope.imagePosition.index:0,$scope.albumTag=$scope.imagePosition.tag?$scope.imagePosition.tag:"defaultTag",$scope.showImpression=!1,$scope.isActive=function(index,tag){return $scope.imageIndex==index&&$scope.albumTag==tag};var getAlbumIndex=function(){return _.findIndex($scope.albums,function(album){return album.tag==$scope.albumTag})};$scope.showPrev=function(){var albumIndex=getAlbumIndex();if($scope.imageIndex>0)--$scope.imageIndex;else{0==albumIndex&&(albumIndex=$scope.albums.length);var previousAlbum=$scope.albums[albumIndex-1];0==previousAlbum.images.length&&$scope.showPrev(albumIndex-1),$scope.albumTag=previousAlbum.tag,$scope.imageIndex=previousAlbum.images.length-1}},$scope.showNext=function(){var albumIndex=getAlbumIndex();if($scope.imageIndex<$scope.albums[albumIndex].images.length-1)++$scope.imageIndex;else{albumIndex==$scope.albums.length-1&&(albumIndex=-1);var nextAlbum=$scope.albums[albumIndex+1];0==nextAlbum.images.length&&$scope.showNext(albumIndex+1),$scope.albumTag=nextAlbum.tag,$scope.imageIndex=0}},$scope.isPdf=function(image){return image.src&&image.src.indexOf(".pdf")>0},$scope.getTotalLength=function(){var totalLength=0;return angular.forEach($scope.albums,function(album){totalLength+=album.images.length}),totalLength},$scope.getCurrentIndex=function(){for(var currentIndex=1,i=0;i