"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})},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.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:'',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/",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"}}(),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,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.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)});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})}}]);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;i0},$scope.saveImpression=function(image){var bahmniEncounterTransaction=mapBahmniEncounterTransaction(image);spinner.forPromise(encounterService.create(bahmniEncounterTransaction).then(function(){constructNewSourceObs(image),fetchObsRelationship(image)}))};var init=function(){$scope.accessImpression&&$scope.albums.forEach(function(album){album.images.forEach(function(image){fetchObsRelationship(image),constructNewSourceObs(image)})}),ngDialog.openConfirm({template:"../common/gallery/views/gallery.html",scope:$scope,closeByEscape:!0,className:"gallery-dialog ngdialog-theme-default"})},fetchObsRelationship=function(image){observationsService.getObsRelationship(image.uuid).then(function(response){image.sourceObs=response.data})},constructNewSourceObs=function(image){image.newSourceObs=$scope.newSourceObs&&$scope.newSourceObs.targetObsRelation.targetObs.uuid===image.uuid?$scope.targetObs:{value:"",concept:{uuid:configurations.impressionConcept().uuid},targetObsRelation:{relationshipType:Bahmni.Common.Constants.qualifiedByRelationshipType,targetObs:{uuid:image.uuid}}}},mapBahmniEncounterTransaction=function(image){return{patientUuid:$scope.patient.uuid,encounterTypeUuid:configurations.encounterConfig().getConsultationEncounterTypeUuid(),observations:[image.newSourceObs]}};init()};return{link:link,controller:controller}}]);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.ArrayUtil={chunk:function(array,chunkSize){for(var chunks=[],i=0;i$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:'
'}}]),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()}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Obs=Bahmni.Common.Obs||{},angular.module("bahmni.common.obs",[]),Bahmni.Common.Obs.ImageObservation=function(observation,concept,provider){this.concept=concept,this.imageObservation=observation,this.dateTime=observation.observationDateTime,this.provider=provider},angular.module("bahmni.common.uiHelper",["ngClipboard"]),angular.module("bahmni.common.uiHelper").filter("reverse",function(){return function(items){return items&&items.slice().reverse()}}),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").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('
'),{element:$(element).find(".dashboard-section-loader")}},showSpinnerForOverlay=function(){var token=Math.random();tokens.push(token),0===$("#overlay").length&&$("body").prepend('
');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=$('').appendTo("body")[0];hiddenFrame.contentWindow.printAndRemove=function(){hiddenFrame.contentWindow.print(),$(hiddenFrame).remove(),deferred.resolve()};var htmlContent=''+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($("
"+template+"
"))(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($("
"+template+"
"))(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("nonBlank",function(){return function($scope,element,attrs){var addNonBlankAttrs=function(){element.attr({required:"required"})},removeNonBlankAttrs=function(){element.removeAttr("required")};return attrs.nonBlank?void $scope.$watch(attrs.nonBlank,function(value){ return value?addNonBlankAttrs():removeNonBlankAttrs()}):addNonBlankAttrs(element)}}).directive("datepicker",function(){var link=function($scope,element,attrs,ngModel){var maxDate=attrs.maxDate,minDate=attrs.minDate||"-120y",format=attrs.dateFormat||"dd-mm-yy";element.datepicker({changeYear:!0,changeMonth:!0,maxDate:maxDate,minDate:minDate,yearRange:"c-120:c+120",dateFormat:format,onSelect:function(dateText){$scope.$apply(function(){ngModel.$setViewValue(dateText)})}})};return{require:"ngModel",link:link}}).directive("myAutocomplete",["$parse",function($parse){var link=function(scope,element,attrs,ngModelCtrl){var source=($parse(attrs.ngModel),scope.source()),responseMap=scope.responseMap(),onSelect=scope.onSelect();element.autocomplete({autofocus:!0,minLength:2,source:function(request,response){source(attrs.id,request.term,attrs.itemType).then(function(data){var results=responseMap?responseMap(data.data):data.data;response(results)})},select:function(event,ui){return scope.$apply(function(scope){ngModelCtrl.$setViewValue(ui.item.value),scope.$eval(attrs.ngChange),null!=onSelect&&onSelect(ui.item)}),!0},search:function(event){var searchTerm=$.trim(element.val());searchTerm.length<2&&event.preventDefault()}})};return{link:link,require:"ngModel",scope:{source:"&",responseMap:"&",onSelect:"&"}}}]).directive("bmForm",["$timeout",function($timeout){var link=function(scope,elem,attrs){$timeout(function(){$(elem).unbind("submit").submit(function(e){var formScope=scope.$parent,formName=attrs.name;e.preventDefault(),scope.autofillable&&$(elem).find("input").trigger("change"),formScope[formName].$valid?(formScope.$apply(attrs.ngSubmit),$(elem).removeClass("submitted-with-error")):$(elem).addClass("submitted-with-error")})},0)};return{link:link,require:"form",scope:{autofillable:"="}}}]).directive("patternValidate",["$timeout",function($timeout){return function($scope,element,attrs){var addPatternToElement=function(){$scope.fieldValidation&&$scope.fieldValidation[attrs.id]&&element.attr({pattern:$scope.fieldValidation[attrs.id].pattern,title:$scope.fieldValidation[attrs.id].errorMessage,type:"text"})};$timeout(addPatternToElement)}}]).directive("validateOn",function(){var link=function(scope,element,attrs,ngModelCtrl){var validationMessage=attrs.validationMessage||"Please enter a valid detail",setValidity=function(value){var valid=!!value;ngModelCtrl.$setValidity("blank",valid),element[0].setCustomValidity(valid?"":validationMessage)};scope.$watch(attrs.validateOn,setValidity,!0)};return{link:link,require:"ngModel"}}),angular.module("bahmni.common.uiHelper").directive("bahmniAutocomplete",["$translate",function($translate){var link=function(scope,element,attrs,ngModelCtrl){var source=scope.source(),responseMap=scope.responseMap&&scope.responseMap(),onSelect=scope.onSelect(),onEdit=scope.onEdit&&scope.onEdit(),minLength=scope.minLength||2,formElement=element[0],validationMessage=scope.validationMessage||$translate.instant("SELECT_VALUE_FROM_AUTOCOMPLETE_DEFAULT_MESSAGE"),validateIfNeeded=function(value){scope.strictSelect&&(scope.isInvalid=value!==scope.selectedValue,_.isEmpty(value)&&(scope.isInvalid=!1))};scope.$watch("initialValue",function(){scope.initialValue&&(scope.selectedValue=scope.initialValue,scope.isInvalid=!1)}),element.autocomplete({autofocus:!0,minLength:minLength,source:function(request,response){source({elementId:attrs.id,term:request.term,elementType:attrs.type}).then(function(data){var results=responseMap?responseMap(data):data;response(results)})},select:function(event,ui){return scope.selectedValue=ui.item.value,ngModelCtrl.$setViewValue(ui.item.value),null!=onSelect&&onSelect(ui.item),validateIfNeeded(ui.item.value),scope.blurOnSelect&&element.blur(),scope.$apply(),scope.$eval(attrs.ngDisabled),scope.$apply(),!0},search:function(event,ui){null!=onEdit&&onEdit(ui.item);var searchTerm=$.trim(element.val());validateIfNeeded(searchTerm),searchTerm.length=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()}},angular.module("bahmni.common.uiHelper").directive("bmGallery",["$location","$rootScope","$compile",function($location,$rootScope,$compile){var controller=function($scope){$scope.albums=[],$scope.imagePosition={tag:void 0,index:0},this.image=function(record){var provider=record.provider;return{src:Bahmni.Common.Constants.documentsPath+"/"+record.imageObservation.value,title:record.concept.name,commentOnUpload:record.comment||record.imageObservation.comment,date:record.imageObservation.observationDateTime,uuid:record.imageObservation.uuid,providerName:provider?provider.name:null}},this.addImageObservation=function(record,tag){return this.addImage(this.image(record),tag)},this.addImage=function(image,tag,tagOrder){var matchedAlbum=getMatchingAlbum(tag);if(matchedAlbum){var index=image.imageIndex?image.imageIndex:matchedAlbum.images.length;matchedAlbum.images.splice(index,0,image)}else{var newAlbum={};newAlbum.tag=tag,newAlbum.images=[image],$scope.albums.splice(tagOrder,0,newAlbum)}return $scope.albums[0].images.length-1};var getMatchingAlbum=function(tag){return _.find($scope.albums,function(album){return album.tag==tag})};this.removeImage=function(image,tag,index){var matchedAlbum=getMatchingAlbum(tag);matchedAlbum&&matchedAlbum.images&&matchedAlbum.images.splice(index,1)},this.setIndex=function(tag,index){$scope.imagePosition.tag=tag,$scope.imagePosition.index=index},this.open=function(){$compile("")($scope)}};return{controller:controller,scope:{patient:"=",accessImpression:"=?"}}}]).directive("bmGalleryItem",function(){var link=function($scope,element,attrs,imageGalleryController){var image={src:$scope.image.encodedValue,title:$scope.image.concept?$scope.image.concept.name:"",date:$scope.image.obsDatetime,uuid:$scope.image.obsUuid,providerName:$scope.image.provider?$scope.image.provider.name:"",imageIndex:$scope.image.imageIndex,commentOnUpload:$scope.image.comment};imageGalleryController.addImage(image,$scope.visitUuid,$scope.visitOrder),element.click(function(e){e.stopPropagation(),imageGalleryController.setIndex($scope.visitUuid,$scope.index),imageGalleryController.open()}),element.on("$destroy",function(){imageGalleryController.removeImage(image,$scope.visitUuid,$scope.index)})};return{link:link,scope:{image:"=",index:"@",visitUuid:"=",visitOrder:"@"},require:"^bmGallery"}}).directive("bmImageObservationGalleryItem",function(){var link=function(scope,element,attrs,imageGalleryController){scope.imageIndex=imageGalleryController.addImageObservation(scope.observation,"defaultTag"),element.click(function(e){e.stopPropagation(),imageGalleryController.setIndex("defaultTag",scope.imageIndex),imageGalleryController.open()})};return{link:link,scope:{observation:"="},require:"^bmGallery"}}).directive("bmObservationGalleryItem",function(){var link=function(scope,element,attrs,imageGalleryController){scope.imageObservation=new Bahmni.Common.Obs.ImageObservation(scope.observation,scope.observation.concept,scope.observation.provider),scope.imageIndex=imageGalleryController.addImageObservation(scope.imageObservation,"defaultTag"),element.click(function(e){e.stopPropagation(),imageGalleryController.setIndex("defaultTag",scope.imageIndex),imageGalleryController.open()})};return{link:link,scope:{observation:"="},require:"^bmGallery"}}).directive("bmImageObservationGalleryItems",function(){var link=function(scope,elem,attrs,imageGalleryController){angular.forEach(scope.list,function(record){imageGalleryController.addImageObservation(record,"defaultTag")}),$(elem).click(function(){imageGalleryController.open()})};return{link:link,scope:{list:"="},require:"^bmGallery"}}).directive("bmLazyImageObservationGalleryItems",function(){var link=function(scope,elem,attrs,imageGalleryController){scope.promise.then(function(response){angular.forEach(response,function(record){var index=imageGalleryController.addImageObservation(record,"defaultTag");scope.currentObservation&&scope.currentObservation.imageObservation.uuid==record.imageObservation.uuid&&imageGalleryController.setIndex("defaultTag",index)}),$(elem).click(function(){imageGalleryController.open()})})};return{link:link,scope:{promise:"=",currentObservation:"=?index"},require:"^bmGallery"}}),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").directive("bmBackLinks",function(){return{template:'',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").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.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)})}}}),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}});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)}}]),Bahmni.Common.DocumentImage=function(data){angular.extend(this,data),this.title=this.getTitle(),this.thumbnail=this.getThumbnail()},Bahmni.Common.DocumentImage.prototype={getTitle:function(){var titleComponents=[];return this.concept&&titleComponents.push(this.concept.name),this.obsDatetime&&titleComponents.push(moment(this.obsDatetime).format(Bahmni.Common.Constants.dateDisplayFormat)),titleComponents.join(", ")},getThumbnail:function(){var src=this.src||this.encodedValue;return src&&src.replace(/(.*)\.(.*)$/,"$1_thumbnail.$2")||null}},angular.module("bahmni.common.uiHelper").directive("singleSubmit",function(){var ignoreSubmit=!1,link=function(scope,element){var submitHandler=function(){ignoreSubmit||(ignoreSubmit=!0,scope.singleSubmit().finally(function(){ignoreSubmit=!1}))};element.on("submit",submitHandler),scope.$on("$destroy",function(){element.off("submit",submitHandler)})};return{scope:{singleSubmit:"&"},restrict:"A",link:link}}),angular.module("documentupload",["ui.router","bahmni.common.config","opd.documentupload","bahmni.common.patient","authentication","bahmni.common.appFramework","ngDialog","httpErrorInterceptor","bahmni.common.domain","bahmni.common.i18n","bahmni.common.uiHelper","ngSanitize","bahmni.common.patientSearch","bahmni.common.util","bahmni.common.routeErrorHandler","pascalprecht.translate","ngCookies"]),angular.module("documentupload").config(["$stateProvider","$httpProvider","$urlRouterProvider","$bahmniTranslateProvider","$compileProvider",function($stateProvider,$httpProvider,$urlRouterProvider,$bahmniTranslateProvider,$compileProvider){$urlRouterProvider.otherwise("/search");var patientSearchBackLink={label:"",state:"search",accessKey:"p",id:"patients-link",icon:"fa-users"},homeBackLink={label:"",url:"../home/",accessKey:"h",icon:"fa-home"};$compileProvider.debugInfoEnabled(!1),$stateProvider.state("search",{url:"/search",data:{backLinks:[homeBackLink]},views:{content:{templateUrl:"../common/patient-search/views/patientsList.html",controller:"PatientsListController"},"additional-header":{templateUrl:"../common/ui-helper/header.html"}},resolve:{initialization:"initialization"}}).state("upload",{url:"/patient/:patientUuid/document",data:{backLinks:[homeBackLink,patientSearchBackLink]},views:{header:{templateUrl:"views/patientHeader.html"},content:{templateUrl:"views/documentUpload.html",controller:"DocumentController"},"additional-header":{template:''}},resolve:{initialization:"initialization"}}).state("error",{url:"/error",views:{content:{templateUrl:"../common/ui-helper/error.html"}}}),$httpProvider.defaults.headers.common["Disable-WWW-Authenticate"]=!0,$bahmniTranslateProvider.init({app:"document-upload",shouldMerge:!0})}]).run(["backlinkService","$window",function(backlinkService,$window){FastClick.attach(document.body),moment.locale($window.localStorage.NG_TRANSLATE_LANG_KEY||"en"),backlinkService.addBackUrl()}]);var Bahmni=Bahmni||{};Bahmni.DocumentUpload=Bahmni.DocumentUpload||{},angular.module("opd.documentupload",["bahmni.common.patient","bahmni.common.config","bahmni.common.domain","bahmni.common.gallery","bahmni.common.logging"]),Bahmni.Common.AuditLogEventDetails={USER_LOGIN_SUCCESS:{eventType:"USER_LOGIN_SUCCESS",message:"USER_LOGIN_SUCCESS_MESSAGE"},USER_LOGIN_FAILED:{eventType:"USER_LOGIN_FAILED",message:"USER_LOGIN_FAILED_MESSAGE"},USER_LOGOUT_SUCCESS:{eventType:"USER_LOGOUT_SUCCESS",message:"USER_LOGOUT_SUCCESS_MESSAGE"},OPEN_VISIT:{eventType:"OPEN_VISIT",message:"OPEN_VISIT_MESSAGE"},EDIT_VISIT:{eventType:"EDIT_VISIT",message:"EDIT_VISIT_MESSAGE"},CLOSE_VISIT:{eventType:"CLOSE_VISIT",message:"CLOSE_VISIT_MESSAGE"},CLOSE_VISIT_FAILED:{eventType:"CLOSE_VISIT_FAILED",message:"CLOSE_VISIT_FAILED_MESSAGE"},EDIT_ENCOUNTER:{eventType:"EDIT_ENCOUNTER",message:"EDIT_ENCOUNTER_MESSAGE"},VIEWED_REGISTRATION_PATIENT_SEARCH:{eventType:"VIEWED_REGISTRATION_PATIENT_SEARCH",message:"VIEWED_REGISTRATION_PATIENT_SEARCH_MESSAGE"},VIEWED_NEW_PATIENT_PAGE:{eventType:"VIEWED_NEW_PATIENT_PAGE",message:"VIEWED_NEW_PATIENT_PAGE_MESSAGE"},REGISTER_NEW_PATIENT:{eventType:"REGISTER_NEW_PATIENT",message:"REGISTER_NEW_PATIENT_MESSAGE"},EDIT_PATIENT_DETAILS:{eventType:"EDIT_PATIENT_DETAILS",message:"EDIT_PATIENT_DETAILS_MESSAGE"},ACCESSED_REGISTRATION_SECOND_PAGE:{eventType:"ACCESSED_REGISTRATION_SECOND_PAGE",message:"ACCESSED_REGISTRATION_SECOND_PAGE_MESSAGE"},VIEWED_PATIENT_DETAILS:{eventType:"VIEWED_PATIENT_DETAILS",message:"VIEWED_PATIENT_DETAILS_MESSAGE"},PRINT_PATIENT_STICKER:{eventType:"PRINT_PATIENT_STICKER",message:"PRINT_PATIENT_STICKER_MESSAGE"},VIEWED_CLINICAL_PATIENT_SEARCH:{eventType:"VIEWED_CLINICAL_PATIENT_SEARCH",message:"VIEWED_PATIENT_SEARCH_MESSAGE"},VIEWED_CLINICAL_DASHBOARD:{eventType:"VIEWED_CLINICAL_DASHBOARD",message:"VIEWED_CLINICAL_DASHBOARD_MESSAGE"},VIEWED_OBSERVATIONS_TAB:{eventType:"VIEWED_OBSERVATIONS_TAB",message:"VIEWED_OBSERVATIONS_TAB_MESSAGE"},VIEWED_DIAGNOSIS_TAB:{eventType:"VIEWED_DIAGNOSIS_TAB",message:"VIEWED_DIAGNOSIS_TAB_MESSAGE"},VIEWED_TREATMENT_TAB:{eventType:"VIEWED_TREATMENT_TAB",message:"VIEWED_TREATMENT_TAB_MESSAGE"},VIEWED_DISPOSITION_TAB:{eventType:"VIEWED_DISPOSITION_TAB",message:"VIEWED_DISPOSITION_TAB_MESSAGE"},VIEWED_DASHBOARD_SUMMARY:{eventType:"VIEWED_DASHBOARD_SUMMARY",message:"VIEWED_DASHBOARD_SUMMARY_MESSAGE"},VIEWED_ORDERS_TAB:{eventType:"VIEWED_ORDERS_TAB",message:"VIEWED_ORDERS_TAB_MESSAGE"},VIEWED_BACTERIOLOGY_TAB:{eventType:"VIEWED_BACTERIOLOGY_TAB",message:"VIEWED_BACTERIOLOGY_TAB_MESSAGE"},VIEWED_INVESTIGATION_TAB:{eventType:"VIEWED_INVESTIGATION_TAB",message:"VIEWED_INVESTIGATION_TAB_MESSAGE"},VIEWED_SUMMARY_PRINT:{eventType:"VIEWED_SUMMARY_PRINT",message:"VIEWED_SUMMARY_PRINT_MESSAGE"},VIEWED_VISIT_DASHBOARD:{eventType:"VIEWED_VISIT_DASHBOARD",message:"VIEWED_VISIT_DASHBOARD_MESSAGE"},VIEWED_VISIT_PRINT:{eventType:"VIEWED_VISIT_PRINT",message:"VIEWED_VISIT_PRINT_MESSAGE"},VIEWED_DASHBOARD_OBSERVATION:{eventType:"VIEWED_DASHBOARD_OBSERVATION",message:"VIEWED_DASHBOARD_OBSERVATION_MESSAGE"},VIEWED_PATIENTPROGRAM:{eventType:"VIEWED_PATIENTPROGRAM",message:"VIEWED_PATIENTPROGRAM_MESSAGE"},RUN_REPORT:{eventType:"RUN_REPORT",message:"RUN_REPORT_MESSAGE"}},angular.module("opd.documentupload").factory("initialization",["$rootScope","$q","$window","$location","configurationService","configurations","authenticator","appService","spinner",function($rootScope,$q,$window,$location,configurationService,configurations,authenticator,appService,spinner){var initializationPromise=$q.defer(),url=purl(decodeURIComponent($window.location));$rootScope.appConfig=url.param();var getConfigs=function(){var configNames=["genderMap"];return configurations.load(configNames).then(function(){$rootScope.genderMap=configurations.genderMap()})},getConsultationConfigs=function(){var configNames=["encounterConfig"];return configurationService.getConfigurations(configNames).then(function(configurations){$rootScope.encounterConfig=angular.extend(new EncounterConfig,configurations.encounterConfig)})},validate=function(){var deferrable=$q.defer(),throwValidationError=function(errorMessage){$rootScope.error=errorMessage,initializationPromise.reject(),deferrable.reject()};return null===$rootScope.appConfig.encounterType?throwValidationError("encounterType should be configured in config"):null===$rootScope.encounterConfig.getEncounterTypeUuid($rootScope.appConfig.encounterType)&&throwValidationError("Configured encounterType does not exist"),deferrable.resolve(),deferrable},checkPrivilege=function(){return appService.checkPrivilege("app:document-upload").catch(function(){return initializationPromise.reject()})},initApp=function(){return appService.initApp("documentUpload",{app:!0,extension:!0},$rootScope.appConfig.encounterType)};return $rootScope.$on("$stateChangeError",function(){$location.path("/error")}),authenticator.authenticateUser().then(initApp).then(checkPrivilege).then(getConsultationConfigs).then(validate).then(function(){initializationPromise.resolve()}),spinner.forPromise(initializationPromise.promise).then(getConfigs)}]);var Bahmni=Bahmni||{};Bahmni.DocumentUpload=Bahmni.DocumentUpload||{},Bahmni.DocumentUpload.Constants=function(){return{visitRepresentation:"custom:(uuid,startDatetime,stopDatetime,visitType,patient)"}}(),Bahmni.DocumentUpload.Visit=function(){var DocumentImage=Bahmni.Common.DocumentImage;this.startDatetime="",this.stopDatetime="",this.visitType=null,this.uuid=null,this.changed=!1,this.files=[];var androidDateFormat="YYYY-MM-DD hh:mm:ss";this._sortSavedFiles=function(savedFiles){return savedFiles.sort(function(file1,file2){return file1.id-file2.id}),savedFiles},this.initSavedFiles=function(encounters){this.files=[];var providerMapper=new Bahmni.Common.Domain.ProviderMapper,savedFiles=this.files;encounters.forEach(function(encounter){encounter.obs&&encounter.obs.forEach(function(observation){observation.groupMembers&&observation.groupMembers.forEach(function(member){var conceptName=observation.concept.name.name;savedFiles.push(new DocumentImage({id:member.id,encodedValue:Bahmni.Common.Constants.documentsPath+"/"+member.value,obsUuid:observation.uuid,obsDatetime:member.obsDatetime,visitUuid:encounter.visit.uuid,encounterUuid:encounter.uuid,provider:providerMapper.map(encounter.provider),concept:{uuid:observation.concept.uuid,editableName:conceptName,name:conceptName},comment:member.comment}))})})}),this.files=this._sortSavedFiles(savedFiles),this.assignImageIndex()},this.assignImageIndex=function(){ var imageIndex=this.getNoOfImages()-1;this.files.map(function(file){return file.encodedValue.indexOf(".pdf")>0||(file.imageIndex=imageIndex,imageIndex--),file})},this.getNoOfImages=function(){var imageFiles=_.filter(this.files,function(file){return!(file.encodedValue.indexOf(".pdf")>0)});return imageFiles.length},this.isNew=function(){return null===this.uuid},this.hasFiles=function(){return this.files.length>0},this.startDate=function(){return this.isNew()?this.parseDate(this.startDatetime):moment(this.startDatetime).toDate()},this.endDate=function(){return this.stopDatetime?this.parseDate(this.stopDatetime):void 0},this.parseDate=function(date){if(date instanceof Date)return date;var dateFormat=date&&date.indexOf("-")!==-1?androidDateFormat:Bahmni.Common.Constants.dateFormat;return moment(date,dateFormat).toDate()},this.addFile=function(file){var savedImage=null,alreadyPresent=this.files.filter(function(img){return img.encodedValue===file});return 0===alreadyPresent.length&&(savedImage=new DocumentImage({encodedValue:file,new:!0}),this.files.push(savedImage)),this.assignImageIndex(),this.markAsUpdated(),savedImage},this.markAsUpdated=function(){this.changed=this.files.some(function(file){return file.changed||!file.obsUuid||file.voided})},this.isSaved=function(file){return!!file.obsUuid},this.removeFile=function(file){this.isSaved(file)?this.toggleVoidingOfFile(file):this.removeNewAddedFile(file)},this.removeNewAddedFile=function(file){var i=this.files.indexOf(file);this.files.splice(i,1),this.assignImageIndex(),this.markAsUpdated()},this.toggleVoidingOfFile=function(file){file.voided=!file.voided,this.markAsUpdated()},this.hasErrors=function(){var imageHasError=_.find(this.files,function(file){return!(file.voided||file.concept&&file.concept.editableName&&file.concept.uuid)});return!!imageHasError},this.hasVisitType=function(){return!(!this.visitType||!this.visitType.uuid)}},angular.module("opd.documentupload").directive("fileUpload",[function(){var link=function(scope,element){element.bind("change",function(){var files=element[0].files;angular.forEach(files,function(file,index){var reader=new FileReader;reader.onload=function(event){scope.onSelect()(event.target.result,scope.visit,file.name,file.type)},reader.readAsDataURL(file)})})};return{restrict:"A",scope:{visit:"=",onSelect:"&"},link:link}}]),angular.module("opd.documentupload").directive("dateValidator",function(){var DateUtil=Bahmni.Common.Util.DateUtil,isVisitDateFromFuture=function(visitDate){return!(!visitDate.startDatetime&&!visitDate.stopDatetime)&&(DateUtil.getDate(visitDate.startDatetime)>new Date||DateUtil.getDate(visitDate.stopDatetime)>new Date)},isStartDateBeforeEndDate=function(visitDate){return!visitDate.startDatetime||!visitDate.stopDatetime||DateUtil.getDate(visitDate.startDatetime)<=DateUtil.getDate(visitDate.stopDatetime)};return{restrict:"A",require:"ngModel",link:function(scope,element,attrs,ngModel){function validate(){ngModel.$setValidity("overlap",scope.isNewVisitDateValid()),ngModel.$setValidity("future",!isVisitDateFromFuture(scope.newVisit)),ngModel.$setValidity("dateSequence",isStartDateBeforeEndDate(scope.newVisit))}scope.$watch(attrs.ngModel,validate),scope.$watch(attrs.dependentModel,validate)}}}),angular.module("opd.documentupload").controller("DocumentController",["$scope","$stateParams","visitService","patientService","encounterService","spinner","visitDocumentService","$rootScope","$http","$q","$timeout","sessionService","$anchorScroll","$translate","messagingService",function($scope,$stateParams,visitService,patientService,encounterService,spinner,visitDocumentService,$rootScope,$http,$q,$timeout,sessionService,$anchorScroll,$translate,messagingService){var encounterTypeUuid,topLevelConceptUuid,customVisitParams=Bahmni.DocumentUpload.Constants.visitRepresentation,DateUtil=Bahmni.Common.Util.DateUtil,patientMapper=new Bahmni.PatientMapper($rootScope.patientConfig,$rootScope,$translate),activeEncounter={},locationUuid=sessionService.getLoginLocationUuid();$scope.visits=[],$scope.fileTypeConcepts=[],$scope.toggleGallery=!0,$scope.conceptNameInvalid=!1;var setOrientationWarning=function(){$scope.orientation_warning=window.orientation&&(window.orientation<0||window.orientation>90)};setOrientationWarning();var onOrientationChange=function(){$scope.$apply(setOrientationWarning)};window.addEventListener("orientationchange",onOrientationChange),$scope.$on("$destroy",function(){window.removeEventListener("orientationchange",onOrientationChange)});var initNewVisit=function(){$scope.newVisit=new Bahmni.DocumentUpload.Visit,$scope.currentVisit=$scope.newVisit},createVisit=function(visit){return angular.extend(new Bahmni.DocumentUpload.Visit,visit)},getVisitTypes=function(){return visitService.getVisitType().then(function(response){$scope.visitTypes=response.data.results})},getPatient=function(){return patientService.getPatient($stateParams.patientUuid).success(function(openMRSPatient){$rootScope.patient=patientMapper.map(openMRSPatient)})},getVisitStartStopDateTime=function(visit){return{startDatetime:DateUtil.getDate(visit.startDatetime),stopDatetime:DateUtil.getDate(visit.stopDatetime)}},isVisitInSameRange=function(newVisitWithoutTime,existingVisit){return existingVisit.startDatetime<=newVisitWithoutTime.stopDatetime&&(newVisitWithoutTime.startDatetime<=existingVisit.stopDatetime||DateUtil.isInvalid(existingVisit.stopDatetime))};$scope.isNewVisitDateValid=function(){var filterExistingVisitsInSameDateRange=function(existingVisit){return!DateUtil.isInvalid(newVisitWithoutTime.startDatetime)&&isVisitInSameRange(newVisitWithoutTime,existingVisit)},newVisitWithoutTime={};newVisitWithoutTime.startDatetime=DateUtil.getDate($scope.newVisit.startDatetime),newVisitWithoutTime.stopDatetime=$scope.newVisit.stopDatetime?DateUtil.getDate($scope.newVisit.stopDatetime):DateUtil.now();var visitStartStopDateTime=$scope.visits.map(getVisitStartStopDateTime),existingVisitsInSameRange=visitStartStopDateTime.filter(filterExistingVisitsInSameDateRange);return $scope.isDateValid=0===existingVisitsInSameRange.length,0===existingVisitsInSameRange.length};var getVisits=function(){return visitService.search({patient:$rootScope.patient.uuid,v:customVisitParams,includeInactive:!0}).then(function(response){var visits=response.data.results;visits.length>0&&(visits[0].stopDatetime?$scope.currentVisit=null:$scope.currentVisit=visits[0]),visits.forEach(function(visit){$scope.visits.push(createVisit(visit))})})},getEncountersForVisits=function(){return encounterService.getEncountersForEncounterType($rootScope.patient.uuid,encounterTypeUuid).success(function(encounters){$scope.visits.forEach(function(visit){var visitEncounters=encounters.results.filter(function(a){return a.visit.uuid===visit.uuid});visit.initSavedFiles(visitEncounters)})})},getTopLevelConcept=function(){return null===$rootScope.appConfig.topLevelConcept?(topLevelConceptUuid=null,$q.when({})):$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{params:{name:$rootScope.appConfig.topLevelConcept,v:"custom:(uuid,setMembers:(uuid,name:(name)))"}}).then(function(response){response.data.results[0].setMembers&&response.data.results[0].setMembers.length>0&&response.data.results[0].setMembers.forEach(function(concept){var conceptToAdd={concept:{uuid:concept.uuid,name:concept.name.name,editableName:concept.name.name}};$scope.fileTypeConcepts.push(conceptToAdd)});var topLevelConcept=response.data.results[0];topLevelConceptUuid=topLevelConcept?topLevelConcept.uuid:null})},sortVisits=function(){$scope.visits.sort(function(a,b){var date1=DateUtil.parse(a.startDatetime),date2=DateUtil.parse(b.startDatetime);return date2.getTime()-date1.getTime()})},getActiveEncounter=function(){var currentProviderUuid=$rootScope.currentProvider?$rootScope.currentProvider.uuid:null;return encounterService.find({patientUuid:$stateParams.patientUuid,encounterTypeUuids:[encounterTypeUuid],providerUuids:_.isEmpty(currentProviderUuid)?null:[currentProviderUuid],includeAll:Bahmni.Common.Constants.includeAllObservations,locationUuid:locationUuid}).then(function(encounterTransactionResponse){activeEncounter=encounterTransactionResponse.data})},init=function(){encounterTypeUuid=$scope.encounterConfig.getEncounterTypeUuid($rootScope.appConfig.encounterType),initNewVisit();var deferrables=$q.defer(),promises=[];return promises.push(getVisitTypes()),promises.push(getActiveEncounter()),promises.push(getPatient().then(getVisits).then(getEncountersForVisits)),promises.push(getTopLevelConcept()),$q.all(promises).then(function(){deferrables.resolve()}),deferrables.promise};spinner.forPromise(init()),$scope.getConcepts=function(request){return $http.get(Bahmni.Common.Constants.conceptUrl,{params:{q:request.term,memberOf:topLevelConceptUuid,v:"custom:(uuid,name)"}}).then(function(result){return result.data.results})},$scope.getDataResults=function(results){return results.map(function(concept){return{concept:{uuid:concept.uuid,name:concept.name.name,editableName:concept.name.name},value:concept.name.name}})},$scope.onSelect=function(file,visit,fileName,fileType){$scope.toggleGallery=!1,fileType=visitDocumentService.getFileType(fileType),"not_supported"!==fileType?spinner.forPromise(visitDocumentService.saveFile(file,$rootScope.patient.uuid,$rootScope.appConfig.encounterType,fileName,fileType).then(function(response){var fileUrl=Bahmni.Common.Constants.documentsPath+"/"+response.data.url;visit.addFile(fileUrl);$scope.toggleGallery=!0},function(){messagingService.showMessage("error"),$scope.toggleGallery=!0})):(messagingService.showMessage("error",$translate.instant("FILE_TYPE_NOT_SUPPORTED_MESSAGE")),$scope.toggleGallery=!0,$scope.$$phase||$scope.$apply())},$scope.toInitFileConcept=function(file){file.concept&&file.concept.editableName||(file.concept=Object.create($scope.fileTypeConcepts[0].concept),file.changed=!0)},$scope.onConceptSelected=function(file){var selectedItem=_.find($scope.fileTypeConcepts,function(fileType){return _.get(fileType,"concept.name")==_.get(file,"concept.editableName")});selectedItem&&selectedItem.concept&&(file.concept=Object.create(selectedItem.concept)),file.changed=!0},$scope.enableSaveButtonOnCommentChange=function(file,visit){_.set(file,"changed",!0),_.set(visit,"changed",!0)},$scope.resetCurrentVisit=function(visit){return areVisitsSame($scope.currentVisit,visit)&&areVisitsSame($scope.currentVisit,$scope.newVisit)?($scope.currentVisit=null,$scope.currentVisit):void($scope.currentVisit=$scope.isCurrentVisit(visit)?$scope.newVisit:visit)},$scope.isCurrentVisit=function(visit){return $scope.currentVisit&&$scope.currentVisit.uuid===visit.uuid};var areVisitsSame=function(currentVisit,newVisit){return currentVisit==newVisit&&newVisit==$scope.newVisit},getEncounterStartDateTime=function(visit){return visit.endDate()?visit.startDate():null},createVisitDocument=function(visit){var visitDocument={};return visitDocument.patientUuid=$scope.patient.uuid,visitDocument.visitTypeUuid=visit.visitType.uuid,visitDocument.visitStartDate=visit.startDate(),visitDocument.visitEndDate=visit.endDate(),visitDocument.encounterTypeUuid=encounterTypeUuid,visitDocument.encounterDateTime=getEncounterStartDateTime(visit),visitDocument.providerUuid=$rootScope.currentProvider.uuid,visitDocument.visitUuid=visit.uuid,visitDocument.locationUuid=locationUuid,visitDocument.documents=[],visit.files.forEach(function(file){var fileUrl=file.encodedValue.replace(Bahmni.Common.Constants.documentsPath+"/",""),comment=_.isEmpty(file.comment)?void 0:file.comment;visit.isSaved(file)?file.changed!==!0&&file.voided!==!0||visitDocument.documents.push({testUuid:file.concept.uuid,image:fileUrl,voided:file.voided,obsUuid:file.obsUuid,comment:comment}):visitDocument.documents.push({testUuid:file.concept.uuid,image:fileUrl,obsDateTime:getEncounterStartDateTime(visit),comment:comment})}),visitDocument},flashSuccessMessage=function(){$scope.success=!0,$timeout(function(){$scope.success=!1},2e3)};$scope.setDefaultEndDate=function(newVisit){newVisit.stopDatetime||($scope.newVisit.stopDatetime=newVisit.endDate()?DateUtil.parse(newVisit.endDate()):new Date)};var isObsByCurrentProvider=function(obs){return obs.provider&&$rootScope.currentUser.person.uuid===obs.provider.uuid};$scope.canDeleteFile=function(obs){return isObsByCurrentProvider(obs)||obs.new};var updateVisit=function(visit,encounters){var visitEncounters=encounters.filter(function(encounter){return visit.uuid===encounter.visit.uuid});visit.initSavedFiles(visitEncounters),visit.changed=!1,$scope.currentVisit=visit,sortVisits(),flashSuccessMessage()},isExistingVisit=function(visit){return!!visit.uuid};$scope.save=function(visit){$scope.toggleGallery=!1;var visitDocument;return(isExistingVisit(visit)||$scope.isNewVisitDateValid())&&(visitDocument=createVisitDocument(visit)),spinner.forPromise(visitDocumentService.save(visitDocument).then(function(response){return encounterService.getEncountersForEncounterType($scope.patient.uuid,encounterTypeUuid).then(function(encounterResponse){var savedVisit=$scope.visits[$scope.visits.indexOf(visit)];savedVisit?(updateVisit(savedVisit,encounterResponse.data.results),$scope.toggleGallery=!0):visitService.getVisit(response.data.visitUuid,customVisitParams).then(function(visitResponse){var newVisit=createVisit(visitResponse.data);visit=$scope.visits.push(newVisit),initNewVisit(),updateVisit(newVisit,encounterResponse.data.results),$scope.toggleGallery=!0}),getActiveEncounter()})}))},$scope.isPdf=function(file){return file.encodedValue.indexOf(".pdf")>0},$anchorScroll()}]);