"use strict";var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},function(){var hostUrl=localStorage.getItem("host")?"https://"+localStorage.getItem("host"):"",rootDir=localStorage.getItem("rootDir")||"",RESTWS=hostUrl+"/openmrs/ws/rest",RESTWS_V1=hostUrl+"/openmrs/ws/rest/v1",BAHMNI_CORE=RESTWS_V1+"/bahmnicore",EMRAPI=RESTWS+"/emrapi",BACTERIOLOGY=RESTWS_V1,BASE_URL=hostUrl+"/bahmni_config/openmrs/apps/",CUSTOM_URL=hostUrl+"/implementation_config/openmrs/apps/",serverErrorMessages=[{serverMessage:"Cannot have more than one active order for the same orderable and care setting at same time",clientMessage:"One or more drugs you are trying to order are already active. Please change the start date of the conflicting drug or remove them from the new prescription."},{serverMessage:"[Order.cannot.have.more.than.one]",clientMessage:"One or more drugs you are trying to order are already active. Please change the start date of the conflicting drug or remove them from the new prescription."}],representation="custom:(uuid,name,names,conceptClass,setMembers:(uuid,name,names,conceptClass,setMembers:(uuid,name,names,conceptClass,setMembers:(uuid,name,names,conceptClass))))",unAuthenticatedReferenceDataMap={"/openmrs/ws/rest/v1/location?tags=Login+Location&s=byTags&v=default":"LoginLocations","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=locale.allowed.list":"LocaleList"},authenticatedReferenceDataMap={"/openmrs/ws/rest/v1/idgen/identifiertype":"IdentifierTypes","/openmrs/module/addresshierarchy/ajax/getOrderedAddressHierarchyLevels.form":"AddressHierarchyLevels","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=mrs.genders":"Genders","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=bahmni.encountersession.duration":"encounterSessionDuration","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=bahmni.relationshipTypeMap":"RelationshipTypeMap","/openmrs/ws/rest/v1/bahmnicore/config/bahmniencounter?callerContext=REGISTRATION_CONCEPTS":"RegistrationConcepts","/openmrs/ws/rest/v1/relationshiptype?v=custom:(aIsToB,bIsToA,uuid)":"RelationshipType","/openmrs/ws/rest/v1/personattributetype?v=custom:(uuid,name,sortWeight,description,format,concept)":"PersonAttributeType","/openmrs/ws/rest/v1/entitymapping?mappingType=loginlocation_visittype&s=byEntityAndMappingType":"LoginLocationToVisitTypeMapping","/openmrs/ws/rest/v1/bahmnicore/config/patient":"PatientConfig","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Consultation+Note&v=custom:(uuid,name,answers)":"ConsultationNote","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Lab+Order+Notes&v=custom:(uuid,name)":"LabOrderNotes","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Impression&v=custom:(uuid,name)":"RadiologyImpressionConfig","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=All_Tests_and_Panels&v=custom:(uuid,name:(uuid,name),setMembers:(uuid,name:(uuid,name)))":"AllTestsAndPanelsConcept","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Dosage+Frequency&v=custom:(uuid,name,answers)":"DosageFrequencyConfig","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Dosage+Instructions&v=custom:(uuid,name,answers)":"DosageInstructionConfig","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=bahmni.encounterType.default":"DefaultEncounterType","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Stopped+Order+Reason&v=custom:(uuid,name,answers)":"StoppedOrderReasonConfig","/openmrs/ws/rest/v1/ordertype":"OrderType","/openmrs/ws/rest/v1/bahmnicore/config/drugOrders":"DrugOrderConfig","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=drugOrder.drugOther":"NonCodedDrugConcept"};authenticatedReferenceDataMap["/openmrs/ws/rest/v1/entitymapping?mappingType=location_encountertype&s=byEntityAndMappingType&entityUuid="+(localStorage.getItem("LoginInformation")?JSON.parse(localStorage.getItem("LoginInformation")).currentLocation.uuid:"")]="LoginLocationToEncounterTypeMapping",Bahmni.Common.Constants={hostURL:hostUrl,dateFormat:"dd/mm/yyyy",dateDisplayFormat:"DD-MMM-YYYY",timeDisplayFormat:"hh:mm",emrapiDiagnosisUrl:EMRAPI+"/diagnosis",bahmniDiagnosisUrl:BAHMNI_CORE+"/diagnosis/search",bahmniDeleteDiagnosisUrl:BAHMNI_CORE+"/diagnosis/delete",diseaseTemplateUrl:BAHMNI_CORE+"/diseaseTemplates",AllDiseaseTemplateUrl:BAHMNI_CORE+"/diseaseTemplate",emrapiConceptUrl:EMRAPI+"/concept",encounterConfigurationUrl:BAHMNI_CORE+"/config/bahmniencounter",patientConfigurationUrl:BAHMNI_CORE+"/config/patient",drugOrderConfigurationUrl:BAHMNI_CORE+"/config/drugOrders",emrEncounterUrl:EMRAPI+"/encounter",encounterUrl:RESTWS_V1+"/encounter",locationUrl:RESTWS_V1+"/location",bahmniVisitLocationUrl:BAHMNI_CORE+"/visitLocation",bahmniOrderUrl:BAHMNI_CORE+"/orders",bahmniDrugOrderUrl:BAHMNI_CORE+"/drugOrders",bahmniDispositionByVisitUrl:BAHMNI_CORE+"/disposition/visit",bahmniDispositionByPatientUrl:BAHMNI_CORE+"/disposition/patient",bahmniSearchUrl:BAHMNI_CORE+"/search",bahmniLabOrderResultsUrl:BAHMNI_CORE+"/labOrderResults",bahmniEncounterUrl:BAHMNI_CORE+"/bahmniencounter",conceptUrl:RESTWS_V1+"/concept",bahmniConceptAnswerUrl:RESTWS_V1+"/bahmniconceptanswer",conceptSearchByFullNameUrl:RESTWS_V1+"/concept?s=byFullySpecifiedName",visitUrl:RESTWS_V1+"/visit",endVisitUrl:BAHMNI_CORE+"/visit/endVisit",endVisitAndCreateEncounterUrl:BAHMNI_CORE+"/visit/endVisitAndCreateEncounter",visitTypeUrl:RESTWS_V1+"/visittype",patientImageUrlByPatientUuid:RESTWS_V1+"/patientImage?patientUuid=",labResultUploadedFileNameUrl:"/uploaded_results/",visitSummaryUrl:BAHMNI_CORE+"/visit/summary",encounterModifierUrl:BAHMNI_CORE+"/bahmniencountermodifier",openmrsUrl:hostUrl+"/openmrs",loggingUrl:hostUrl+"/log/",idgenConfigurationURL:RESTWS_V1+"/idgen/identifiertype",bahmniRESTBaseURL:BAHMNI_CORE+"",observationsUrl:BAHMNI_CORE+"/observations",obsRelationshipUrl:BAHMNI_CORE+"/obsrelationships",encounterImportUrl:BAHMNI_CORE+"/admin/upload/encounter",programImportUrl:BAHMNI_CORE+"/admin/upload/program",conceptImportUrl:BAHMNI_CORE+"/admin/upload/concept",conceptSetImportUrl:BAHMNI_CORE+"/admin/upload/conceptset",drugImportUrl:BAHMNI_CORE+"/admin/upload/drug",labResultsImportUrl:BAHMNI_CORE+"/admin/upload/labResults",referenceTermsImportUrl:BAHMNI_CORE+"/admin/upload/referenceterms",relationshipImportUrl:BAHMNI_CORE+"/admin/upload/relationship",conceptSetExportUrl:BAHMNI_CORE+"/admin/export/conceptset?conceptName=:conceptName",patientImportUrl:BAHMNI_CORE+"/admin/upload/patient",adminImportStatusUrl:BAHMNI_CORE+"/admin/upload/status",programUrl:RESTWS_V1+"/program",programEnrollPatientUrl:RESTWS_V1+"/bahmniprogramenrollment",programStateDeletionUrl:RESTWS_V1+"/programenrollment",programEnrollmentDefaultInformation:"default",programEnrollmentFullInformation:"full",programAttributeTypes:RESTWS_V1+"/programattributetype",relationshipTypesUrl:RESTWS_V1+"/relationshiptype",personAttributeTypeUrl:RESTWS_V1+"/personattributetype",diseaseSummaryPivotUrl:BAHMNI_CORE+"/diseaseSummaryData",allTestsAndPanelsConceptName:"All_Tests_and_Panels",dosageFrequencyConceptName:"Dosage Frequency",dosageInstructionConceptName:"Dosage Instructions",stoppedOrderReasonConceptName:"Stopped Order Reason",consultationNoteConceptName:"Consultation Note",diagnosisConceptSet:"Diagnosis Concept Set",radiologyOrderType:"Radiology Order",radiologyResultConceptName:"Radiology Result",investigationEncounterType:"INVESTIGATION",validationNotesEncounterType:"VALIDATION NOTES",labOrderNotesConcept:"Lab Order Notes",impressionConcept:"Impression",qualifiedByRelationshipType:"qualified-by",dispositionConcept:"Disposition",dispositionGroupConcept:"Disposition Set",dispositionNoteConcept:"Disposition Note",ruledOutDiagnosisConceptName:"Ruled Out Diagnosis",emrapiConceptMappingSource:"org.openmrs.module.emrapi",abbreviationConceptMappingSource:"Abbreviation",includeAllObservations:!1,openmrsObsUrl:RESTWS_V1+"/obs",openmrsObsRepresentation:"custom:(uuid,obsDatetime,value:(uuid,name:(uuid,name)))",admissionCode:"ADMIT",dischargeCode:"DISCHARGE",transferCode:"TRANSFER",undoDischargeCode:"UNDO_DISCHARGE",vitalsConceptName:"Vitals",heightConceptName:"HEIGHT",weightConceptName:"WEIGHT",bmiConceptName:"BMI",bmiStatusConceptName:"BMI STATUS",abnormalObservationConceptName:"IS_ABNORMAL",documentsPath:"/document_images",documentsConceptName:"Document",miscConceptClassName:"Misc",abnormalConceptClassName:"Abnormal",unknownConceptClassName:"Unknown",durationConceptClassName:"Duration",conceptDetailsClassName:"Concept Details",admissionEncounterTypeName:"ADMISSION",dischargeEncounterTypeName:"DISCHARGE",imageClassName:"Image",videoClassName:"Video",locationCookieName:"bahmni.user.location",retrospectiveEntryEncounterDateCookieName:"bahmni.clinical.retrospectiveEncounterDate",JSESSIONID:"JSESSIONID",rootScopeRetrospectiveEntry:"retrospectiveEntry.encounterDate",patientFileConceptName:"Patient file",serverErrorMessages:serverErrorMessages,currentUser:"bahmni.user",retrospectivePrivilege:"app:clinical:retrospective",locationPickerPrivilege:"app:clinical:locationpicker",onBehalfOfPrivilege:"app:clinical:onbehalf",nutritionalConceptName:"Nutritional Values",messageForNoObservation:"NO_OBSERVATIONS_CAPTURED",messageForNoDisposition:"NO_DISPOSTIONS_AVAILABLE_MESSAGE_KEY",messageForNoFulfillment:"NO_FULFILMENT_MESSAGE",reportsUrl:"/bahmnireports",uploadReportTemplateUrl:"/bahmnireports/upload",ruledOutdiagnosisStatus:"Ruled Out Diagnosis",registartionConsultationPrivilege:"app:common:registration_consultation_link",manageIdentifierSequencePrivilege:"Manage Identifier Sequence",closeVisitPrivilege:"app:common:closeVisit",deleteDiagnosisPrivilege:"app:clinical:deleteDiagnosis",viewPatientsPrivilege:"View Patients",editPatientsPrivilege:"Edit Patients",addVisitsPrivilege:"Add Visits",deleteVisitsPrivilege:"Delete Visits",grantProviderAccess:"app:clinical:grantProviderAccess",grantProviderAccessDataCookieName:"app.clinical.grantProviderAccessData",globalPropertyUrl:BAHMNI_CORE+"/sql/globalproperty",passwordPolicyUrl:BAHMNI_CORE+"/globalProperty/passwordPolicyProperties",fulfillmentConfiguration:"fulfillment",fulfillmentFormSuffix:" Fulfillment Form",noNavigationLinksMessage:"NO_NAVIGATION_LINKS_AVAILABLE_MESSAGE",conceptSetRepresentationForOrderFulfillmentConfig:representation,entityMappingUrl:RESTWS_V1+"/entitymapping",encounterTypeUrl:RESTWS_V1+"/encountertype",defaultExtensionName:"default",orderSetMemberAttributeTypeUrl:RESTWS_V1+"/ordersetmemberattributetype",orderSetUrl:RESTWS_V1+"/bahmniorderset",primaryOrderSetMemberAttributeTypeName:"Primary",bahmniBacteriologyResultsUrl:BACTERIOLOGY+"/specimen",bedFromVisit:RESTWS_V1+"/beds",ordersUrl:RESTWS_V1+"/order",formDataUrl:RESTWS_V1+"/obs",providerUrl:RESTWS_V1+"/provider",drugUrl:RESTWS_V1+"/drug",orderTypeUrl:RESTWS_V1+"/ordertype",userUrl:RESTWS_V1+"/user",passwordUrl:RESTWS_V1+"/password",formUrl:RESTWS_V1+"/form",allFormsUrl:RESTWS_V1+"/bahmniie/form/allForms",latestPublishedForms:RESTWS_V1+"/bahmniie/form/latestPublishedForms",formTranslationsUrl:RESTWS_V1+"/bahmniie/form/translations",sqlUrl:BAHMNI_CORE+"/sql",patientAttributeDateFieldFormat:"org.openmrs.util.AttributableDate",platform:"user.platform",RESTWS_V1:RESTWS_V1,baseUrl:BASE_URL,customUrl:CUSTOM_URL,faviconUrl:hostUrl+"/bahmni/favicon.ico",platformType:{other:"other"},numericDataType:"Numeric",encryptionType:{SHA3:"SHA3"},LoginInformation:"LoginInformation",ServerDateTimeFormat:"YYYY-MM-DDTHH:mm:ssZZ",calculateDose:BAHMNI_CORE+"/calculateDose",unAuthenticatedReferenceDataMap:unAuthenticatedReferenceDataMap,authenticatedReferenceDataMap:authenticatedReferenceDataMap,rootDir:rootDir,dischargeUrl:BAHMNI_CORE+"/discharge",uuidRegex:"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",eventlogFilterUrl:hostUrl+"/openmrs/ws/rest/v1/eventlog/filter",bahmniConnectMetaDataDb:"metaData",serverDateTimeUrl:"/cgi-bin/systemdate",loginText:"/bahmni_config/openmrs/apps/home/whiteLabel.json",auditLogUrl:RESTWS_V1+"/auditlog",appointmentServiceUrl:RESTWS_V1+"/appointmentService",conditionUrl:EMRAPI+"/condition",conditionHistoryUrl:EMRAPI+"/conditionhistory",followUpConditionConcept:"Follow-up Condition",localeLangs:"/bahmni_config/openmrs/apps/home/locale_languages.json",privilegeRequiredErrorMessage:"PRIVILEGE_REQUIRED",defaultPossibleRelativeSearchLimit:10}}(),angular.module("bahmni.common.routeErrorHandler",["ui.router"]).run(["$rootScope",function($rootScope){$rootScope.$on("$stateChangeError",function(event){event.preventDefault()})}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Util=Bahmni.Common.Util||{},angular.module("bahmni.common.util",[]).provider("$bahmniCookieStore",[function(){var self=this;self.defaultOptions={};var fixedEncodeURIComponent=function(str){return encodeURIComponent(str).replace(/[!'()*]/g,function(c){return"%"+c.charCodeAt(0).toString(16)})};self.setDefaultOptions=function(options){self.defaultOptions=options},self.$get=function(){return{get:function(name){var jsonCookie=$.cookie(name);return jsonCookie?angular.fromJson(decodeURIComponent(jsonCookie)):null},put:function(name,value,options){options=$.extend({},self.defaultOptions,options),$.cookie.raw=!0,$.cookie(name,fixedEncodeURIComponent(angular.toJson(value)),options)},remove:function(name,options){options=$.extend({},self.defaultOptions,options),$.removeCookie(name,options)}}}}]),Bahmni.Common.Util.DateUtil={diffInDays:function(dateFrom,dateTo){return Math.floor((this.parse(dateTo)-this.parse(dateFrom))/864e5)},diffInMinutes:function(dateFrom,dateTo){return moment(dateTo).diff(moment(dateFrom),"minutes")},diffInSeconds:function(dateFrom,dateTo){return moment(dateFrom).diff(moment(dateTo),"seconds")},isInvalid:function(date){return"Invalid Date"==date},diffInDaysRegardlessOfTime:function(dateFrom,dateTo){var from=new Date(dateFrom),to=new Date(dateTo);return from.setHours(0,0,0,0),to.setHours(0,0,0,0),Math.floor((to-from)/864e5)},addSeconds:function(date,seconds){return moment(date).add(seconds,"seconds").toDate()},addMinutes:function(date,minutes){return this.addSeconds(date,60*minutes)},addDays:function(date,days){return moment(date).add(days,"day").toDate()},addMonths:function(date,months){return moment(date).add(months,"month").toDate()},addYears:function(date,years){return moment(date).add(years,"year").toDate()},subtractSeconds:function(date,seconds){return moment(date).subtract(seconds,"seconds").toDate()},subtractDays:function(date,days){return this.addDays(date,-1*days)},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},getDateWitTime:function(datetime){return datetime?moment(datetime).format("YYYY-MM-DD HH:mm:ss"):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")}},Bahmni.Common.Util.ArrayUtil={chunk:function(array,chunkSize){for(var chunks=[],i=0;i0)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)}]),Modernizr.addTest("ios",function(){return!!navigator.userAgent.match(/(iPad|iPhone|iPod)/i)}),Modernizr.addTest("windowOS",function(){return navigator.appVersion.indexOf("Win")!=-1}),$(function(){Modernizr.ios&&$(document).on("click","label[for]",function(){var $inputElement=$("input#"+$(this).attr("for")),elementType=$inputElement.attr("type");"radio"===elementType?$inputElement.prop("checked",!0):"checkbox"===elementType?$inputElement.prop("checked",!$inputElement.prop("checked")):$inputElement.focus()})}),Bahmni.Common.Util.DateTimeFormatter={getDateWithoutTime:function(datetime){return datetime?moment(datetime).format("YYYY-MM-DD"):null}};var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Models=Bahmni.Common.Models||{},angular.module("bahmni.common.models",[]);var Bahmni=Bahmni||{};Bahmni.Auth=Bahmni.Auth||{},angular.module("authentication",["ui.router"]),Bahmni.Auth.User=function(user){angular.extend(this,user),this.userProperties=user.userProperties||{},this.favouriteObsTemplates=this.userProperties.favouriteObsTemplates?this.userProperties.favouriteObsTemplates.split("###"):[],this.favouriteWards=this.userProperties.favouriteWards?this.userProperties.favouriteWards.split("###"):[],this.recentlyViewedPatients=this.userProperties.recentlyViewedPatients?JSON.parse(this.userProperties.recentlyViewedPatients):[],this.toContract=function(){var user=angular.copy(this);return user.userProperties.favouriteObsTemplates=this.favouriteObsTemplates.join("###"),user.userProperties.favouriteWards=this.favouriteWards.join("###"),user.userProperties.recentlyViewedPatients=JSON.stringify(this.recentlyViewedPatients),delete user.favouriteObsTemplates,delete user.favouriteWards,delete user.recentlyViewedPatients,user},this.addDefaultLocale=function(locale){this.userProperties.defaultLocale=locale},this.addToRecentlyViewed=function(patient,maxPatients){_.some(this.recentlyViewedPatients,{uuid:patient.uuid})||(this.recentlyViewedPatients.unshift({uuid:patient.uuid,name:patient.name,identifier:patient.identifier}),_.size(this.recentlyViewedPatients)>=maxPatients&&(this.recentlyViewedPatients=_.take(this.recentlyViewedPatients,maxPatients)))},this.isFavouriteObsTemplate=function(conceptName){return _.includes(this.favouriteObsTemplates,conceptName)},this.toggleFavoriteObsTemplate=function(conceptName){this.isFavouriteObsTemplate(conceptName)?this.favouriteObsTemplates=_.without(this.favouriteObsTemplates,conceptName):this.favouriteObsTemplates.push(conceptName)},this.isFavouriteWard=function(wardName){return _.includes(this.favouriteWards,wardName)},this.toggleFavoriteWard=function(wardName){this.isFavouriteWard(wardName)?this.favouriteWards=_.without(this.favouriteWards,wardName):this.favouriteWards.push(wardName)}},angular.module("authentication").service("userService",["$rootScope","$http","$q",function($rootScope,$http,$q){var getUserFromServer=function(userName){return $http.get(Bahmni.Common.Constants.userUrl,{method:"GET",params:{username:userName,v:"custom:(username,uuid,person:(uuid,),privileges:(name,retired),userProperties)"},cache:!1})};this.getUser=function(userName){var deferrable=$q.defer();return getUserFromServer(userName).success(function(data){deferrable.resolve(data)}).error(function(){deferrable.reject("Unable to get user data")}),deferrable.promise},this.savePreferences=function(){var deferrable=$q.defer(),user=$rootScope.currentUser.toContract();return $http.post(Bahmni.Common.Constants.userUrl+"/"+user.uuid,{uuid:user.uuid,userProperties:user.userProperties},{withCredentials:!0}).then(function(response){$rootScope.currentUser.userProperties=response.data.userProperties,deferrable.resolve()}),deferrable.promise};var getProviderFromServer=function(uuid){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",params:{user:uuid},cache:!1})};this.getProviderForUser=function(uuid){var deferrable=$q.defer();return getProviderFromServer(uuid).success(function(data){if(data.results.length>0){var providerName=data.results[0].display.split("-")[1];data.results[0].name=providerName?providerName.trim():providerName,deferrable.resolve(data)}else deferrable.reject("UNABLE_TO_GET_PROVIDER_DATA")}).error(function(){deferrable.reject("UNABLE_TO_GET_PROVIDER_DATA")}),deferrable.promise},this.getPasswordPolicies=function(){return $http.get(Bahmni.Common.Constants.passwordPolicyUrl,{method:"GET",withCredentials:!0})}}]),angular.module("authentication").config(["$httpProvider",function($httpProvider){var interceptor=["$rootScope","$q",function($rootScope,$q){function success(response){return response}function error(response){return 401===response.status&&$rootScope.$broadcast("event:auth-loginRequired"),$q.reject(response)}return{response:success,responseError:error}}];$httpProvider.interceptors.push(interceptor)}]).run(["$rootScope","$window","$timeout",function($rootScope,$window,$timeout){$rootScope.$on("event:auth-loginRequired",function(){$timeout(function(){$window.location="../home/index.html#/login"})})}]).service("sessionService",["$rootScope","$http","$q","$bahmniCookieStore","userService",function($rootScope,$http,$q,$bahmniCookieStore,userService){var sessionResourcePath=Bahmni.Common.Constants.RESTWS_V1+"/session?v=custom:(uuid)",getAuthFromServer=function(username,password,otp){var btoa=otp?username+":"+password+":"+otp:username+":"+password;return $http.get(sessionResourcePath,{headers:{Authorization:"Basic "+window.btoa(btoa)},cache:!1})};this.resendOTP=function(username,password){var btoa=username+":"+password;return $http.get(sessionResourcePath+"&resendOTP=true",{headers:{Authorization:"Basic "+window.btoa(btoa)},cache:!1})};var createSession=function(username,password,otp){var deferrable=$q.defer();return destroySessionFromServer().success(function(){getAuthFromServer(username,password,otp).then(function(response){204==response.status&&deferrable.resolve({firstFactAuthorization:!0}),deferrable.resolve(response.data)},function(response){401==response.status?deferrable.reject("LOGIN_LABEL_WRONG_OTP_MESSAGE_KEY"):410==response.status?deferrable.reject("LOGIN_LABEL_OTP_EXPIRED"):429==response.status&&deferrable.reject("LOGIN_LABEL_MAX_FAILED_ATTEMPTS"),deferrable.reject("LOGIN_LABEL_LOGIN_ERROR_MESSAGE_KEY")})}).error(function(){deferrable.reject("LOGIN_LABEL_LOGIN_ERROR_MESSAGE_KEY")}),deferrable.promise},hasAnyActiveProvider=function(providers){return _.filter(providers,function(provider){return void 0==provider.retired||"false"==provider.retired}).length>0},self=this,destroySessionFromServer=function(){return $http["delete"](sessionResourcePath)},sessionCleanup=function(){delete $.cookie(Bahmni.Common.Constants.currentUser,null,{path:"/"}),delete $.cookie(Bahmni.Common.Constants.currentUser,null,{path:"/"}),delete $.cookie(Bahmni.Common.Constants.retrospectiveEntryEncounterDateCookieName,null,{path:"/"}),delete $.cookie(Bahmni.Common.Constants.grantProviderAccessDataCookieName,null,{path:"/"}),$rootScope.currentUser=void 0};this.destroy=function(){var deferrable=$q.defer();return destroySessionFromServer().then(function(){sessionCleanup(),deferrable.resolve()}),deferrable.promise},this.loginUser=function(username,password,location,otp){var deferrable=$q.defer();return createSession(username,password,otp).then(function(data){data.authenticated?($bahmniCookieStore.put(Bahmni.Common.Constants.currentUser,username,{path:"/",expires:7}),void 0!=location&&($bahmniCookieStore.remove(Bahmni.Common.Constants.locationCookieName),$bahmniCookieStore.put(Bahmni.Common.Constants.locationCookieName,{name:location.display,uuid:location.uuid},{path:"/",expires:7})),deferrable.resolve(data)):data.firstFactAuthorization?deferrable.resolve(data):deferrable.reject("LOGIN_LABEL_LOGIN_ERROR_MESSAGE_KEY")},function(errorInfo){deferrable.reject(errorInfo)}),deferrable.promise},this.get=function(){return $http.get(sessionResourcePath,{cache:!1})},this.loadCredentials=function(){var deferrable=$q.defer(),currentUser=$bahmniCookieStore.get(Bahmni.Common.Constants.currentUser);return currentUser?(userService.getUser(currentUser).then(function(data){userService.getProviderForUser(data.results[0].uuid).then(function(providers){!_.isEmpty(providers.results)&&hasAnyActiveProvider(providers.results)?($rootScope.currentUser=new Bahmni.Auth.User(data.results[0]),$rootScope.currentUser.currentLocation=$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName).name,$rootScope.$broadcast("event:user-credentialsLoaded",data.results[0]),deferrable.resolve(data.results[0])):(self.destroy(),deferrable.reject("YOU_HAVE_NOT_BEEN_SETUP_PROVIDER"))},function(){self.destroy(),deferrable.reject("COULD_NOT_GET_PROVIDER")})},function(){self.destroy(),deferrable.reject("Could not get roles for the current user.")}),deferrable.promise):(this.destroy()["finally"](function(){$rootScope.$broadcast("event:auth-loginRequired"),deferrable.reject("No User in session. Please login again.")}),deferrable.promise)},this.getLoginLocationUuid=function(){return $bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName)?$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName).uuid:null},this.changePassword=function(currentUserUuid,oldPassword,newPassword){return $http({method:"POST",url:Bahmni.Common.Constants.passwordUrl,data:{oldPassword:oldPassword,newPassword:newPassword},headers:{"Content-Type":"application/json"}})},this.loadProviders=function(userInfo){
return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",params:{user:userInfo.uuid},cache:!1}).success(function(data){var providerUuid=data.results.length>0?data.results[0].uuid:void 0;$rootScope.currentProvider={uuid:providerUuid}})}}]).factory("authenticator",["$rootScope","$q","$window","sessionService",function($rootScope,$q,$window,sessionService){var authenticateUser=function(){var defer=$q.defer(),sessionDetails=sessionService.get();return sessionDetails.then(function(response){response.data.authenticated?defer.resolve():(defer.reject("User not authenticated"),$rootScope.$broadcast("event:auth-loginRequired"))}),defer.promise};return{authenticateUser:authenticateUser}}]).directive("logOut",["sessionService","$window","configurationService","auditLogService",function(sessionService,$window,configurationService,auditLogService){return{link:function(scope,element){element.bind("click",function(){scope.$apply(function(){auditLogService.log(void 0,"USER_LOGOUT_SUCCESS",void 0,"MODULE_LABEL_LOGOUT_KEY").then(function(){sessionService.destroy().then(function(){$window.location="../home/index.html#/login"})})})})}}}]).directive("btnUserInfo",[function(){return{restrict:"CA",link:function(scope,elem){elem.bind("click",function(event){$(this).next().toggleClass("active"),event.stopPropagation()}),$(document).find("body").bind("click",function(){$(elem).next().removeClass("active")})}}}]),angular.module("bahmni.common.appFramework",["authentication"]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.AppFramework=Bahmni.Common.AppFramework||{},angular.module("bahmni.common.appFramework").config(["$compileProvider",function($compileProvider){$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|file):/)}]).service("appService",["$http","$q","sessionService","$rootScope","mergeService","loadConfigService","messagingService","$translate",function($http,$q,sessionService,$rootScope,mergeService,loadConfigService,messagingService,$translate){var currentUser=null,baseUrl=Bahmni.Common.Constants.baseUrl,customUrl=Bahmni.Common.Constants.customUrl,appDescriptor=null,loadConfig=function(url){return loadConfigService.loadConfig(url,appDescriptor.contextPath)},loadTemplate=function(appDescriptor){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.contextPath+"/appTemplate.json").then(function(result){_.keys(result.data).length>0&&appDescriptor.setTemplate(result.data),deferrable.resolve(appDescriptor)},function(error){404!==error.status?deferrable.reject(error):deferrable.resolve(appDescriptor)}),deferrable.promise},setDefinition=function(baseResultData,customResultData){customResultData&&(_.keys(baseResultData).length>0||_.keys(customResultData.length>0))?appDescriptor.setDefinition(baseResultData,customResultData):_.keys(baseResultData).length>0&&appDescriptor.setDefinition(baseResultData)},loadDefinition=function(appDescriptor){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.contextPath+"/app.json").then(function(baseResult){baseResult.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.contextPath+"/app.json").then(function(customResult){setDefinition(baseResult.data,customResult.data),deferrable.resolve(appDescriptor)},function(){setDefinition(baseResult.data),deferrable.resolve(appDescriptor)}):(setDefinition(baseResult.data),deferrable.resolve(appDescriptor))},function(error){404!==error.status?deferrable.reject(error):deferrable.resolve(appDescriptor)}),deferrable.promise},setExtensions=function(baseResultData,customResultData){customResultData?appDescriptor.setExtensions(baseResultData,customResultData):appDescriptor.setExtensions(baseResultData)},loadExtensions=function(appDescriptor,extensionFileName){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.extensionPath+extensionFileName).then(function(baseResult){baseResult.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.extensionPath+extensionFileName).then(function(customResult){setExtensions(baseResult.data,customResult.data),deferrable.resolve(appDescriptor)},function(){setExtensions(baseResult.data),deferrable.resolve(appDescriptor)}):(setExtensions(baseResult.data),deferrable.resolve(appDescriptor))},function(error){404!==error.status?deferrable.reject(error):deferrable.resolve(appDescriptor)}),deferrable.promise},setDefaultPageConfig=function(pageName,baseResultData,customResultData){customResultData&&(_.keys(customResultData).length>0||_.keys(baseResultData).length>0)?appDescriptor.addConfigForPage(pageName,baseResultData,customResultData):_.keys(baseResultData).length>0&&appDescriptor.addConfigForPage(pageName,baseResultData)},hasPrivilegeOf=function(privilegeName){return _.some(currentUser.privileges,{name:privilegeName})},loadPageConfig=function(pageName,appDescriptor){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.contextPath+"/"+pageName+".json").then(function(baseResult){baseResult.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.contextPath+"/"+pageName+".json").then(function(customResult){setDefaultPageConfig(pageName,baseResult.data,customResult.data),deferrable.resolve(appDescriptor)},function(){setDefaultPageConfig(pageName,baseResult.data),deferrable.resolve(appDescriptor)}):(setDefaultPageConfig(pageName,baseResult.data),deferrable.resolve(appDescriptor))},function(error){404!==error.status?(messagingService.showMessage("error","Incorrect Configuration: "+error.message),deferrable.reject(error)):deferrable.resolve(appDescriptor)}),deferrable.promise};this.getAppDescriptor=function(){return appDescriptor},this.configBaseUrl=function(){return baseUrl},this.loadCsvFileFromConfig=function(name){return loadConfig(baseUrl+appDescriptor.contextPath+"/"+name)},this.loadConfig=function(name,shouldMerge){return loadConfig(baseUrl+appDescriptor.contextPath+"/"+name).then(function(baseResponse){return baseResponse.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.contextPath+"/"+name).then(function(customResponse){return shouldMerge||void 0===shouldMerge?mergeService.merge(baseResponse.data,customResponse.data):[baseResponse.data,customResponse.data]},function(){return baseResponse.data}):baseResponse.data})},this.loadMandatoryConfig=function(path){return $http.get(path)},this.getAppName=function(){return this.appName},this.checkPrivilege=function(privilegeName){return hasPrivilegeOf(privilegeName)?$q.when(!0):(messagingService.showMessage("error",$translate.instant(Bahmni.Common.Constants.privilegeRequiredErrorMessage)+" [Privileges required: "+privilegeName+"]"),$q.reject())},this.initApp=function(appName,options,extensionFileSuffix,configPages){this.appName=appName;var appLoader=$q.defer(),extensionFileName=extensionFileSuffix&&"default"!==extensionFileSuffix.toLowerCase()?"/extension-"+extensionFileSuffix+".json":"/extension.json",promises=[],opts=options||{app:!0,extension:!0},inheritAppContext=!opts.inherit||opts.inherit;appDescriptor=new Bahmni.Common.AppFramework.AppDescriptor(appName,inheritAppContext,function(){return currentUser},mergeService);var loadCredentialsPromise=sessionService.loadCredentials(),loadProviderPromise=loadCredentialsPromise.then(sessionService.loadProviders);return promises.push(loadCredentialsPromise),promises.push(loadProviderPromise),opts.extension&&promises.push(loadExtensions(appDescriptor,extensionFileName)),opts.template&&promises.push(loadTemplate(appDescriptor)),opts.app&&promises.push(loadDefinition(appDescriptor)),_.isEmpty(configPages)||configPages.forEach(function(configPage){promises.push(loadPageConfig(configPage,appDescriptor))}),$q.all(promises).then(function(results){currentUser=results[0],appLoader.resolve(appDescriptor),$rootScope.$broadcast("event:appExtensions-loaded")},function(errors){appLoader.reject(errors)}),appLoader.promise}}]),angular.module("bahmni.common.appFramework").service("mergeService",[function(){this.merge=function(base,custom){var mergeResult=$.extend(!0,{},base,custom);return deleteNullValuedKeys(mergeResult)};var deleteNullValuedKeys=function(currentObject){return _.forOwn(currentObject,function(value,key){(_.isUndefined(value)||_.isNull(value)||_.isNaN(value)||_.isObject(value)&&_.isNull(deleteNullValuedKeys(value)))&&delete currentObject[key]}),currentObject}}]),angular.module("bahmni.common.appFramework").directive("appExtensionList",["appService",function(appService){var appDescriptor=appService.getAppDescriptor();return{restrict:"EA",template:'',scope:{extnPointId:"@",showLabel:"@",onExtensionClick:"&",contextModel:"&"},compile:function(cElement,cAttrs){var extnList=appDescriptor.getExtensions(cAttrs.extnPointId);return function(scope){scope.appExtensions=extnList;var model=scope.contextModel();scope.extnParams=model||{}}},controller:function($scope,$location){$scope.formatUrl=appDescriptor.formatUrl,$scope.extnLinkClick=function(extn,params){var proceedWithDefault=!0,clickHandler=$scope.onExtensionClick(),target=appDescriptor.formatUrl(extn.url,params);if(clickHandler){var event={src:extn,target:target,params:params,preventDefault:function(){proceedWithDefault=!1}};clickHandler(event)}proceedWithDefault&&$location.url(target)}}}}]),Bahmni.Common.AppFramework.AppDescriptor=function(context,inheritContext,retrieveUserCallback,mergeService){this.id=null,this.instanceOf=null,this.description=null,this.contextModel=null,this.baseExtensionPoints=[],this.customExtensionPoints=[],this.baseExtensions={},this.customExtensions={},this.customConfigs={},this.baseConfigs={},this.extensionPath=context,this.contextPath=inheritContext?context.split("/")[0]:context;var self=this,setExtensionPointsFromExtensions=function(currentExtensions,currentExtensionPoints){_.values(currentExtensions).forEach(function(extn){if(extn){var existing=self[currentExtensionPoints].filter(function(ep){return ep.id===extn.extensionPointId});0===existing.length&&self[currentExtensionPoints].push({id:extn.extensionPointId,description:extn.description})}})};this.setExtensions=function(baseExtensions,customExtensions){customExtensions&&(setExtensionPointsFromExtensions(customExtensions,"customExtensionPoints"),self.customExtensions=customExtensions),self.baseExtensions=baseExtensions,setExtensionPointsFromExtensions(baseExtensions,"baseExtensionPoints")},this.setTemplate=function(template){self.instanceOf=template.id,self.description=self.description||template.description,self.contextModel=self.contextModel||template.contextModel,template.configOptions&&_.values(template.configOptions).forEach(function(opt){var existing=self.configs.filter(function(cfg){return cfg.name===opt.name});existing.length>0?existing[0].description=opt.description:self.configs.push({name:opt.name,description:opt.description,value:opt.defaultValue})})};var setConfig=function(instance,currentConfig){for(var configName in instance.config){var existingConfig=getConfig(self[currentConfig],configName);existingConfig?existingConfig.value=instance.config[configName]:self[currentConfig][configName]={name:configName,value:instance.config[configName]}}},setDefinitionExtensionPoints=function(extensionPoints,currentExtensionPoints){extensionPoints&&extensionPoints.forEach(function(iep){if(iep){var existing=self[currentExtensionPoints].filter(function(ep){return ep.id===iep.id});0===existing.length&&self[currentExtensionPoints].push(iep)}})};this.setDefinition=function(baseInstance,customInstance){self.instanceOf=customInstance&&customInstance.instanceOf?customInstance.instanceOf:baseInstance.instanceOf,self.id=customInstance&&customInstance.id?customInstance.id:baseInstance.id,self.description=customInstance&&customInstance.description?customInstance.description:baseInstance.description,self.contextModel=customInstance&&customInstance.contextModel?customInstance.contextModel:baseInstance.contextModel,setDefinitionExtensionPoints(baseInstance.extensionPoints,"baseExtensionPoints"),setConfig(baseInstance,"baseConfigs"),customInstance&&(setDefinitionExtensionPoints(customInstance.extensionPoints,"customExtensionPoints"),setConfig(customInstance,"customConfigs"))};var getExtensions=function(extPointId,type,extensions){var currentUser=retrieveUserCallback(),currentExtensions=_.values(extensions);if(currentUser&¤tExtensions){var extnType=type||"all",userPrivileges=currentUser.privileges.map(function(priv){return priv.retired?"":priv.name}),appsExtns=currentExtensions.filter(function(extn){return("all"===extnType||extn.type===extnType)&&extn.extensionPointId===extPointId&&(!extn.requiredPrivilege||userPrivileges.indexOf(extn.requiredPrivilege)>=0)});return appsExtns.sort(function(extn1,extn2){return extn1.order-extn2.order}),appsExtns}};this.getExtensions=function(extPointId,type,shouldMerge){if(shouldMerge||void 0===shouldMerge){var mergedExtensions=mergeService.merge(self.baseExtensions,self.customExtensions);return getExtensions(extPointId,type,mergedExtensions)}return[getExtensions(extPointId,type,self.baseExtensions),getExtensions(extPointId,type,self.customExtensions)]},this.getExtensionById=function(id,shouldMerge){if(shouldMerge||void 0===shouldMerge){var mergedExtensions=_.values(mergeService.merge(self.baseExtensions,self.customExtensions));return mergedExtensions.filter(function(extn){return extn.id===id})[0]}return[self.baseExtensions.filter(function(extn){return extn.id===id})[0],self.customExtensions.filter(function(extn){return extn.id===id})[0]]};var getConfig=function(config,configName){var cfgList=_.values(config).filter(function(cfg){return cfg.name===configName});return cfgList.length>0?cfgList[0]:null};this.getConfig=function(configName,shouldMerge){return shouldMerge||void 0===shouldMerge?getConfig(mergeService.merge(self.baseConfigs,self.customConfigs),configName):[getConfig(self.baseConfigs,configName),getConfig(self.customConfigs,configName)]},this.getConfigValue=function(configName,shouldMerge){var config=this.getConfig(configName,shouldMerge);return shouldMerge||void 0===shouldMerge?config?config.value:null:config},this.formatUrl=function(url,options,useQueryParams){var pattern=/{{([^}]*)}}/g,matches=url.match(pattern),replacedString=url,checkQueryParams=useQueryParams||!1,queryParameters=this.parseQueryParams();return matches&&matches.forEach(function(el){var key=el.replace("{{","").replace("}}",""),value=options[key];value||checkQueryParams!==!0||(value=queryParameters[key]||null),replacedString=replacedString.replace(el,value)}),replacedString.trim()},this.parseQueryParams=function(locationSearchString){var urlParams,match,pl=/\+/g,search=/([^&=]+)=?([^&]*)/g,decode=function(s){return decodeURIComponent(s.replace(pl," "))},queryString=locationSearchString||window.location.search.substring(1);for(urlParams={};match=search.exec(queryString);)urlParams[decode(match[1])]=decode(match[2]);return urlParams},this.addConfigForPage=function(pageName,baseConfig,customConfig){self.basePageConfigs=self.basePageConfigs||{},self.basePageConfigs[pageName]=baseConfig,self.customPageConfigs=self.customPageConfigs||{},self.customPageConfigs[pageName]=customConfig},this.getConfigForPage=function(pageName,shouldMerge){return shouldMerge||void 0===shouldMerge?mergeService.merge(self.basePageConfigs[pageName],self.customPageConfigs[pageName]):[_.values(self.basePageConfigs[pageName]),_.values(self.customPageConfigs[pageName])]}},angular.module("bahmni.common.appFramework").service("loadConfigService",["$http",function($http){this.loadConfig=function(url){return $http.get(url,{withCredentials:!0})}}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.DisplayControl=Bahmni.Common.DisplayControl||{},Bahmni.Common.DisplayControl.PatientProfile=Bahmni.Common.DisplayControl.PatientProfile||{},angular.module("bahmni.common.displaycontrol.patientprofile",[]),angular.module("bahmni.common.displaycontrol.patientprofile").filter("titleCase",function(){return function(input){return input=input||"",input.replace(/\w\S*/g,function(txt){return txt.charAt(0).toUpperCase()+txt.substr(1).toLowerCase()})}}),angular.module("bahmni.common.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||{},Bahmni.Common.Domain=Bahmni.Common.Domain||{},Bahmni.Common.Domain.Helper=Bahmni.Common.Domain.Helper||{},angular.module("bahmni.common.domain",[]),angular.module("bahmni.common.domain").factory("locationService",["$http","$bahmniCookieStore",function($http,$bahmniCookieStore){var getAllByTag=function(tags,operator){return $http.get(Bahmni.Common.Constants.locationUrl,{params:{s:"byTags",tags:tags||"",v:"default",operator:operator||"ALL"},cache:!0})},getByUuid=function(locationUuid){return $http.get(Bahmni.Common.Constants.locationUrl+"/"+locationUuid,{cache:!0}).then(function(response){return response.data})},getLoggedInLocation=function(){var cookie=$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName);return getByUuid(cookie.uuid)},getVisitLocation=function(locationUuid){return $http.get(Bahmni.Common.Constants.bahmniVisitLocationUrl+"/"+locationUuid,{headers:{Accept:"application/json"}})};return{getAllByTag:getAllByTag,getLoggedInLocation:getLoggedInLocation,getByUuid:getByUuid,getVisitLocation:getVisitLocation}}]),angular.module("bahmni.common.domain").factory("configurationService",["$http","$q",function($http,$q){var configurationFunctions={};configurationFunctions.encounterConfig=function(){return $http.get(Bahmni.Common.Constants.encounterConfigurationUrl,{params:{callerContext:"REGISTRATION_CONCEPTS"},withCredentials:!0})},configurationFunctions.patientConfig=function(){var patientConfig=$http.get(Bahmni.Common.Constants.patientConfigurationUrl,{withCredentials:!0});return patientConfig},configurationFunctions.patientAttributesConfig=function(){return $http.get(Bahmni.Common.Constants.personAttributeTypeUrl,{params:{v:"custom:(uuid,name,sortWeight,description,format,concept)"},withCredentials:!0})},configurationFunctions.dosageFrequencyConfig=function(){var dosageFrequencyConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.dosageFrequencyConceptName},withCredentials:!0});return dosageFrequencyConfig},configurationFunctions.dosageInstructionConfig=function(){var dosageInstructionConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.dosageInstructionConceptName},withCredentials:!0});return dosageInstructionConfig},configurationFunctions.stoppedOrderReasonConfig=function(){var stoppedOrderReasonConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.stoppedOrderReasonConceptName},withCredentials:!0});return stoppedOrderReasonConfig},configurationFunctions.consultationNoteConfig=function(){var consultationNoteConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.consultationNoteConceptName},withCredentials:!0});return consultationNoteConfig},configurationFunctions.radiologyObservationConfig=function(){var radiologyObservationConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name)",name:Bahmni.Common.Constants.radiologyResultConceptName},withCredentials:!0});return radiologyObservationConfig},configurationFunctions.labOrderNotesConfig=function(){var labOrderNotesConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name)",name:Bahmni.Common.Constants.labOrderNotesConcept},withCredentials:!0});return labOrderNotesConfig},configurationFunctions.defaultEncounterType=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{params:{property:"bahmni.encounterType.default"},withCredentials:!0,transformResponse:[function(data){return data}]})},configurationFunctions.radiologyImpressionConfig=function(){var radiologyImpressionConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name)",name:Bahmni.Common.Constants.impressionConcept},withCredentials:!0});return radiologyImpressionConfig},configurationFunctions.addressLevels=function(){return $http.get(Bahmni.Common.Constants.openmrsUrl+"/module/addresshierarchy/ajax/getOrderedAddressHierarchyLevels.form",{withCredentials:!0})},configurationFunctions.allTestsAndPanelsConcept=function(){var allTestsAndPanelsConcept=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name:(uuid,name),setMembers:(uuid,name:(uuid,name)))",name:Bahmni.Common.Constants.allTestsAndPanelsConceptName},withCredentials:!0});return allTestsAndPanelsConcept},configurationFunctions.identifierTypesConfig=function(){return $http.get(Bahmni.Common.Constants.idgenConfigurationURL,{withCredentials:!0})},configurationFunctions.genderMap=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{method:"GET",params:{property:"mrs.genders"},withCredentials:!0})},configurationFunctions.relationshipTypeMap=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{method:"GET",params:{property:"bahmni.relationshipTypeMap"},withCredentials:!0})},configurationFunctions.relationshipTypeConfig=function(){return $http.get(Bahmni.Common.Constants.relationshipTypesUrl,{withCredentials:!0,params:{v:"custom:(aIsToB,bIsToA,uuid)"}})},configurationFunctions.loginLocationToVisitTypeMapping=function(){var url=Bahmni.Common.Constants.entityMappingUrl;return $http.get(url,{params:{mappingType:"loginlocation_visittype",s:"byEntityAndMappingType"}})},configurationFunctions.enableAuditLog=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{method:"GET",params:{property:"bahmni.enableAuditLog"},withCredentials:!0})};var existingPromises={},configurations={},getConfigurations=function(configurationNames){var configurationsPromiseDefer=$q.defer(),promises=[];return configurationNames.forEach(function(configurationName){existingPromises[configurationName]||(existingPromises[configurationName]=configurationFunctions[configurationName]().then(function(response){configurations[configurationName]=response.data}),promises.push(existingPromises[configurationName]))}),$q.all(promises).then(function(){configurationsPromiseDefer.resolve(configurations)}),configurationsPromiseDefer.promise};return{getConfigurations:getConfigurations}}]),angular.module("bahmni.common.domain").factory("providerService",["$http",function($http){var search=function(fieldValue){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",params:{q:fieldValue,v:"full"},withCredentials:!0})},searchByUuid=function(uuid){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",params:{user:uuid},cache:!1})},list=function(params){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",cache:!1,params:params})};return{search:search,searchByUuid:searchByUuid,list:list}}]),angular.module("bahmni.common.uiHelper",["ngClipboard"]),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").service("backlinkService",["$window",function($window){var self=this,urls=[];self.reset=function(){urls=[]},self.setUrls=function(backLinks){self.reset(),angular.forEach(backLinks,function(backLink){self.addUrl(backLink)})},self.addUrl=function(backLink){urls.push(backLink)},self.addBackUrl=function(label){var backLabel=label||"Back";urls.push({label:backLabel,action:$window.history.back})},self.getUrlByLabel=function(label){return urls.filter(function(url){return url.label===label})},self.getAllUrls=function(){return urls}}]),angular.module("bahmni.common.uiHelper").service("stateChangeSpinner",["$rootScope","spinner",function($rootScope,spinner){var showSpinner=function(event,toState){toState.spinnerToken=spinner.show()},hideSpinner=function(event,toState){spinner.hide(toState.spinnerToken)};this.activate=function(){$rootScope.$on("$stateChangeStart",showSpinner),$rootScope.$on("$stateChangeSuccess",hideSpinner),$rootScope.$on("$stateChangeError",hideSpinner)}}]),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.uiHelper").service("confirmBox",["$rootScope","ngDialog",function($rootScope,ngDialog){var dialog,confirmBox=function(config){var confirmBoxScope=$rootScope.$new();confirmBoxScope.close=function(){ngDialog.close(dialog.id),confirmBoxScope.$destroy()},confirmBoxScope.scope=config.scope,confirmBoxScope.actions=config.actions,dialog=ngDialog.open({template:"../common/ui-helper/views/confirmBox.html",scope:confirmBoxScope,className:config.className||"ngdialog-theme-default"})};return confirmBox}]),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 "+$translate.instant("CLINICAL_YEARS_TRANSLATION_KEY")+" "),age.months&&(ageInString+=age.months+" "+$translate.instant("CLINICAL_MONTHS_TRANSLATION_KEY")+" "),age.days&&(ageInString+=age.days+" "+$translate.instant("CLINICAL_DAYS_TRANSLATION_KEY")+" "),ageInString},mapAddress=function(preferredAddress){return preferredAddress?{address1:preferredAddress.address1,address2:preferredAddress.address2,address3:preferredAddress.address3,cityVillage:preferredAddress.cityVillage,countyDistrict:null===preferredAddress.countyDistrict?"":preferredAddress.countyDistrict,stateProvince:preferredAddress.stateProvince}:{}},parseDate=function(dateStr){return dateStr?Bahmni.Common.Util.DateUtil.parse(dateStr.substr(0,10)):dateStr},mapGenderText=function(genderChar){return null==genderChar?null:""+$rootScope.genderMap[angular.uppercase(genderChar)]+" "},getPatientBloodGroupText=function(openmrsPatient){if(openmrsPatient.person.bloodGroup)return""+openmrsPatient.person.bloodGroup+" ";if(openmrsPatient.person.attributes&&openmrsPatient.person.attributes.length>0){var bloodGroup;if(_.forEach(openmrsPatient.person.attributes,function(attribute){"bloodGroup"==attribute.attributeType.display&&(bloodGroup=attribute.display)}),bloodGroup)return""+bloodGroup+" "}},checkIfDateField=function(x){return x.format===Bahmni.Common.Constants.patientAttributeDateFieldFormat}},angular.module("bahmni.common.patient").service("patientService",["$http","sessionService",function($http,sessionService){this.getPatient=function(uuid){var patient=$http.get(Bahmni.Common.Constants.openmrsUrl+"/ws/rest/v1/patient/"+uuid,{method:"GET",params:{v:"full"},withCredentials:!0});return patient},this.getRelationships=function(patientUuid){return $http.get(Bahmni.Common.Constants.openmrsUrl+"/ws/rest/v1/relationship",{method:"GET",params:{person:patientUuid,v:"full"},withCredentials:!0})},this.findPatients=function(params){return $http.get(Bahmni.Common.Constants.sqlUrl,{method:"GET",params:params,withCredentials:!0})},this.search=function(query,offset,identifier){return offset=offset||0,$http.get(Bahmni.Common.Constants.bahmniSearchUrl+"/patient",{method:"GET",params:{q:query,startIndex:offset,identifier:identifier,loginLocationUuid:sessionService.getLoginLocationUuid()},withCredentials:!0})},this.getPatientContext=function(patientUuid,programUuid,personAttributes,programAttributes,patientIdentifiers){return $http.get("/openmrs/ws/rest/v1/bahmnicore/patientcontext",{params:{patientUuid:patientUuid,programUuid:programUuid,personAttributes:personAttributes,programAttributes:programAttributes,patientIdentifiers:patientIdentifiers},withCredentials:!0})}}]),angular.module("bahmni.common.patient").filter("gender",["$rootScope",function($rootScope){return function(genderChar){return null==genderChar?"Unknown":$rootScope.genderMap[angular.uppercase(genderChar)]}}]);var Bahmni=Bahmni||{};Bahmni.ConceptSet=Bahmni.ConceptSet||{},Bahmni.ConceptSet.FormConditions=Bahmni.ConceptSet.FormConditions||{},angular.module("bahmni.common.conceptSet",["bahmni.common.uiHelper","ui.select2","pasvaz.bindonce","ngSanitize","ngTagsInput"]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.PatientSearch=Bahmni.Common.PatientSearch||{},Bahmni.Common.PatientSearch.Constants={searchExtensionTileViewType:"tile",searchExtensionTabularViewType:"tabular",tabularViewIgnoreHeadingsList:["display","uuid","image","$$hashKey","activeVisitUuid","hasBeenAdmitted","forwardUrl","programUuid","enrollment"],identifierHeading:["ID","Id","id","identifier","DQ_COLUMN_TITLE_ACTION"],nameHeading:["NAME","Name","name"],patientTileHeight:100,patientTileWidth:100,printIgnoreHeadingsList:["DQ_COLUMN_TITLE_ACTION"],tileLoadRatio:.5},Bahmni.Common.PatientSearch.Search=function(searchTypes){function mapPatient(patient){return(patient.name||patient.givenName||patient.familyName)&&(patient.name=patient.name||patient.givenName+(patient.familyName?" "+patient.familyName:"")),patient.display=_.map(self.searchColumns,function(column){return patient[column]}).join(" - "),patient.image=Bahmni.Common.Constants.patientImageUrlByPatientUuid+patient.uuid,patient}var self=this;self.searchTypes=searchTypes||[],self.searchType=this.searchTypes[0],self.searchParameter="",self.noResultsMessage=null,self.searchResults=[],self.activePatients=[],self.navigated=!1,self.links=self.searchType&&self.searchType.links?self.searchType.links:[],self.searchColumns=self.searchType&&self.searchType.searchColumns?self.searchType.searchColumns:["identifier","name"],angular.forEach(searchTypes,function(searchType){searchType.patientCount="..."}),self.switchSearchType=function(searchType){self.noResultsMessage=null,self.isSelectedSearch(searchType)||(self.searchParameter="",self.navigated=!0,self.searchType=searchType,self.activePatients=[],self.searchResults=[],self.links=self.searchType&&self.searchType.links?self.searchType.links:[],self.searchColumns=self.searchType&&self.searchType.searchColumns?self.searchType.searchColumns:["identifier","name"]),self.markPatientEntry()},self.markPatientEntry=function(){self.startPatientSearch=!0,window.setTimeout(function(){self.startPatientSearch=!1})},self.patientsCount=function(){return self.activePatients.length},self.updatePatientList=function(patientList){self.activePatients=patientList.map(mapPatient),self.searchResults=self.activePatients},self.updateSearchResults=function(patientList){self.updatePatientList(patientList),0===self.activePatients.length&&""!=self.searchParameter?self.noResultsMessage="NO_RESULTS_FOUND":self.noResultsMessage=null},self.hasSingleActivePatient=function(){return 1===self.activePatients.length},self.filterPatients=function(matchingCriteria){matchingCriteria=matchingCriteria?matchingCriteria:matchesNameOrId,self.searchResults=self.searchParameter?self.activePatients.filter(matchingCriteria):self.activePatients},self.filterPatientsByIdentifier=function(){self.filterPatients(matchesId)},self.isSelectedSearch=function(searchType){return self.searchType&&self.searchType.id==searchType.id},self.isCurrentSearchLookUp=function(){return self.searchType&&self.searchType.handler},self.isTileView=function(){return self.searchType&&self.searchType.view===Bahmni.Common.PatientSearch.Constants.searchExtensionTileViewType},self.isTabularView=function(){return self.searchType&&self.searchType.view===Bahmni.Common.PatientSearch.Constants.searchExtensionTabularViewType},self.showPatientCountOnSearchParameter=function(searchType){return showPatientCount(searchType)&&self.searchParameter};var matchesNameOrId=function(patient){return patient.display.toLowerCase().indexOf(self.searchParameter.toLowerCase())!==-1},matchesId=function(patient){return patient.identifier.toLowerCase().indexOf(self.searchParameter.toLowerCase())!==-1},showPatientCount=function(searchType){return self.isSelectedSearch(searchType)&&self.isCurrentSearchLookUp()}},angular.module("bahmni.common.patientSearch",["bahmni.common.patient","infinite-scroll"]);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)}}]);var debugUiRouter=function($rootScope){$rootScope.$on("$stateChangeStart",function(event,toState,toParams){console.log("$stateChangeStart to "+toState.to+"- fired when the transition begins. toState,toParams : \n",toState,toParams)}),$rootScope.$on("$stateChangeError",function(){console.log("$stateChangeError - fired when an error occurs during transition."),console.log(arguments)}),$rootScope.$on("$stateChangeSuccess",function(event,toState){console.log("$stateChangeSuccess to "+toState.name+"- fired once the state transition is complete.")}),$rootScope.$on("$viewContentLoaded",function(event){console.log("$viewContentLoaded - fired after dom rendered",event)}),$rootScope.$on("$stateNotFound",function(event,unfoundState,fromState,fromParams){console.log("$stateNotFound "+unfoundState.to+" - fired when a state cannot be found by its name."),console.log(unfoundState,fromState,fromParams)})},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("ui.calendar",[]).constant("uiCalendarConfig",{calendars:{}}).controller("uiCalendarCtrl",["$scope","$locale",function($scope,$locale){var sources=$scope.eventSources,extraEventSignature=$scope.calendarWatchEvent?$scope.calendarWatchEvent:angular.noop,wrapFunctionWithScopeApply=function(functionToWrap){return function(){if($scope.$root.$$phase)return functionToWrap.apply(this,arguments);var args=arguments,that=this;return $scope.$root.$apply(function(){return functionToWrap.apply(that,args)})}},eventSerialId=1;this.eventFingerprint=function(e){e._id||(e._id=eventSerialId++);var extraSignature=extraEventSignature({event:e})||"",start=moment.isMoment(e.start)?e.start.unix():e.start?moment(e.start).unix():"",end=moment.isMoment(e.end)?e.end.unix():e.end?moment(e.end).unix():"";return[e._id,e.id||"",e.title||"",e.url||"",start,end,e.allDay||"",e.className||"",extraSignature].join("")};var sourceSerialId=1,sourceEventsSerialId=1;this.sourceFingerprint=function(source){var fp=""+(source.__id||(source.__id=sourceSerialId++)),events=angular.isObject(source)&&source.events;return events&&(fp=fp+"-"+(events.__id||(events.__id=sourceEventsSerialId++))),fp},this.allEvents=function(){return Array.prototype.concat.apply([],(sources||[]).reduce(function(previous,source){if(angular.isArray(source))previous.push(source);else if(angular.isObject(source)&&angular.isArray(source.events)){var extEvent=Object.keys(source).filter(function(key){return"_id"!==key&&"events"!==key});source.events.forEach(function(event){angular.extend(event,extEvent)}),previous.push(source.events)}return previous},[]))},this.changeWatcher=function(arraySource,tokenFn){var self,getTokens=function(){return((angular.isFunction(arraySource)?arraySource():arraySource)||[]).reduce(function(rslt,el){var token=tokenFn(el);return map[token]=el,rslt.push(token),rslt},[])},subtractAsSets=function(a,b){var obj=(b||[]).reduce(function(rslt,val){return rslt[val]=!0,rslt},Object.create(null));return(a||[]).filter(function(val){return!obj[val]})},map={},applyChanges=function(newTokens,oldTokens){var i,token,replacedTokens={},removedTokens=subtractAsSets(oldTokens,newTokens);for(i=0;il?(g.push(d),h.push(l),i.push(a(d).height())):k+=l}),d&&(c-=k,e=Math.floor(c/g.length),f=Math.floor(c-e*(g.length-1))),a(g).each(function(b,c){var d=b===g.length-1?f:e,j=h[b],k=i[b],l=d-(j-k);d>j&&a(c).height(l)})}function j(a){a.height("")}function k(b){var c=0;return b.find("> span").each(function(b,d){var e=a(d).outerWidth();e>c&&(c=e)}),c++,b.width(c),c}function l(a,b){var c,d=a.add(b);return d.css({position:"relative",left:-1}),c=a.outerHeight()-b.outerHeight(),d.css({position:"",left:""}),c}function m(b){var c=b.css("position"),d=b.parents().filter(function(){var b=a(this);return/(auto|scroll)/.test(b.css("overflow")+b.css("overflow-y")+b.css("overflow-x"))}).eq(0);return"fixed"!==c&&d.length?d:a(b[0].ownerDocument||document)}function n(a,b){var c=a.offset(),d=c.left-(b?b.left:0),e=c.top-(b?b.top:0);return{left:d,right:d+a.outerWidth(),top:e,bottom:e+a.outerHeight()}}function o(a,b){var c=a.offset(),d=q(a),e=c.left+t(a,"border-left-width")+d.left-(b?b.left:0),f=c.top+t(a,"border-top-width")+d.top-(b?b.top:0);return{left:e,right:e+a[0].clientWidth,top:f,bottom:f+a[0].clientHeight}}function p(a,b){var c=a.offset(),d=c.left+t(a,"border-left-width")+t(a,"padding-left")-(b?b.left:0),e=c.top+t(a,"border-top-width")+t(a,"padding-top")-(b?b.top:0);return{left:d,right:d+a.width(),top:e,bottom:e+a.height()}}function q(a){var b=a.innerWidth()-a[0].clientWidth,c={left:0,right:0,top:0,bottom:a.innerHeight()-a[0].clientHeight};return r()&&"rtl"==a.css("direction")?c.left=b:c.right=b,c}function r(){return null===Ya&&(Ya=s()),Ya}function s(){var b=a("").css({position:"absolute",top:-1e3,left:0,border:0,padding:0,overflow:"scroll",direction:"rtl"}).appendTo("body"),c=b.children(),d=c.offset().left>b.offset().left;return b.remove(),d}function t(a,b){return parseFloat(a.css(b))||0}function u(a){return 1==a.which&&!a.ctrlKey}function v(a){if(void 0!==a.pageX)return a.pageX;var b=a.originalEvent.touches;return b?b[0].pageX:void 0}function w(a){if(void 0!==a.pageY)return a.pageY;var b=a.originalEvent.touches;return b?b[0].pageY:void 0}function x(a){return/^touch/.test(a.type)}function y(a){a.addClass("fc-unselectable").on("selectstart",z)}function z(a){a.preventDefault()}function A(a){return!!window.addEventListener&&(window.addEventListener("scroll",a,!0),!0)}function B(a){return!!window.removeEventListener&&(window.removeEventListener("scroll",a,!0),!0)}function C(a,b){var c={left:Math.max(a.left,b.left),right:Math.min(a.right,b.right),top:Math.max(a.top,b.top),bottom:Math.min(a.bottom,b.bottom)};return c.lefti&&j>g?(g>=i?(c=g.clone(),e=!0):(c=i.clone(),e=!1),j>=h?(d=h.clone(),f=!0):(d=j.clone(),f=!1),{start:c,end:d,isStart:e,isEnd:f}):void 0}function L(a,c){return b.duration({days:a.clone().stripTime().diff(c.clone().stripTime(),"days"),ms:a.time()-c.time()})}function M(a,c){return b.duration({days:a.clone().stripTime().diff(c.clone().stripTime(),"days")})}function N(a,c,d){return b.duration(Math.round(a.diff(c,d,!0)),d)}function O(a,b){var c,d,e;for(c=0;c<$a.length&&(d=$a[c],e=P(d,a,b),!(e>=1&&ha(e)));c++);return d}function P(a,c,d){return null!=d?d.diff(c,a,!0):b.isDuration(c)?c.as(a):c.end.diff(c.start,a,!0)}function Q(a,b,c){var d;return T(c)?(b-a)/c:(d=c.asMonths(),Math.abs(d)>=1&&ha(d)?b.diff(a,"months",!0)/d:b.diff(a,"days",!0)/c.asDays())}function R(a,b){var c,d;return T(a)||T(b)?a/b:(c=a.asMonths(),d=b.asMonths(),Math.abs(c)>=1&&ha(c)&&Math.abs(d)>=1&&ha(d)?c/d:a.asDays()/b.asDays())}function S(a,c){var d;return T(a)?b.duration(a*c):(d=a.asMonths(),Math.abs(d)>=1&&ha(d)?b.duration({months:d*c}):b.duration({days:a.asDays()*c}))}function T(a){return Boolean(a.hours()||a.minutes()||a.seconds()||a.milliseconds())}function U(a){return"[object Date]"===Object.prototype.toString.call(a)||a instanceof Date}function V(a){return/^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(a)}function W(a,b){var c,d,e,f,g,h,i={};if(b)for(c=0;c=0;f--)if(g=a[f][d],"object"==typeof g)e.unshift(g);else if(void 0!==g){i[d]=g;break}e.length&&(i[d]=W(e))}for(c=a.length-1;c>=0;c--){h=a[c];for(d in h)d in i||(i[d]=h[d])}return i}function X(a){var b=function(){};return b.prototype=a,new b}function Y(a,b){for(var c in a)$(a,c)&&(b[c]=a[c])}function Z(a,b){var c,d,e=["constructor","toString","valueOf"];for(c=0;c /g,">").replace(/'/g,"'").replace(/"/g,""").replace(/\n/g," ")}function da(a){return a.replace(/&.*?;/g,"")}function ea(b){var c=[];return a.each(b,function(a,b){null!=b&&c.push(a+":"+b)}),c.join(";")}function fa(a){
return a.charAt(0).toUpperCase()+a.slice(1)}function ga(a,b){return a-b}function ha(a){return a%1===0}function ia(a,b){var c=a[b];return function(){return c.apply(a,arguments)}}function ja(a,b,c){var d,e,f,g,h,i=function(){var j=+new Date-g;b>j?d=setTimeout(i,b-j):(d=null,c||(h=a.apply(f,e),f=e=null))};return function(){f=this,e=arguments,g=+new Date;var j=c&&!d;return d||(d=setTimeout(i,b)),j&&(h=a.apply(f,e),f=e=null),h}}function ka(c,d,e){var f,g,h,i,j=c[0],k=1==c.length&&"string"==typeof j;return b.isMoment(j)?(i=b.apply(null,c),ma(j,i)):U(j)||void 0===j?i=b.apply(null,c):(f=!1,g=!1,k?db.test(j)?(j+="-01",c=[j],f=!0,g=!0):(h=eb.exec(j))&&(f=!h[5],g=!0):a.isArray(j)&&(g=!0),i=d||f?b.utc.apply(b,c):b.apply(null,c),f?(i._ambigTime=!0,i._ambigZone=!0):e&&(g?i._ambigZone=!0:k&&(i.utcOffset?i.utcOffset(j):i.zone(j)))),i._fullCalendar=!0,i}function la(a,c){var d,e,f=!1,g=!1,h=a.length,i=[];for(d=0;h>d;d++)e=a[d],b.isMoment(e)||(e=Va.moment.parseZone(e)),f=f||e._ambigTime,g=g||e._ambigZone,i.push(e);for(d=0;h>d;d++)e=i[d],c||!f||e._ambigTime?g&&!e._ambigZone&&(i[d]=e.clone().stripZone()):i[d]=e.clone().stripTime();return i}function ma(a,b){a._ambigTime?b._ambigTime=!0:b._ambigTime&&(b._ambigTime=!1),a._ambigZone?b._ambigZone=!0:b._ambigZone&&(b._ambigZone=!1)}function na(a,b){a.year(b[0]||0).month(b[1]||0).date(b[2]||0).hours(b[3]||0).minutes(b[4]||0).seconds(b[5]||0).milliseconds(b[6]||0)}function oa(a,b){return gb.format.call(a,b)}function pa(a,b){return qa(a,va(b))}function qa(a,b){var c,d="";for(c=0;cg&&(f=ua(a,b,j,k,c[h]),f!==!1);h--)m=f+m;for(i=g;h>=i;i++)n+=ra(a,c[i]),o+=ra(b,c[i]);return(n||o)&&(p=e?o+d+n:n+d+o),l+p+m}function ua(a,b,c,d,e){var f,g;return"string"==typeof e?e:!!((f=e.token)&&(g=ib[f.charAt(0)],g&&c.isSame(d,g)))&&oa(a,f)}function va(a){return a in jb?jb[a]:jb[a]=wa(a)}function wa(a){for(var b,c=[],d=/\[([^\]]*)\]|\(([^\)]*)\)|(LTS|LT|(\w)\4*o?)|([^\w\[\(]+)/g;b=d.exec(a);)b[1]?c.push(b[1]):b[2]?c.push({maybe:wa(b[2])}):b[3]?c.push({token:b[3]}):b[5]&&c.push(b[5]);return c}function xa(){}function ya(a,b){var c;return $(b,"constructor")&&(c=b.constructor),"function"!=typeof c&&(c=b.constructor=function(){a.apply(this,arguments)}),c.prototype=X(a.prototype),Y(b,c.prototype),Z(b,c.prototype),Y(a,c),c}function za(a,b){Y(b,a.prototype)}function Aa(a,b){return!a&&!b||!(!a||!b)&&(a.component===b.component&&Ba(a,b)&&Ba(b,a))}function Ba(a,b){for(var c in a)if(!/^(component|left|right|top|bottom)$/.test(c)&&a[c]!==b[c])return!1;return!0}function Ca(a){var b=Ea(a);return"background"===b||"inverse-background"===b}function Da(a){return"inverse-background"===Ea(a)}function Ea(a){return ba((a.source||{}).rendering,a.rendering)}function Fa(a){var b,c,d={};for(b=0;b=a.leftCol)return!0;return!1}function Ja(a,b){return a.leftCol-b.leftCol}function Ka(a){var b,c,d,e=[];for(b=0;bb.top&&a.top ").prependTo(c),R=N.header=new Sa(N,O),S=R.render(),S&&c.prepend(S),i(O.defaultView),O.handleWindowResize&&(Y=ja(m,O.windowResizeDelay),a(window).resize(Y))}function g(){V&&V.removeElement(),R.removeElement(),T.remove(),c.removeClass("fc fc-ltr fc-rtl fc-unthemed ui-widget"),Y&&a(window).unbind("resize",Y)}function h(){return c.is(":visible")}function i(b){ca++,V&&b&&V.type!==b&&(R.deactivateButton(V.type),H(),V.removeElement(),V=N.view=null),!V&&b&&(V=N.view=ba[b]||(ba[b]=N.instantiateView(b)),V.setElement(a("
").appendTo(T)),R.activateButton(b)),V&&(Z=V.massageCurrentDate(Z),V.displaying&&Z.isWithin(V.intervalStart,V.intervalEnd)||h()&&(V.display(Z),I(),u(),v(),q())),I(),ca--}function j(a){return h()?(a&&l(),ca++,V.updateSize(!0),ca--,!0):void 0}function k(){h()&&l()}function l(){W="number"==typeof O.contentHeight?O.contentHeight:"number"==typeof O.height?O.height-(S?S.outerHeight(!0):0):Math.round(T.width()/Math.max(O.aspectRatio,.5))}function m(a){!ca&&a.target===window&&V.start&&j(!0)&&V.trigger("windowResize",aa)}function n(){p(),r()}function o(){h()&&(H(),V.displayEvents(da),I())}function p(){H(),V.clearEvents(),I()}function q(){!O.lazyFetching||$(V.start,V.end)?r():o()}function r(){_(V.start,V.end)}function s(a){da=a,o()}function t(){o()}function u(){R.updateTitle(V.title)}function v(){var a=N.getNow();a.isWithin(V.intervalStart,V.intervalEnd)?R.disableButton("today"):R.enableButton("today")}function w(a,b){V.select(N.buildSelectSpan.apply(N,arguments))}function x(){V&&V.unselect()}function y(){Z=V.computePrevDate(Z),i()}function z(){Z=V.computeNextDate(Z),i()}function A(){Z.add(-1,"years"),i()}function B(){Z.add(1,"years"),i()}function C(){Z=N.getNow(),i()}function D(a){Z=N.moment(a).stripZone(),i()}function E(a){Z.add(b.duration(a)),i()}function F(a,b){var c;b=b||"day",c=N.getViewSpec(b)||N.getUnitViewSpec(b),Z=a.clone(),i(c?c.type:null)}function G(){return N.applyTimezone(Z)}function H(){T.css({width:"100%",height:T.height(),overflow:"hidden"})}function I(){T.css({width:"",height:"",overflow:""})}function J(){return N}function K(){return V}function L(a,b){return void 0===b?O[a]:void("height"!=a&&"contentHeight"!=a&&"aspectRatio"!=a||(O[a]=b,j(!0)))}function M(a,b){var c=Array.prototype.slice.call(arguments,2);return b=b||aa,this.triggerWith(a,b,c),O[a]?O[a].apply(b,c):void 0}var N=this;N.initOptions(d||{});var O=this.options;N.render=e,N.destroy=g,N.refetchEvents=n,N.reportEvents=s,N.reportEventChange=t,N.rerenderEvents=o,N.changeView=i,N.select=w,N.unselect=x,N.prev=y,N.next=z,N.prevYear=A,N.nextYear=B,N.today=C,N.gotoDate=D,N.incrementDate=E,N.zoomTo=F,N.getDate=G,N.getCalendar=J,N.getView=K,N.option=L,N.trigger=M;var P=X(Ra(O.lang));if(O.monthNames&&(P._months=O.monthNames),O.monthNamesShort&&(P._monthsShort=O.monthNamesShort),O.dayNames&&(P._weekdays=O.dayNames),O.dayNamesShort&&(P._weekdaysShort=O.dayNamesShort),null!=O.firstDay){var Q=X(P._week);Q.dow=O.firstDay,P._week=Q}P._fullCalendar_weekCalc=function(a){return"function"==typeof a?a:"local"===a?a:"iso"===a||"ISO"===a?"ISO":void 0}(O.weekNumberCalculation),N.defaultAllDayEventDuration=b.duration(O.defaultAllDayEventDuration),N.defaultTimedEventDuration=b.duration(O.defaultTimedEventDuration),N.moment=function(){var a;return"local"===O.timezone?(a=Va.moment.apply(null,arguments),a.hasTime()&&a.local()):a="UTC"===O.timezone?Va.moment.utc.apply(null,arguments):Va.moment.parseZone.apply(null,arguments),"_locale"in a?a._locale=P:a._lang=P,a},N.getIsAmbigTimezone=function(){return"local"!==O.timezone&&"UTC"!==O.timezone},N.applyTimezone=function(a){if(!a.hasTime())return a.clone();var b,c=N.moment(a.toArray()),d=a.time()-c.time();return d&&(b=c.clone().add(d),a.time()-b.time()===0&&(c=b)),c},N.getNow=function(){var a=O.now;return"function"==typeof a&&(a=a()),N.moment(a).stripZone()},N.getEventEnd=function(a){return a.end?a.end.clone():N.getDefaultEventEnd(a.allDay,a.start)},N.getDefaultEventEnd=function(a,b){var c=b.clone();return a?c.stripTime().add(N.defaultAllDayEventDuration):c.add(N.defaultTimedEventDuration),N.getIsAmbigTimezone()&&c.stripZone(),c},N.humanizeDuration=function(a){return(a.locale||a.lang).call(a,O.lang).humanize()},Ta.call(N,O);var R,S,T,U,V,W,Y,Z,$=N.isFetchNeeded,_=N.fetchEvents,aa=c[0],ba={},ca=0,da=[];Z=null!=O.defaultDate?N.moment(O.defaultDate).stripZone():N.getNow(),N.getSuggestedViewHeight=function(){return void 0===W&&k(),W},N.isHeightAuto=function(){return"auto"===O.contentHeight||"auto"===O.height},N.freezeContentHeight=H,N.unfreezeContentHeight=I,N.initialize()}function Qa(b){a.each(Cb,function(a,c){null==b[a]&&(b[a]=c(b))})}function Ra(a){var c=b.localeData||b.langData;return c.call(b,a)||c.call(b,"en")}function Sa(b,c){function d(){var b=c.header;return n=c.theme?"ui":"fc",b?o=a("
").append(f("left")).append(f("right")).append(f("center")).append('
'):void 0}function e(){o.remove(),o=a()}function f(d){var e=a('
'),f=c.header[d];return f&&a.each(f.split(" "),function(d){var f,g=a(),h=!0;a.each(this.split(","),function(d,e){var f,i,j,k,l,m,o,q,r,s;"title"==e?(g=g.add(a(" ")),h=!1):((f=(b.options.customButtons||{})[e])?(j=function(a){f.click&&f.click.call(s[0],a)},k="",l=f.text):(i=b.getViewSpec(e))?(j=function(){b.changeView(e)},p.push(e),k=i.buttonTextOverride,l=i.buttonTextDefault):b[e]&&(j=function(){b[e]()},k=(b.overrides.buttonText||{})[e],l=c.buttonText[e]),j&&(m=f?f.themeIcon:c.themeButtonIcons[e],o=f?f.icon:c.buttonIcons[e],q=k?ca(k):m&&c.theme?" ":o&&!c.theme?" ":ca(l),r=["fc-"+e+"-button",n+"-button",n+"-state-default"],s=a(''+q+" ").click(function(a){s.hasClass(n+"-state-disabled")||(j(a),(s.hasClass(n+"-state-active")||s.hasClass(n+"-state-disabled"))&&s.removeClass(n+"-state-hover"))}).mousedown(function(){s.not("."+n+"-state-active").not("."+n+"-state-disabled").addClass(n+"-state-down")}).mouseup(function(){s.removeClass(n+"-state-down")}).hover(function(){s.not("."+n+"-state-active").not("."+n+"-state-disabled").addClass(n+"-state-hover")},function(){s.removeClass(n+"-state-hover").removeClass(n+"-state-down")}),g=g.add(s)))}),h&&g.first().addClass(n+"-corner-left").end().last().addClass(n+"-corner-right").end(),g.length>1?(f=a("
"),h&&f.addClass("fc-button-group"),f.append(g),e.append(f)):e.append(g)}),e}function g(a){o.find("h2").text(a)}function h(a){o.find(".fc-"+a+"-button").addClass(n+"-state-active")}function i(a){o.find(".fc-"+a+"-button").removeClass(n+"-state-active")}function j(a){o.find(".fc-"+a+"-button").attr("disabled","disabled").addClass(n+"-state-disabled")}function k(a){o.find(".fc-"+a+"-button").removeAttr("disabled").removeClass(n+"-state-disabled")}function l(){return p}var m=this;m.render=d,m.removeElement=e,m.updateTitle=g,m.activateButton=h,m.deactivateButton=i,m.disableButton=j,m.enableButton=k,m.getViewsWithButtons=l;var n,o=a(),p=[]}function Ta(c){function d(a,b){return!I||I>a||b>J}function e(a,b){I=a,J=b,S=[];var c=++Q,d=P.length;R=d;for(var e=0;d>e;e++)f(P[e],c)}function f(b,c){g(b,function(d){var e,f,g,h=a.isArray(b.events);if(c==Q){if(d)for(e=0;e=c&&b.end<=d}function G(a,b){var c=a.start.clone().stripZone(),d=H.getEventEnd(a).stripZone();return b.startc}var H=this;H.isFetchNeeded=d,H.fetchEvents=e,H.addEventSource=h,H.removeEventSource=j,H.updateEvent=m,H.renderEvent=p,H.removeEvents=q,H.clientEvents=r,H.mutateEvent=x,H.normalizeEventDates=u,H.normalizeEventTimes=v;var I,J,K=H.reportEvents,O={events:[]},P=[O],Q=0,R=0,S=[];a.each((c.events?[c.events]:[]).concat(c.eventSources||[]),function(a,b){var c=i(b);c&&P.push(c)}),H.getBusinessHoursEvents=z,H.isEventSpanAllowed=A,H.isExternalSpanAllowed=B,H.isSelectionSpanAllowed=C,H.getEventCache=function(){return S}}function Ua(a){a._allDay=a.allDay,a._start=a.start.clone(),a._end=a.end?a.end.clone():null}var Va=a.fullCalendar={version:"2.7.3",internalApiVersion:4},Wa=Va.views={};a.fn.fullCalendar=function(b){var c=Array.prototype.slice.call(arguments,1),d=this;return this.each(function(e,f){var g,h=a(f),i=h.data("fullCalendar");"string"==typeof b?i&&a.isFunction(i[b])&&(g=i[b].apply(i,c),e||(d=g),"destroy"===b&&h.removeData("fullCalendar")):i||(i=new yb(h,b),h.data("fullCalendar",i),i.render())}),d};var Xa=["header","buttonText","buttonIcons","themeButtonIcons"];Va.intersectRanges=K,Va.applyAll=aa,Va.debounce=ja,Va.isInt=ha,Va.htmlEscape=ca,Va.cssToStr=ea,Va.proxy=ia,Va.capitaliseFirstLetter=fa,Va.getOuterRect=n,Va.getClientRect=o,Va.getContentRect=p,Va.getScrollbarWidths=q;var Ya=null;Va.preventDefault=z,Va.intersectRects=C,Va.parseFieldSpecs=G,Va.compareByFieldSpecs=H,Va.compareByFieldSpec=I,Va.flexibleCompare=J,Va.computeIntervalUnit=O,Va.divideRangeByDuration=Q,Va.divideDurationByDuration=R,Va.multiplyDuration=S,Va.durationHasTime=T;var Za=["sun","mon","tue","wed","thu","fri","sat"],$a=["year","month","week","day","hour","minute","second","millisecond"];Va.log=function(){var a=window.console;return a&&a.log?a.log.apply(a,arguments):void 0},Va.warn=function(){var a=window.console;return a&&a.warn?a.warn.apply(a,arguments):Va.log.apply(Va,arguments)};var _a,ab,bb,cb={}.hasOwnProperty,db=/^\s*\d{4}-\d\d$/,eb=/^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?)?$/,fb=b.fn,gb=a.extend({},fb);Va.moment=function(){return ka(arguments)},Va.moment.utc=function(){var a=ka(arguments,!0);return a.hasTime()&&a.utc(),a},Va.moment.parseZone=function(){return ka(arguments,!0,!0)},fb.clone=function(){var a=gb.clone.apply(this,arguments);return ma(this,a),this._fullCalendar&&(a._fullCalendar=!0),a},fb.week=fb.weeks=function(a){var b=(this._locale||this._lang)._fullCalendar_weekCalc;return null==a&&"function"==typeof b?b(this):"ISO"===b?gb.isoWeek.apply(this,arguments):gb.week.apply(this,arguments)},fb.time=function(a){if(!this._fullCalendar)return gb.time.apply(this,arguments);if(null==a)return b.duration({hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds()});this._ambigTime=!1,b.isDuration(a)||b.isMoment(a)||(a=b.duration(a));var c=0;return b.isDuration(a)&&(c=24*Math.floor(a.asDays())),this.hours(c+a.hours()).minutes(a.minutes()).seconds(a.seconds()).milliseconds(a.milliseconds())},fb.stripTime=function(){var a;return this._ambigTime||(a=this.toArray(),this.utc(),ab(this,a.slice(0,3)),this._ambigTime=!0,this._ambigZone=!0),this},fb.hasTime=function(){return!this._ambigTime},fb.stripZone=function(){var a,b;return this._ambigZone||(a=this.toArray(),b=this._ambigTime,this.utc(),ab(this,a),this._ambigTime=b||!1,this._ambigZone=!0),this},fb.hasZone=function(){return!this._ambigZone},fb.local=function(){var a=this.toArray(),b=this._ambigZone;return gb.local.apply(this,arguments),this._ambigTime=!1,this._ambigZone=!1,b&&bb(this,a),this},fb.utc=function(){return gb.utc.apply(this,arguments),this._ambigTime=!1,this._ambigZone=!1,this},a.each(["zone","utcOffset"],function(a,b){gb[b]&&(fb[b]=function(a){return null!=a&&(this._ambigTime=!1,this._ambigZone=!1),gb[b].apply(this,arguments)})}),fb.format=function(){return this._fullCalendar&&arguments[0]?pa(this,arguments[0]):this._ambigTime?oa(this,"YYYY-MM-DD"):this._ambigZone?oa(this,"YYYY-MM-DD[T]HH:mm:ss"):gb.format.apply(this,arguments)},fb.toISOString=function(){return this._ambigTime?oa(this,"YYYY-MM-DD"):this._ambigZone?oa(this,"YYYY-MM-DD[T]HH:mm:ss"):gb.toISOString.apply(this,arguments)},fb.isWithin=function(a,b){var c=la([this,a,b]);return c[0]>=c[1]&&c[0]a;a++)b=arguments[a],c-1>a&&za(this,b);return ya(this,b||{})},xa.mixin=function(a){za(this,a)};var kb=Va.EmitterMixin={on:function(b,c){var d=function(a,b){return c.apply(b.context||this,b.args||[])};return c.guid||(c.guid=a.guid++),d.guid=c.guid,a(this).on(b,d),this},off:function(b,c){return a(this).off(b,c),this},trigger:function(b){var c=Array.prototype.slice.call(arguments,1);return a(this).triggerHandler(b,{args:c}),this},triggerWith:function(b,c,d){return a(this).triggerHandler(b,{context:c,args:d}),this}},lb=Va.ListenerMixin=function(){var b=0,c={listenerId:null,listenTo:function(b,c,d){if("object"==typeof c)for(var e in c)c.hasOwnProperty(e)&&this.listenTo(b,e,c[e]);else"string"==typeof c&&b.on(c+"."+this.getListenerNamespace(),a.proxy(d,this))},stopListeningTo:function(a,b){a.off((b||"")+"."+this.getListenerNamespace())},getListenerNamespace:function(){return null==this.listenerId&&(this.listenerId=b++),"_listener"+this.listenerId}};return c}(),mb={isIgnoringMouse:!1,delayUnignoreMouse:null,initMouseIgnoring:function(a){this.delayUnignoreMouse=ja(ia(this,"unignoreMouse"),a||1e3)},tempIgnoreMouse:function(){this.isIgnoringMouse=!0,this.delayUnignoreMouse()},unignoreMouse:function(){this.isIgnoringMouse=!1}},nb=xa.extend(lb,{isHidden:!0,options:null,el:null,margin:10,constructor:function(a){this.options=a||{}},show:function(){this.isHidden&&(this.el||this.render(),this.el.show(),this.position(),this.isHidden=!1,this.trigger("show"))},hide:function(){this.isHidden||(this.el.hide(),this.isHidden=!0,this.trigger("hide"))},render:function(){var b=this,c=this.options;this.el=a('
').addClass(c.className||"").css({top:0,left:0}).append(c.content).appendTo(c.parentEl),this.el.on("click",".fc-close",function(){b.hide()}),c.autoHide&&this.listenTo(a(document),"mousedown",this.documentMousedown)},documentMousedown:function(b){this.el&&!a(b.target).closest(this.el).length&&this.hide()},removeElement:function(){this.hide(),this.el&&(this.el.remove(),this.el=null),this.stopListeningTo(a(document),"mousedown")},position:function(){var b,c,d,e,f,g=this.options,h=this.el.offsetParent().offset(),i=this.el.outerWidth(),j=this.el.outerHeight(),k=a(window),l=m(this.el);e=g.top||0,f=void 0!==g.left?g.left:void 0!==g.right?g.right-i:0,l.is(window)||l.is(document)?(l=k,b=0,c=0):(d=l.offset(),b=d.top,c=d.left),b+=k.scrollTop(),c+=k.scrollLeft(),g.viewportConstrain!==!1&&(e=Math.min(e,b+l.outerHeight()-j-this.margin),e=Math.max(e,b+this.margin),f=Math.min(f,c+l.outerWidth()-i-this.margin),f=Math.max(f,c+this.margin)),this.el.css({top:e-h.top,left:f-h.left})},trigger:function(a){this.options[a]&&this.options[a].apply(this,Array.prototype.slice.call(arguments,1))}}),ob=Va.CoordCache=xa.extend({els:null,forcedOffsetParentEl:null,origin:null,boundingRect:null,isHorizontal:!1,isVertical:!1,lefts:null,rights:null,tops:null,bottoms:null,constructor:function(b){this.els=a(b.els),this.isHorizontal=b.isHorizontal,this.isVertical=b.isVertical,this.forcedOffsetParentEl=b.offsetParent?a(b.offsetParent):null},build:function(){var a=this.forcedOffsetParentEl||this.els.eq(0).offsetParent();this.origin=a.offset(),this.boundingRect=this.queryBoundingRect(),this.isHorizontal&&this.buildElHorizontals(),this.isVertical&&this.buildElVerticals()},clear:function(){this.origin=null,this.boundingRect=null,this.lefts=null,this.rights=null,this.tops=null,this.bottoms=null},ensureBuilt:function(){this.origin||this.build()},queryBoundingRect:function(){var a=m(this.els.eq(0));return a.is(document)?void 0:o(a)},buildElHorizontals:function(){var b=[],c=[];this.els.each(function(d,e){var f=a(e),g=f.offset().left,h=f.outerWidth();b.push(g),c.push(g+h)}),this.lefts=b,this.rights=c},buildElVerticals:function(){var b=[],c=[];this.els.each(function(d,e){var f=a(e),g=f.offset().top,h=f.outerHeight();b.push(g),c.push(g+h)}),this.tops=b,this.bottoms=c},getHorizontalIndex:function(a){this.ensureBuilt();var b,c=this.boundingRect,d=this.lefts,e=this.rights,f=d.length;if(!c||a>=c.left&&ab;b++)if(a>=d[b]&&a=c.top&&ab;b++)if(a>=d[b]&&a=e*e&&this.handleDistanceSurpassed(a)),this.isDragging&&this.handleDrag(c,d,a)},handleDrag:function(a,b,c){this.trigger("drag",a,b,c),this.updateAutoScroll(c)},endDrag:function(a){this.isDragging&&(this.isDragging=!1,this.handleDragEnd(a))},handleDragEnd:function(a){this.trigger("dragEnd",a),this.destroyHrefHack()},startDelay:function(a){var b=this;this.delay?this.delayTimeoutId=setTimeout(function(){b.handleDelayEnd(a)},this.delay):this.handleDelayEnd(a)},handleDelayEnd:function(a){this.isDelayEnded=!0,this.isDistanceSurpassed&&this.startDrag(a)},handleDistanceSurpassed:function(a){this.isDistanceSurpassed=!0,this.isDelayEnded&&this.startDrag(a)},handleTouchMove:function(a){this.isDragging&&a.preventDefault(),this.handleMove(a)},handleMouseMove:function(a){this.handleMove(a)},handleTouchScroll:function(a){this.isDragging||this.endInteraction(a,!0);
},initHrefHack:function(){var a=this.subjectEl;(this.subjectHref=a?a.attr("href"):null)&&a.removeAttr("href")},destroyHrefHack:function(){var a=this.subjectEl,b=this.subjectHref;setTimeout(function(){b&&a.attr("href",b)},0)},trigger:function(a){this.options[a]&&this.options[a].apply(this,Array.prototype.slice.call(arguments,1)),this["_"+a]&&this["_"+a].apply(this,Array.prototype.slice.call(arguments,1))}});pb.mixin({isAutoScroll:!1,scrollBounds:null,scrollTopVel:null,scrollLeftVel:null,scrollIntervalId:null,scrollSensitivity:30,scrollSpeed:200,scrollIntervalMs:50,initAutoScroll:function(){var a=this.scrollEl;this.isAutoScroll=this.options.scroll&&a&&!a.is(window)&&!a.is(document),this.isAutoScroll&&this.listenTo(a,"scroll",ja(this.handleDebouncedScroll,100))},destroyAutoScroll:function(){this.endAutoScroll(),this.isAutoScroll&&this.stopListeningTo(this.scrollEl,"scroll")},computeScrollBounds:function(){this.isAutoScroll&&(this.scrollBounds=n(this.scrollEl))},updateAutoScroll:function(a){var b,c,d,e,f=this.scrollSensitivity,g=this.scrollBounds,h=0,i=0;g&&(b=(f-(w(a)-g.top))/f,c=(f-(g.bottom-w(a)))/f,d=(f-(v(a)-g.left))/f,e=(f-(g.right-v(a)))/f,b>=0&&1>=b?h=b*this.scrollSpeed*-1:c>=0&&1>=c&&(h=c*this.scrollSpeed),d>=0&&1>=d?i=d*this.scrollSpeed*-1:e>=0&&1>=e&&(i=e*this.scrollSpeed)),this.setScrollVel(h,i)},setScrollVel:function(a,b){this.scrollTopVel=a,this.scrollLeftVel=b,this.constrainScrollVel(),!this.scrollTopVel&&!this.scrollLeftVel||this.scrollIntervalId||(this.scrollIntervalId=setInterval(ia(this,"scrollIntervalFunc"),this.scrollIntervalMs))},constrainScrollVel:function(){var a=this.scrollEl;this.scrollTopVel<0?a.scrollTop()<=0&&(this.scrollTopVel=0):this.scrollTopVel>0&&a.scrollTop()+a[0].clientHeight>=a[0].scrollHeight&&(this.scrollTopVel=0),this.scrollLeftVel<0?a.scrollLeft()<=0&&(this.scrollLeftVel=0):this.scrollLeftVel>0&&a.scrollLeft()+a[0].clientWidth>=a[0].scrollWidth&&(this.scrollLeftVel=0)},scrollIntervalFunc:function(){var a=this.scrollEl,b=this.scrollIntervalMs/1e3;this.scrollTopVel&&a.scrollTop(a.scrollTop()+this.scrollTopVel*b),this.scrollLeftVel&&a.scrollLeft(a.scrollLeft()+this.scrollLeftVel*b),this.constrainScrollVel(),this.scrollTopVel||this.scrollLeftVel||this.endAutoScroll()},endAutoScroll:function(){this.scrollIntervalId&&(clearInterval(this.scrollIntervalId),this.scrollIntervalId=null,this.handleScrollEnd())},handleDebouncedScroll:function(){this.scrollIntervalId||this.handleScrollEnd()},handleScrollEnd:function(){}});var qb=pb.extend({component:null,origHit:null,hit:null,coordAdjust:null,constructor:function(a,b){pb.call(this,b),this.component=a},handleInteractionStart:function(a){var b,c,d,e=this.subjectEl;this.computeCoords(),a?(c={left:v(a),top:w(a)},d=c,e&&(b=n(e),d=D(d,b)),this.origHit=this.queryHit(d.left,d.top),e&&this.options.subjectCenter&&(this.origHit&&(b=C(this.origHit,b)||b),d=E(b)),this.coordAdjust=F(d,c)):(this.origHit=null,this.coordAdjust=null),pb.prototype.handleInteractionStart.apply(this,arguments)},computeCoords:function(){this.component.prepareHits(),this.computeScrollBounds()},handleDragStart:function(a){var b;pb.prototype.handleDragStart.apply(this,arguments),b=this.queryHit(v(a),w(a)),b&&this.handleHitOver(b)},handleDrag:function(a,b,c){var d;pb.prototype.handleDrag.apply(this,arguments),d=this.queryHit(v(c),w(c)),Aa(d,this.hit)||(this.hit&&this.handleHitOut(),d&&this.handleHitOver(d))},handleDragEnd:function(){this.handleHitDone(),pb.prototype.handleDragEnd.apply(this,arguments)},handleHitOver:function(a){var b=Aa(a,this.origHit);this.hit=a,this.trigger("hitOver",this.hit,b,this.origHit)},handleHitOut:function(){this.hit&&(this.trigger("hitOut",this.hit),this.handleHitDone(),this.hit=null)},handleHitDone:function(){this.hit&&this.trigger("hitDone",this.hit)},handleInteractionEnd:function(){pb.prototype.handleInteractionEnd.apply(this,arguments),this.origHit=null,this.hit=null,this.component.releaseHits()},handleScrollEnd:function(){pb.prototype.handleScrollEnd.apply(this,arguments),this.computeCoords()},queryHit:function(a,b){return this.coordAdjust&&(a+=this.coordAdjust.left,b+=this.coordAdjust.top),this.component.queryHit(a,b)}}),rb=xa.extend(lb,{options:null,sourceEl:null,el:null,parentEl:null,top0:null,left0:null,y0:null,x0:null,topDelta:null,leftDelta:null,isFollowing:!1,isHidden:!1,isAnimating:!1,constructor:function(b,c){this.options=c=c||{},this.sourceEl=b,this.parentEl=c.parentEl?a(c.parentEl):b.parent()},start:function(b){this.isFollowing||(this.isFollowing=!0,this.y0=w(b),this.x0=v(b),this.topDelta=0,this.leftDelta=0,this.isHidden||this.updatePosition(),x(b)?this.listenTo(a(document),"touchmove",this.handleMove):this.listenTo(a(document),"mousemove",this.handleMove))},stop:function(b,c){function d(){this.isAnimating=!1,e.removeElement(),this.top0=this.left0=null,c&&c()}var e=this,f=this.options.revertDuration;this.isFollowing&&!this.isAnimating&&(this.isFollowing=!1,this.stopListeningTo(a(document)),b&&f&&!this.isHidden?(this.isAnimating=!0,this.el.animate({top:this.top0,left:this.left0},{duration:f,complete:d})):d())},getEl:function(){var a=this.el;return a||(this.sourceEl.width(),a=this.el=this.sourceEl.clone().addClass(this.options.additionalClass||"").css({position:"absolute",visibility:"",display:this.isHidden?"none":"",margin:0,right:"auto",bottom:"auto",width:this.sourceEl.width(),height:this.sourceEl.height(),opacity:this.options.opacity||"",zIndex:this.options.zIndex}),a.addClass("fc-unselectable"),a.appendTo(this.parentEl)),a},removeElement:function(){this.el&&(this.el.remove(),this.el=null)},updatePosition:function(){var a,b;this.getEl(),null===this.top0&&(this.sourceEl.width(),a=this.sourceEl.offset(),b=this.el.offsetParent().offset(),this.top0=a.top-b.top,this.left0=a.left-b.left),this.el.css({top:this.top0+this.topDelta,left:this.left0+this.leftDelta})},handleMove:function(a){this.topDelta=w(a)-this.y0,this.leftDelta=v(a)-this.x0,this.isHidden||this.updatePosition()},hide:function(){this.isHidden||(this.isHidden=!0,this.el&&this.el.hide())},show:function(){this.isHidden&&(this.isHidden=!1,this.updatePosition(),this.getEl().show())}}),sb=Va.Grid=xa.extend(lb,mb,{view:null,isRTL:null,start:null,end:null,el:null,elsByFill:null,eventTimeFormat:null,displayEventTime:null,displayEventEnd:null,minResizeDuration:null,largeUnit:null,dayDragListener:null,segDragListener:null,segResizeListener:null,externalDragListener:null,constructor:function(a){this.view=a,this.isRTL=a.opt("isRTL"),this.elsByFill={},this.dayDragListener=this.buildDayDragListener(),this.initMouseIgnoring()},computeEventTimeFormat:function(){return this.view.opt("smallTimeFormat")},computeDisplayEventTime:function(){return!0},computeDisplayEventEnd:function(){return!0},setRange:function(a){this.start=a.start.clone(),this.end=a.end.clone(),this.rangeUpdated(),this.processRangeOptions()},rangeUpdated:function(){},processRangeOptions:function(){var a,b,c=this.view;this.eventTimeFormat=c.opt("eventTimeFormat")||c.opt("timeFormat")||this.computeEventTimeFormat(),a=c.opt("displayEventTime"),null==a&&(a=this.computeDisplayEventTime()),b=c.opt("displayEventEnd"),null==b&&(b=this.computeDisplayEventEnd()),this.displayEventTime=a,this.displayEventEnd=b},spanToSegs:function(a){},diffDates:function(a,b){return this.largeUnit?N(a,b,this.largeUnit):L(a,b)},prepareHits:function(){},releaseHits:function(){},queryHit:function(a,b){},getHitSpan:function(a){},getHitEl:function(a){},setElement:function(a){this.el=a,y(a),this.bindDayHandler("touchstart",this.dayTouchStart),this.bindDayHandler("mousedown",this.dayMousedown),this.bindSegHandlers(),this.bindGlobalHandlers()},bindDayHandler:function(b,c){var d=this;this.el.on(b,function(b){return a(b.target).is(".fc-event-container *, .fc-more")||a(b.target).closest(".fc-popover").length?void 0:c.call(d,b)})},removeElement:function(){this.unbindGlobalHandlers(),this.clearDragListeners(),this.el.remove()},renderSkeleton:function(){},renderDates:function(){},unrenderDates:function(){},bindGlobalHandlers:function(){this.listenTo(a(document),{dragstart:this.externalDragStart,sortstart:this.externalDragStart})},unbindGlobalHandlers:function(){this.stopListeningTo(a(document))},dayMousedown:function(a){this.isIgnoringMouse||this.dayDragListener.startInteraction(a,{})},dayTouchStart:function(a){var b=this.view;(b.isSelected||b.selectedEvent)&&this.tempIgnoreMouse(),this.dayDragListener.startInteraction(a,{delay:this.view.opt("longPressDelay")})},buildDayDragListener:function(){var a,b,c=this,d=this.view,e=d.opt("selectable"),f=new qb(this,{scroll:d.opt("dragScroll"),interactionStart:function(){a=f.origHit},dragStart:function(){d.unselect()},hitOver:function(d,f,h){h&&(f||(a=null),e&&(b=c.computeSelection(c.getHitSpan(h),c.getHitSpan(d)),b?c.renderSelection(b):b===!1&&g()))},hitOut:function(){a=null,b=null,c.unrenderSelection(),h()},interactionEnd:function(e,f){f||(a&&!c.isIgnoringMouse&&d.triggerDayClick(c.getHitSpan(a),c.getHitEl(a),e),b&&d.reportSelection(b,e),h())}});return f},clearDragListeners:function(){this.dayDragListener.endInteraction(),this.segDragListener&&this.segDragListener.endInteraction(),this.segResizeListener&&this.segResizeListener.endInteraction(),this.externalDragListener&&this.externalDragListener.endInteraction()},renderEventLocationHelper:function(a,b){var c=this.fabricateHelperEvent(a,b);return this.renderHelper(c,b)},fabricateHelperEvent:function(a,b){var c=b?X(b.event):{};return c.start=a.start.clone(),c.end=a.end?a.end.clone():null,c.allDay=null,this.view.calendar.normalizeEventDates(c),c.className=(c.className||[]).concat("fc-helper"),b||(c.editable=!1),c},renderHelper:function(a,b){},unrenderHelper:function(){},renderSelection:function(a){this.renderHighlight(a)},unrenderSelection:function(){this.unrenderHighlight()},computeSelection:function(a,b){var c=this.computeSelectionSpan(a,b);return!(c&&!this.view.calendar.isSelectionSpanAllowed(c))&&c},computeSelectionSpan:function(a,b){var c=[a.start,a.end,b.start,b.end];return c.sort(ga),{start:c[0].clone(),end:c[3].clone()}},renderHighlight:function(a){this.renderFill("highlight",this.spanToSegs(a))},unrenderHighlight:function(){this.unrenderFill("highlight")},highlightSegClasses:function(){return["fc-highlight"]},renderBusinessHours:function(){},unrenderBusinessHours:function(){},getNowIndicatorUnit:function(){},renderNowIndicator:function(a){},unrenderNowIndicator:function(){},renderFill:function(a,b){},unrenderFill:function(a){var b=this.elsByFill[a];b&&(b.remove(),delete this.elsByFill[a])},renderFillSegEls:function(b,c){var d,e=this,f=this[b+"SegEl"],g="",h=[];if(c.length){for(d=0;d "},getDayClasses:function(a){var b=this.view,c=b.calendar.getNow(),d=["fc-"+Za[a.day()]];return 1==b.intervalDuration.as("months")&&a.month()!=b.intervalStart.month()&&d.push("fc-other-month"),a.isSame(c,"day")?d.push("fc-today",b.highlightStateClass):c>a?d.push("fc-past"):d.push("fc-future"),d}});sb.mixin({mousedOverSeg:null,isDraggingSeg:!1,isResizingSeg:!1,isDraggingExternal:!1,segs:null,renderEvents:function(a){var b,c=[],d=[];for(b=0;b *",function(b){var e=a(this).data("fc-seg");return!e||d.isDraggingSeg||d.isResizingSeg?void 0:c.call(d,e,b)})},handleSegClick:function(a,b){return this.view.trigger("eventClick",a.el[0],a.event,b)},handleSegMouseover:function(a,b){this.isIgnoringMouse||this.mousedOverSeg||(this.mousedOverSeg=a,a.el.addClass("fc-allow-mouse-resize"),this.view.trigger("eventMouseover",a.el[0],a.event,b))},handleSegMouseout:function(a,b){b=b||{},this.mousedOverSeg&&(a=a||this.mousedOverSeg,this.mousedOverSeg=null,a.el.removeClass("fc-allow-mouse-resize"),this.view.trigger("eventMouseout",a.el[0],a.event,b))},handleSegMousedown:function(a,b){var c=this.startSegResize(a,b,{distance:5});!c&&this.view.isEventDraggable(a.event)&&this.buildSegDragListener(a).startInteraction(b,{distance:5})},handleSegTouchStart:function(a,b){var c,d=this.view,e=a.event,f=d.isEventSelected(e),g=d.isEventDraggable(e),h=d.isEventResizable(e),i=!1;f&&h&&(i=this.startSegResize(a,b)),i||!g&&!h||(c=g?this.buildSegDragListener(a):this.buildSegSelectListener(a),c.startInteraction(b,{delay:f?0:this.view.opt("longPressDelay")})),this.tempIgnoreMouse()},handleSegTouchEnd:function(a,b){this.tempIgnoreMouse()},startSegResize:function(b,c,d){return!!a(c.target).is(".fc-resizer")&&(this.buildSegResizeListener(b,a(c.target).is(".fc-start-resizer")).startInteraction(c,d),!0)},buildSegDragListener:function(a){var b,c,d,e=this,f=this.view,i=f.calendar,j=a.el,k=a.event;if(this.segDragListener)return this.segDragListener;var l=this.segDragListener=new qb(f,{scroll:f.opt("dragScroll"),subjectEl:j,subjectCenter:!0,interactionStart:function(d){b=!1,c=new rb(a.el,{additionalClass:"fc-dragging",parentEl:f.el,opacity:l.isTouch?null:f.opt("dragOpacity"),revertDuration:f.opt("dragRevertDuration"),zIndex:2}),c.hide(),c.start(d)},dragStart:function(c){l.isTouch&&!f.isEventSelected(k)&&f.selectEvent(k),b=!0,e.handleSegMouseout(a,c),e.segDragStart(a,c),f.hideEvent(k)},hitOver:function(b,h,j){var m;a.hit&&(j=a.hit),d=e.computeEventDrop(j.component.getHitSpan(j),b.component.getHitSpan(b),k),d&&!i.isEventSpanAllowed(e.eventToSpan(d),k)&&(g(),d=null),d&&(m=f.renderDrag(d,a))?(m.addClass("fc-dragging"),l.isTouch||e.applyDragOpacity(m),c.hide()):c.show(),h&&(d=null)},hitOut:function(){f.unrenderDrag(),c.show(),d=null},hitDone:function(){h()},interactionEnd:function(g){c.stop(!d,function(){b&&(f.unrenderDrag(),f.showEvent(k),e.segDragStop(a,g)),d&&f.reportEventDrop(k,d,this.largeUnit,j,g)}),e.segDragListener=null}});return l},buildSegSelectListener:function(a){var b=this,c=this.view,d=a.event;if(this.segDragListener)return this.segDragListener;var e=this.segDragListener=new pb({dragStart:function(a){e.isTouch&&!c.isEventSelected(d)&&c.selectEvent(d)},interactionEnd:function(a){b.segDragListener=null}});return e},segDragStart:function(a,b){this.isDraggingSeg=!0,this.view.trigger("eventDragStart",a.el[0],a.event,b,{})},segDragStop:function(a,b){this.isDraggingSeg=!1,this.view.trigger("eventDragStop",a.el[0],a.event,b,{})},computeEventDrop:function(a,b,c){var d,e,f=this.view.calendar,g=a.start,h=b.start;return g.hasTime()===h.hasTime()?(d=this.diffDates(h,g),c.allDay&&T(d)?(e={start:c.start.clone(),end:f.getEventEnd(c),allDay:!1},f.normalizeEventTimes(e)):e={start:c.start.clone(),end:c.end?c.end.clone():null,allDay:c.allDay},e.start.add(d),e.end&&e.end.add(d)):e={start:h.clone(),end:null,allDay:!h.hasTime()},e},applyDragOpacity:function(a){var b=this.view.opt("dragOpacity");null!=b&&a.each(function(a,c){c.style.opacity=b})},externalDragStart:function(b,c){var d,e,f=this.view;f.opt("droppable")&&(d=a((c?c.item:null)||b.target),e=f.opt("dropAccept"),(a.isFunction(e)?e.call(d[0],d):d.is(e))&&(this.isDraggingExternal||this.listenToExternalDrag(d,b,c)))},listenToExternalDrag:function(a,b,c){var d,e=this,f=this.view.calendar,i=Ha(a),j=e.externalDragListener=new qb(this,{interactionStart:function(){e.isDraggingExternal=!0},hitOver:function(a){d=e.computeExternalDrop(a.component.getHitSpan(a),i),d&&!f.isExternalSpanAllowed(e.eventToSpan(d),d,i.eventProps)&&(g(),d=null),d&&e.renderDrag(d)},hitOut:function(){d=null},hitDone:function(){h(),e.unrenderDrag()},interactionEnd:function(b){d&&e.view.reportExternalDrop(i,d,a,b,c),e.isDraggingExternal=!1,e.externalDragListener=null}});j.startDrag(b)},computeExternalDrop:function(a,b){var c=this.view.calendar,d={start:c.applyTimezone(a.start),end:null};return b.startTime&&!d.start.hasTime()&&d.start.time(b.startTime),b.duration&&(d.end=d.start.clone().add(b.duration)),d},renderDrag:function(a,b){},unrenderDrag:function(){},buildSegResizeListener:function(a,b){var c,d,e=this,f=this.view,i=f.calendar,j=a.el,k=a.event,l=i.getEventEnd(k),m=this.segResizeListener=new qb(this,{scroll:f.opt("dragScroll"),subjectEl:j,interactionStart:function(){c=!1},dragStart:function(b){c=!0,e.handleSegMouseout(a,b),e.segResizeStart(a,b)},hitOver:function(c,h,j){var m=e.getHitSpan(j),n=e.getHitSpan(c);d=b?e.computeEventStartResize(m,n,k):e.computeEventEndResize(m,n,k),d&&(i.isEventSpanAllowed(e.eventToSpan(d),k)?d.start.isSame(k.start)&&d.end.isSame(l)&&(d=null):(g(),d=null)),d&&(f.hideEvent(k),e.renderEventResize(d,a))},hitOut:function(){d=null},hitDone:function(){e.unrenderEventResize(),f.showEvent(k),h()},interactionEnd:function(b){c&&e.segResizeStop(a,b),d&&f.reportEventResize(k,d,this.largeUnit,j,b),e.segResizeListener=null}});return m},segResizeStart:function(a,b){this.isResizingSeg=!0,this.view.trigger("eventResizeStart",a.el[0],a.event,b,{})},segResizeStop:function(a,b){this.isResizingSeg=!1,this.view.trigger("eventResizeStop",a.el[0],a.event,b,{})},computeEventStartResize:function(a,b,c){return this.computeEventResize("start",a,b,c)},computeEventEndResize:function(a,b,c){return this.computeEventResize("end",a,b,c)},computeEventResize:function(a,b,c,d){var e,f,g=this.view.calendar,h=this.diffDates(c[a],b[a]);return e={start:d.start.clone(),end:g.getEventEnd(d),allDay:d.allDay},e.allDay&&T(h)&&(e.allDay=!1,g.normalizeEventTimes(e)),e[a].add(h),e.start.isBefore(e.end)||(f=this.minResizeDuration||(d.allDay?g.defaultAllDayEventDuration:g.defaultTimedEventDuration),"start"==a?e.start=e.end.clone().subtract(f):e.end=e.start.clone().add(f)),e},renderEventResize:function(a,b){},unrenderEventResize:function(){},getEventTimeText:function(a,b,c){return null==b&&(b=this.eventTimeFormat),null==c&&(c=this.displayEventEnd),this.displayEventTime&&a.start.hasTime()?c&&a.end?this.view.formatRange(a,b):a.start.format(b):""},getSegClasses:function(a,b,c){var d=this.view,e=a.event,f=["fc-event",a.isStart?"fc-start":"fc-not-start",a.isEnd?"fc-end":"fc-not-end"].concat(e.className,e.source?e.source.className:[]);return b&&f.push("fc-draggable"),c&&f.push("fc-resizable"),d.isEventSelected(e)&&f.push("fc-selected"),f},getSegSkinCss:function(a){var b=a.event,c=this.view,d=b.source||{},e=b.color,f=d.color,g=c.opt("eventColor");return{"background-color":b.backgroundColor||e||d.backgroundColor||f||c.opt("eventBackgroundColor")||g,"border-color":b.borderColor||e||d.borderColor||f||c.opt("eventBorderColor")||g,color:b.textColor||d.textColor||c.opt("eventTextColor")}},eventToSegs:function(a){return this.eventsToSegs([a])},eventToSpan:function(a){return this.eventToSpans(a)[0]},eventToSpans:function(a){var b=this.eventToRange(a);return this.eventRangeToSpans(b,a)},eventsToSegs:function(b,c){var d=this,e=Fa(b),f=[];return a.each(e,function(a,b){var e,g=[];for(e=0;eh&&g.push({start:h,end:c.start}),h=c.end;return f>h&&g.push({start:h,end:f}),g},sortEventSegs:function(a){a.sort(ia(this,"compareEventSegs"))},compareEventSegs:function(a,b){return a.eventStartMS-b.eventStartMS||b.eventDurationMS-a.eventDurationMS||b.event.allDay-a.event.allDay||H(a.event,b.event,this.view.eventOrderSpecs)}}),Va.isBgEvent=Ca,Va.dataAttrPrefix="";var tb=Va.DayTableMixin={breakOnWeeks:!1,dayDates:null,dayIndices:null,daysPerRow:null,rowCnt:null,colCnt:null,colHeadFormat:null,updateDayTable:function(){for(var a,b,c,d=this.view,e=this.start.clone(),f=-1,g=[],h=[];e.isBefore(this.end);)d.isHiddenDay(e)?g.push(f+.5):(f++,g.push(f),h.push(e.clone())),e.add(1,"days");if(this.breakOnWeeks){for(b=h[0].day(),a=1;ac?b[0]-1:c>=b.length?b[b.length-1]+1:b[c]},computeColHeadFormat:function(){return this.rowCnt>1||this.colCnt>10?"ddd":this.colCnt>1?this.view.opt("dayOfMonthFormat"):"dddd"},sliceRangeByRow:function(a){var b,c,d,e,f,g=this.daysPerRow,h=this.view.computeDayRange(a),i=this.getDateDayIndex(h.start),j=this.getDateDayIndex(h.end.clone().subtract(1,"days")),k=[];for(b=0;b=e&&k.push({row:b,firstRowDayIndex:e-c,lastRowDayIndex:f-c,isStart:e===i,isEnd:f===j});return k},sliceRangeByDay:function(a){var b,c,d,e,f,g,h=this.daysPerRow,i=this.view.computeDayRange(a),j=this.getDateDayIndex(i.start),k=this.getDateDayIndex(i.end.clone().subtract(1,"days")),l=[];for(b=0;b=e;e++)f=Math.max(j,e),g=Math.min(k,e),f=Math.ceil(f),g=Math.floor(g),g>=f&&l.push({row:b,firstRowDayIndex:f-c,lastRowDayIndex:g-c,isStart:f===j,isEnd:g===k});return l},renderHeadHtml:function(){var a=this.view;return'"},renderHeadIntroHtml:function(){return this.renderIntroHtml()},renderHeadTrHtml:function(){return""+(this.isRTL?"":this.renderHeadIntroHtml())+this.renderHeadDateCellsHtml()+(this.isRTL?this.renderHeadIntroHtml():"")+" "},renderHeadDateCellsHtml:function(){var a,b,c=[];for(a=0;a
",link=function(scope){var init=function(){scope.constDays=constDays,scope.weekStartsIndex=scope.weekStartsIndex||1,initDays()},initDays=function(){scope.ngModel=scope.ngModel||angular.copy(scope.constDays)};scope.onDayClicked=function(dayIndex){initDays(),scope.ngDisabled||(scope.ngModel[dayIndex].isSelected=!scope.ngModel[dayIndex].isSelected,scope.ngChange&&scope.ngChange({newValue:{index:dayIndex,item:scope.ngModel[dayIndex]}}))},init()};return{restrict:"AE",scope:{ngModel:"=?",ngChange:"&",weekStartsIndex:"=",ngDisabled:"=?"},link:link,template:template}}),angular.module("bahmni.appointments").directive("serviceAvailability",["appService","confirmBox",function(appService,confirmBox){var states={NEW:0,EDIT:1,READONLY:2},constDays=[{dayOfWeek:"SUNDAY",isSelected:!1},{dayOfWeek:"MONDAY",isSelected:!1},{dayOfWeek:"TUESDAY",isSelected:!1},{dayOfWeek:"WEDNESDAY",isSelected:!1},{dayOfWeek:"THURSDAY",isSelected:!1},{dayOfWeek:"FRIDAY",isSelected:!1},{dayOfWeek:"SATURDAY",isSelected:!1}],link=function(scope){var init=function(){scope.availability=scope.availability||{},scope.startOfWeek=appService.getAppDescriptor().getConfigValue("startOfWeek")||2};scope.add=function(){addOrUpdateToIndex(scope.availabilityList.length)&&(scope.availability={days:angular.copy(constDays)})},scope.clearValueIfInvalid=function(){scope.availability.maxAppointmentsLimit<0&&(scope.availability.maxAppointmentsLimit="")},scope.update=function(){var index=scope.availabilityList.indexOf(scope.backUpAvailability);addOrUpdateToIndex(index)&&(scope.state=states.READONLY)};var addOrUpdateToIndex=function(index){return scope.doesOverlap=overlapsWithExisting(index),scope.doesOverlap||(scope.availabilityList[index]=scope.availability),!scope.doesOverlap};scope.isValid=function(){var startTime=scope.availability.startTime,endTime=scope.availability.endTime;return startTime&&endTime&&startTime0&&($scope.weeklyAvailabilityOnSelectedDate=getWeeklyAvailabilityOnADate(date,$scope.selectedService.weeklyAvailability),$scope.weeklyAvailabilityOnSelectedDate&&0===$scope.weeklyAvailabilityOnSelectedDate.length&&($scope.allowedStartTime=void 0,$scope.allowedEndTime=void 0))},isServiceAvailableOnWeekDate=function(dayOfWeek,weeklyAvailability){return _.find(weeklyAvailability,function(wA){return wA.dayOfWeek===dayOfWeek})};$scope.checkAvailability=function(){if($scope.warning.appointmentDate=!1,!$scope.isPastAppointment&&$scope.selectedService&&$scope.appointment.date){setServiceAvailableTimesForADate($scope.appointment.date);var allSlots,dayOfWeek=moment($scope.appointment.date).format("dddd").toUpperCase();_.isEmpty($scope.selectedService.weeklyAvailability)?allSlots=getAllSlots($scope.selectedService.startTime,$scope.selectedService.endTime,$scope.minDuration):(allSlots=getSlotsForWeeklyAvailability(dayOfWeek,$scope.selectedService.weeklyAvailability,$scope.minDuration),$scope.warning.appointmentDate=!isServiceAvailableOnWeekDate(dayOfWeek,$scope.selectedService.weeklyAvailability)),$scope.startTimes=allSlots.startTime,$scope.endTimes=allSlots.endTime,$scope.warning.endTime=!isAppointmentTimeWithinServiceAvailability($scope.appointment.endTime),$scope.warning.startTime=!isAppointmentTimeWithinServiceAvailability($scope.appointment.startTime),$scope.warning.outOfRange=isSelectedSlotOutOfRange(),triggerSlotCalculation()}};var setServiceDetails=function(service){return appointmentsServiceService.getService(service.uuid).then(function(response){$scope.selectedService=response.data,$scope.appointment.location=_.find(appointmentCreateConfig.locations,{uuid:$scope.selectedService.location.uuid}),$scope.minDuration=response.data.durationMins||Bahmni.Appointments.Constants.minDurationForAppointment})};$scope.continueWithoutSaving=function(){$scope.showConfirmationPopUp=!1,$state.go($scope.toStateConfig.toState,$scope.toStateConfig.toParams,{reload:!0}),ngDialog.close()},$scope.continueWithSaving=function(){saveAppointment($scope.validatedAppointment),ngDialog.close()},$scope.cancelTransition=function(){$scope.showConfirmationPopUp=!0,ngDialog.close()},$scope.displayConfirmationDialog=function(){ngDialog.openConfirm({template:"views/admin/appointmentServiceNavigationConfirmation.html",scope:$scope,closeByEscape:!0})},$scope.displayConflictConfirmationDialog=function(){ngDialog.openConfirm({template:"views/manage/appointmentConflictConfirmation.html",scope:$scope,closeByEscape:!0})},$scope.$on("$destroy",function(){cleanUpListenerStateChangeStart()});var getSlotsForWeeklyAvailability=function(dayOfWeek,weeklyAvailability,durationInMin){var slots={startTime:[],endTime:[]},dayAvailability=_.filter(weeklyAvailability,function(o){return o.dayOfWeek===dayOfWeek});return dayAvailability=_.sortBy(dayAvailability,"startTime"),
_.each(dayAvailability,function(day){var allSlots=getAllSlots(day.startTime,day.endTime,durationInMin);slots.startTime=_.concat(slots.startTime,allSlots.startTime),slots.endTime=_.concat(slots.endTime,allSlots.endTime)}),slots},getAllSlots=function(startTimeString,endTimeString,durationInMin){startTimeString=_.isEmpty(startTimeString)?"00:00":startTimeString,endTimeString=_.isEmpty(endTimeString)?"23:59":endTimeString;for(var startTime=getFormattedTime(startTimeString),endTime=getFormattedTime(endTimeString),result=[],slots={startTime:[],endTime:[]},current=moment(startTime);current.valueOf()<=endTime.valueOf();)result.push(current.format("hh:mm a")),current.add(durationInMin,"minutes");return slots.startTime=_.slice(result,0,result.length-1),slots.endTime=_.slice(result,1),slots},getFormattedTime=function(time){return moment(time,"hh:mm a")},isFormFilled=function(){return!_.every(_.values($scope.appointment),function(value){return!value})},cleanUpListenerStateChangeStart=$scope.$on("$stateChangeStart",function(event,toState,toParams,fromState,fromParams){isFormFilled()&&$scope.showConfirmationPopUp&&(event.preventDefault(),ngDialog.close(),$scope.toStateConfig={toState:toState,toParams:toParams},$scope.displayConfirmationDialog())}),newAppointmentStartingEndingBeforeExistingAppointment=function(existingStart,newStart,newEnd){return newEnd<=existingStart},newAppointmentStartingEndingAfterExistingAppointment=function(newStart,existingStart,existingEnd){return newStart>=existingEnd},isNewAppointmentConflictingWithExistingAppointment=function(existingAppointment,newAppointment){var existingStart=moment(existingAppointment.startDateTime),existingEnd=moment(existingAppointment.endDateTime),newStart=moment(newAppointment.startDateTime),newEnd=moment(newAppointment.endDateTime);return!(newAppointmentStartingEndingBeforeExistingAppointment(existingStart,newStart,newEnd)||newAppointmentStartingEndingAfterExistingAppointment(newStart,existingStart,existingEnd))},checkForConflict=function(existingAppointment,newAppointment){var isOnSameDay=0===moment(existingAppointment.startDateTime).diff(moment(newAppointment.startDateTime),"days"),isAppointmentTimingConflicted=isNewAppointmentConflictingWithExistingAppointment(existingAppointment,newAppointment);return existingAppointment.uuid!==newAppointment.uuid&&"Cancelled"!==existingAppointment.status&&isOnSameDay&&isAppointmentTimingConflicted},getConflictingAppointments=function(appointment){return _.filter($scope.patientAppointments,function(bookedAppointment){return checkForConflict(bookedAppointment,appointment)})},saveAppointment=function(appointment){return spinner.forPromise(appointmentsService.save(appointment).then(function(){messagingService.showMessage("info","APPOINTMENT_SAVE_SUCCESS"),$scope.showConfirmationPopUp=!1;var params=$state.params;params.viewDate=moment($scope.appointment.date).startOf("day").toDate(),params.isFilterOpen=!0,params.isSearchEnabled=params.isSearchEnabled&&$scope.isEditMode(),$state.go("^",params,{reload:!0})}))},wireAutocompleteEvents=function(){$("#endTimeID").bind("focus",function(){$("#endTimeID").autocomplete("search")});var $startTimeID=$("#startTimeID");$startTimeID.bind("focus",function(){$("#startTimeID").autocomplete("search")}),$startTimeID.bind("focusout",function(){$scope.onSelectStartTime()})};return $scope.isEditMode=function(){return $scope.appointment.uuid},$scope.isEditAllowed=function(){return!$scope.isPastAppointment&&("Scheduled"===$scope.appointment.status||"CheckedIn"===$scope.appointment.status)},$scope.navigateToPreviousState=function(){$state.go("^",$state.params,{reload:!0})},init()}]),angular.module("bahmni.appointments").controller("AppointmentServiceController",["$scope","$q","spinner","$state","appointmentsServiceService","locationService","messagingService","specialityService","ngDialog","appService","appointmentServiceContext","confirmBox",function($scope,$q,spinner,$state,appointmentsServiceService,locationService,messagingService,specialityService,ngDialog,appService,appointmentServiceContext,confirmBox){$scope.showConfirmationPopUp=!0,$scope.enableSpecialities=appService.getAppDescriptor().getConfigValue("enableSpecialities"),$scope.enableServiceTypes=appService.getAppDescriptor().getConfigValue("enableServiceTypes"),$scope.enableCalendarView=appService.getAppDescriptor().getConfigValue("enableCalendarView"),$scope.colorsForAppointmentService=appService.getAppDescriptor().getConfigValue("colorsForAppointmentService");var serviceDetails=appointmentServiceContext?appointmentServiceContext.service:{};$scope.service=Bahmni.Appointments.AppointmentServiceViewModel.createFromResponse(serviceDetails),$scope.service.color=$scope.service.color||$scope.colorsForAppointmentService&&$scope.colorsForAppointmentService[0]||"#008000";var save=function(){if(clearValuesIfDisabledAndInvalid(),$scope.createServiceForm.$invalid)return void messagingService.showMessage("error","INVALID_SERVICE_FORM_ERROR_MESSAGE");var service=Bahmni.Appointments.AppointmentService.createFromUIObject($scope.service);appointmentsServiceService.save(service).then(function(){messagingService.showMessage("info","APPOINTMENT_SERVICE_SAVE_SUCCESS"),$scope.showConfirmationPopUp=!1,$state.go("home.admin.service")}),ngDialog.close()},clearValuesIfDisabledAndInvalid=function(){var form=$scope.createServiceForm;form.serviceTime.$invalid&&$scope.hasWeeklyAvailability()&&(delete $scope.service.startTime,delete $scope.service.endTime,form.serviceTime.$setValidity("timeSequence",!0)),form.serviceMaxLoad.$invalid&&($scope.hasWeeklyAvailability()||$scope.hasServiceTypes())&&(delete $scope.service.maxAppointmentsLimit,form.serviceMaxLoad.$setValidity("min",!0)),form.serviceMaxLoad.$invalid&&$scope.hasServiceTypes()&&(delete $scope.service.maxAppointmentsLimit,form.serviceMaxLoad.$setValidity("min",!0))};$scope.hasWeeklyAvailability=function(){return $scope.service.weeklyAvailability.length>0},$scope.hasServiceTypes=function(){return $scope.service.serviceTypes.length>0};var isNew=function(){return!$scope.service.uuid};$scope.confirmSave=function(){if(isNew())return void save();var childScope={};childScope.message="CONFIRM_EDIT_SERVICE_MESSAGE_KEY",childScope.cancel=cancelSave,childScope.ok=save,confirmBox({scope:childScope,actions:[{name:"cancel",display:"CANCEL_KEY"},{name:"ok",display:"OK_KEY"}],className:"ngdialog-theme-default delete-program-popup"})};var cancelSave=function(closeDialog){closeDialog()};$scope.validateServiceName=function(){$scope.createServiceForm.name.$setValidity("uniqueServiceName",isServiceNameUnique($scope.service))};var isServiceNameUnique=function(service){return!service.name||!$scope.services.some(function(existingService){var isConflictingName=existingService.name.toLowerCase()===service.name.toLowerCase();return service.uuid?isConflictingName&&service.uuid!==existingService.uuid:isConflictingName})},initAppointmentLocations=function(){return locationService.getAllByTag("Appointment Location").then(function(response){$scope.locations=response.data.results})},initSpecialities=function(){return specialityService.getAllSpecialities().then(function(response){$scope.specialities=response.data})},initServices=function(){return appointmentsServiceService.getAllServices().then(function(response){$scope.services=response.data})},init=function(){var promises=[];return promises.push(initAppointmentLocations()),promises.push(initServices()),$scope.enableSpecialities&&promises.push(initSpecialities()),spinner.forPromise($q.all(promises))};$scope.continueWithoutSaving=function(){$scope.showConfirmationPopUp=!1,$state.go($scope.toStateConfig.toState,$scope.toStateConfig.toParams),ngDialog.close()},$scope.cancelTransition=function(){$scope.showConfirmationPopUp=!0,ngDialog.close()},$scope.displayConfirmationDialog=function(){ngDialog.openConfirm({template:"views/admin/appointmentServiceNavigationConfirmation.html",scope:$scope,closeByEscape:!0})};var cleanUpListenerStateChangeStart=$scope.$on("$stateChangeStart",function(event,toState,toParams){$scope.showConfirmationPopUp&&(event.preventDefault(),ngDialog.close(),$scope.toStateConfig={toState:toState,toParams:toParams},$scope.displayConfirmationDialog())});return $scope.$on("$destroy",function(){cleanUpListenerStateChangeStart()}),init()}]),angular.module("bahmni.appointments").controller("AppointmentsDayCalendarController",["$scope","$rootScope","$state","uiCalendarConfig","appService","calendarViewPopUp","checkinPopUp",function($scope,$rootScope,$state,uiCalendarConfig,appService,calendarViewPopUp,checkinPopUp){$scope.eventSources=[];var init=function(){$scope.events=$scope.appointments.events,$scope.alertOnEventClick=function(event,jsEvent,view){var checkinAppointment=function(patient,patientAppointment){checkinPopUp({scope:{patientAppointment:patientAppointment},className:"ngdialog-theme-default app-dialog-container"})};calendarViewPopUp({scope:{appointments:event.appointments,checkinAppointment:checkinAppointment,enableCreateAppointment:isSelectable()},className:"ngdialog-theme-default delete-program-popup app-dialog-container"})},$scope.alertOnDrop=function(event,delta,revertFunc,jsEvent,ui,view){$scope.alertMessage="Event Dropped to make dayDelta "+delta},$scope.alertOnResize=function(event,delta,revertFunc,jsEvent,ui,view){$scope.alertMessage="Event Resized to make dayDelta "+delta},$scope.addRemoveEventSource=function(sources,source){var canAdd=0;angular.forEach(sources,function(value,key){sources[key]===source&&(sources.splice(key,1),canAdd=1)}),0===canAdd&&sources.push(source)},$scope.remove=function(index){$scope.events.splice(index,1)},$scope.changeView=function(view,calendar){uiCalendarConfig.calendars[calendar].fullCalendar("changeView",view)};var isUserPrivilegedToCreateAppointment=function(){return _.find($rootScope.currentUser.privileges,function(privilege){return privilege.name===Bahmni.Appointments.Constants.privilegeManageAppointments})};$scope.createAppointment=function(start,end,jsEvent,view,resource){if(isUserPrivilegedToCreateAppointment()){var params=$state.params;params.appointment={startDateTime:start,endDateTime:end,appointmentKind:"Scheduled",provider:resource&&resource.provider},$state.go("home.manage.appointments.calendar.new",params,{reload:!1})}};var isSelectable=function(){return!Bahmni.Common.Util.DateUtil.isBeforeDate($scope.date,moment().startOf("day"))};$scope.uiConfig={calendar:{height:document.getElementsByClassName("app-calendar-container")[0].clientHeight,editable:!1,defaultDate:$scope.date,header:!1,timezone:"local",defaultView:"agendaDay",resources:$scope.appointments.resources,businessHours:{start:appService.getAppDescriptor().getConfigValue("startOfDay")||Bahmni.Appointments.Constants.defaultCalendarStartTime,end:appService.getAppDescriptor().getConfigValue("endOfDay")||Bahmni.Appointments.Constants.defaultCalendarEndTime},scrollTime:appService.getAppDescriptor().getConfigValue("startOfDay")||Bahmni.Appointments.Constants.defaultCalendarStartTime,groupByResource:!0,selectable:isSelectable(),select:$scope.createAppointment,slotLabelInterval:appService.getAppDescriptor().getConfigValue("calendarSlotLabelInterval")||Bahmni.Appointments.Constants.defaultCalendarSlotLabelInterval,slotDuration:appService.getAppDescriptor().getConfigValue("calendarSlotDuration")||Bahmni.Appointments.Constants.defaultCalendarSlotDuration,eventLimit:!0,allDaySlot:!1,allDayDefault:!1,eventClick:$scope.alertOnEventClick,eventDrop:$scope.alertOnDrop,eventResize:$scope.alertOnResize,eventRender:$scope.eventRender,schedulerLicenseKey:"GPL-My-Project-Is-Open-Source"}},$scope.eventSources=[$scope.events]},resetEvents=function(){_.isEmpty($scope.eventSources)||$scope.eventSources.splice(0,$scope.eventSources.length),_.isEmpty($scope.appointments.events)||$scope.eventSources.push($scope.appointments.events),$scope.uiConfig.calendar.resources=$scope.appointments.resources};$scope.$watch("appointments",function(newValue,oldValue){newValue!==oldValue&&resetEvents()}),init()}]),angular.module("bahmni.appointments").controller("AllAppointmentsController",["$scope","$state","appService","$rootScope",function($scope,$state,appService,$rootScope){$scope.enableCalendarView=appService.getAppDescriptor().getConfigValue("enableCalendarView"),$scope.isSearchEnabled=!1,$scope.manageAppointmentPrivilege=Bahmni.Appointments.Constants.privilegeManageAppointments,$scope.navigateTo=function(viewName){$scope.currentTab=viewName;var path="home.manage.appointments."+viewName;$state.params.appointmentsData=$rootScope.appointmentsData,$state.go(path,$state.params,{reload:!1})},$scope.getCurrentAppointmentTabName=function(){return $state.current.tabName},$scope.$watch(function(){return $state.params.isSearchEnabled},function(isSearchEnabled){$scope.isSearchEnabled=isSearchEnabled},!0)}]),angular.module("bahmni.appointments").controller("AppointmentsCalendarViewController",["$scope","$state","$translate","spinner","appointmentsService","appointmentsFilter","$rootScope",function($scope,$state,$translate,spinner,appointmentsService,appointmentsFilter,$rootScope){var init=function(){$scope.startDate=$state.params.viewDate||moment().startOf("day").toDate(),$scope.$on("filterClosedOpen",function(event,args){$scope.isFilterOpen=args.filterViewStatus}),$scope.isFilterOpen=$state.params.isFilterOpen},parseAppointments=function(allAppointments){if(allAppointments){var appointments=allAppointments.filter(function(appointment){return"Cancelled"!==appointment.status}),resources=_.chain(appointments).filter(function(appointment){return!_.isEmpty(appointment.provider)}).map(function(appointment){return appointment.provider}).uniqBy("name").map(function(provider){return{id:provider.name,title:provider.name,provider:provider}}).sortBy(function(provider){return provider.id&&provider.id.toLowerCase()}).value(),hasAppointmentsWithNoProvidersSpecified=_.find(appointments,function(appointment){return _.isEmpty(appointment.provider)});hasAppointmentsWithNoProvidersSpecified&&resources.push({id:$translate.instant("NO_PROVIDER_COLUMN_KEY"),title:$translate.instant("NO_PROVIDER_COLUMN_KEY"),provider:{name:$translate.instant("NO_PROVIDER_COLUMN_KEY"),display:$translate.instant("NO_PROVIDER_COLUMN_KEY"),uuid:"no-provider-uuid"}});var events=[];appointments.reduce(function(result,appointment){var event={};event.resourceId=appointment.provider?appointment.provider.name:$translate.instant("NO_PROVIDER_COLUMN_KEY"),event.start=appointment.startDateTime,event.end=appointment.endDateTime,event.color=appointment.service.color,event.serviceName=appointment.service.name;var existingEvent=_.find(result,event),patientName=appointment.patient.name+" ("+appointment.patient.identifier+")",isBedAssigned=appointment.additionalInfo&&appointment.additionalInfo.BED_NUMBER_KEY;return existingEvent?(existingEvent.title=[existingEvent.title,patientName].join(", "),existingEvent.className="appointmentIcons multiplePatients"+(isBedAssigned?" bed-accom":""),existingEvent.appointments.push(appointment)):(event.title=patientName,event.className="appointmentIcons "+appointment.status+(isBedAssigned?" bed-accom":""),event.appointments=[],event.appointments.push(appointment),result.push(event)),result},events),$scope.providerAppointments={resources:resources,events:events},$scope.shouldReload=!0}};return $scope.$watch(function(){return $state.params.filterParams},function(newValue,oldValue){if(newValue!==oldValue){var filteredAppointments=appointmentsFilter($scope.allAppointmentsForDay||$state.params.appointmentsData,$state.params.filterParams);filteredAppointments&&parseAppointments(filteredAppointments)}},!0),$scope.getAppointmentsForDate=function(viewDate){$state.params.viewDate=viewDate,$scope.shouldReload=!1;var params={forDate:viewDate};if($scope.$on("$stateChangeStart",function(event,toState,toParams){"list"==toState.tabName&&(toParams.doFetchAppointmentsData=!1)}),$state.params.doFetchAppointmentsData)return spinner.forPromise(appointmentsService.getAllAppointments(params).then(function(response){$scope.allAppointmentsForDay=response.data;var filteredAppointments=appointmentsFilter($scope.allAppointmentsForDay,$state.params.filterParams);return $rootScope.appointmentsData=filteredAppointments,parseAppointments(filteredAppointments)}));var filteredAppointments=appointmentsFilter($state.params.appointmentsData,$state.params.filterParams);return $state.params.doFetchAppointmentsData=!0,parseAppointments(filteredAppointments)},$scope.hasNoAppointments=function(){return _.isEmpty($scope.providerAppointments)||_.isEmpty($scope.providerAppointments.events)},init()}]),angular.module("bahmni.appointments").controller("AppointmentsListViewController",["$scope","$state","$rootScope","$translate","$stateParams","spinner","appointmentsService","appService","appointmentsFilter","printer","checkinPopUp","confirmBox","ngDialog","messagingService",function($scope,$state,$rootScope,$translate,$stateParams,spinner,appointmentsService,appService,appointmentsFilter,printer,checkinPopUp,confirmBox,ngDialog,messagingService){$scope.enableSpecialities=appService.getAppDescriptor().getConfigValue("enableSpecialities"),$scope.enableServiceTypes=appService.getAppDescriptor().getConfigValue("enableServiceTypes"),$scope.allowedActions=appService.getAppDescriptor().getConfigValue("allowedActions")||[],$scope.allowedActionsByStatus=appService.getAppDescriptor().getConfigValue("allowedActionsByStatus")||{},$scope.colorsForListView=appService.getAppDescriptor().getConfigValue("colorsForListView")||{},$scope.manageAppointmentPrivilege=Bahmni.Appointments.Constants.privilegeManageAppointments,$scope.searchedPatient=!1;var oldPatientData=[];$scope.$on("filterClosedOpen",function(event,args){$scope.isFilterOpen=args.filterViewStatus}),$scope.tableInfo=[{heading:"APPOINTMENT_PATIENT_ID",sortInfo:"patient.identifier",enable:!0},{heading:"APPOINTMENT_PATIENT_NAME",sortInfo:"patient.name","class":!0,enable:!0},{heading:"APPOINTMENT_DATE",sortInfo:"date",enable:!0},{heading:"APPOINTMENT_START_TIME_KEY",sortInfo:"startDateTime",enable:!0},{heading:"APPOINTMENT_END_TIME_KEY",sortInfo:"endDateTime",enable:!0},{heading:"APPOINTMENT_PROVIDER",sortInfo:"provider.name","class":!0,enable:!0},{heading:"APPOINTMENT_SERVICE_SPECIALITY_KEY",sortInfo:"service.speciality.name",enable:$scope.enableSpecialities},{heading:"APPOINTMENT_SERVICE",sortInfo:"service.name","class":!0,enable:!0},{heading:"APPOINTMENT_SERVICE_TYPE_FULL",sortInfo:"serviceType.name","class":!0,enable:$scope.enableServiceTypes},{heading:"APPOINTMENT_STATUS",sortInfo:"status",enable:!0},{heading:"APPOINTMENT_WALK_IN",sortInfo:"appointmentKind",enable:!0},{heading:"APPOINTMENT_SERVICE_LOCATION_KEY",sortInfo:"location.name","class":!0,enable:!0},{heading:"APPOINTMENT_ADDITIONAL_INFO",sortInfo:"additionalInfo","class":!0,enable:!0},{heading:"APPOINTMENT_CREATE_NOTES",sortInfo:"comments",enable:!0}];var init=function(){$scope.searchedPatient=$stateParams.isSearchEnabled&&$stateParams.patient,$scope.startDate=$stateParams.viewDate||moment().startOf("day").toDate(),$scope.isFilterOpen=$stateParams.isFilterOpen};$scope.getAppointmentsForDate=function(viewDate){$stateParams.viewDate=viewDate,$scope.selectedAppointment=void 0;var params={forDate:viewDate};$scope.$on("$stateChangeStart",function(event,toState,toParams){"calendar"==toState.tabName&&(toParams.doFetchAppointmentsData=!1)}),$state.params.doFetchAppointmentsData?spinner.forPromise(appointmentsService.getAllAppointments(params).then(function(response){$scope.appointments=response.data,$scope.filteredAppointments=appointmentsFilter($scope.appointments,$stateParams.filterParams),$rootScope.appointmentsData=$scope.filteredAppointments})):($scope.filteredAppointments=appointmentsFilter($state.params.appointmentsData,$stateParams.filterParams),$state.params.doFetchAppointmentsData=!0)},$scope.displaySearchedPatient=function(appointments){oldPatientData=$scope.filteredAppointments,$scope.filteredAppointments=appointments.map(function(appointmet){return appointmet.date=appointmet.startDateTime,appointmet}),$scope.searchedPatient=!0,$stateParams.isFilterOpen=!1,$scope.isFilterOpen=!1,$stateParams.isSearchEnabled=!0},$scope.hasNoAppointments=function(){return _.isEmpty($scope.filteredAppointments)},$scope.goBackToPreviousView=function(){$scope.searchedPatient=!1,$scope.filteredAppointments=oldPatientData,$stateParams.isFilterOpen=!0,$scope.isFilterOpen=!0,$stateParams.isSearchEnabled=!1},$scope.isSelected=function(appointment){return $scope.selectedAppointment===appointment},$scope.select=function(appointment){return $scope.isSelected(appointment)?void($scope.selectedAppointment=void 0):void($scope.selectedAppointment=appointment)},$scope.isWalkIn=function(appointmentType){return"WalkIn"===appointmentType?"Yes":"No"},$scope.editAppointment=function(){var params=$stateParams;params.uuid=$scope.selectedAppointment.uuid,$state.go("home.manage.appointments.list.edit",params)},$scope.checkinAppointment=function(){var scope=$rootScope.$new();scope.message=$translate.instant("APPOINTMENT_STATUS_CHANGE_CONFIRM_MESSAGE",{toStatus:"CheckedIn"}),scope.action=_.partial(changeStatus,"CheckedIn",_),checkinPopUp({scope:scope,className:"ngdialog-theme-default app-dialog-container"})},$scope.$watch(function(){return $stateParams.filterParams},function(newValue,oldValue){newValue!==oldValue&&($scope.filteredAppointments=appointmentsFilter($scope.appointments||$state.params.appointmentsData,$stateParams.filterParams))},!0),$scope.sortAppointmentsBy=function(sortColumn){"additionalInfo"===sortColumn&&($scope.filteredAppointments=$scope.filteredAppointments.map(function(appointment){return appointment.additionalInformation=$scope.display(_.get(appointment,sortColumn)),appointment}),sortColumn="additionalInformation");var emptyObjects=_.filter($scope.filteredAppointments,function(appointment){return!_.property(sortColumn)(appointment)}),nonEmptyObjects=_.difference($scope.filteredAppointments,emptyObjects),sortedNonEmptyObjects=_.sortBy(nonEmptyObjects,function(appointment){return angular.isNumber(_.get(appointment,sortColumn))?_.get(appointment,sortColumn):_.get(appointment,sortColumn).toLowerCase()});$scope.reverseSort&&sortedNonEmptyObjects.reverse(),$scope.filteredAppointments=sortedNonEmptyObjects.concat(emptyObjects),$scope.sortColumn=sortColumn,$scope.reverseSort=!$scope.reverseSort},$scope.printPage=function(){var printTemplateUrl=appService.getAppDescriptor().getConfigValue("printListViewTemplateUrl")||"views/manage/list/listView.html";printer.print(printTemplateUrl,{searchedPatient:$scope.searchedPatient,filteredAppointments:$scope.filteredAppointments,startDate:$stateParams.viewDate,enableServiceTypes:$scope.enableServiceTypes,enableSpecialities:$scope.enableSpecialities})},$scope.undoCheckIn=function(){var undoCheckIn=function(closeConfirmBox){return appointmentsService.undoCheckIn($scope.selectedAppointment.uuid).then(function(response){ngDialog.close(),$scope.selectedAppointment.status=response.data.status;var message=$translate.instant("APPOINTMENT_STATUS_CHANGE_SUCCESS_MESSAGE",{toStatus:response.data.status});closeConfirmBox(),messagingService.showMessage("info",message)})},scope={};scope.message=$translate.instant("APPOINTMENT_UNDO_CHECKIN_CONFIRM_MESSAGE"),scope.yes=undoCheckIn,showPopUp(scope)};var changeStatus=function(toStatus,onDate,closeConfirmBox){var message=$translate.instant("APPOINTMENT_STATUS_CHANGE_SUCCESS_MESSAGE",{toStatus:toStatus});return appointmentsService.changeStatus($scope.selectedAppointment.uuid,toStatus,onDate).then(function(response){ngDialog.close(),$scope.selectedAppointment.status=response.data.status,closeConfirmBox(),messagingService.showMessage("info",message)})};$scope.confirmAction=function(toStatus){var scope={};scope.message=$translate.instant("APPOINTMENT_STATUS_CHANGE_CONFIRM_MESSAGE",{toStatus:toStatus}),scope.yes=_.partial(changeStatus,toStatus,void 0,_),showPopUp(scope)},$scope.display=function(jsonObj){return jsonObj=_.mapKeys(jsonObj,function(value,key){return $translate.instant(key)}),JSON.stringify(jsonObj||"").replace(/[{\"}]/g,"").replace(/[,]/g,",\t")};var showPopUp=function(popUpScope){popUpScope.no=function(closeConfirmBox){closeConfirmBox()},confirmBox({scope:popUpScope,actions:[{name:"yes",display:"YES_KEY"},{name:"no",display:"NO_KEY"}],className:"ngdialog-theme-default"})};$scope.isAllowedAction=function(action){return _.includes($scope.allowedActions,action)},$scope.isValidAction=function(action){if(!$scope.selectedAppointment)return!1;var status=$scope.selectedAppointment.status,allowedActions=$scope.allowedActionsByStatus.hasOwnProperty(status)?$scope.allowedActionsByStatus[status]:[];return _.includes(allowedActions,action)},init()}]),angular.module("bahmni.appointments").controller("AppointmentsSummaryController",["$scope","$state","$window","spinner","appointmentsService","appService",function($scope,$state,$window,spinner,appointmentsService,appService){var init=function(){$scope.viewDate=$state.params.viewDate||moment().startOf("day").toDate(),$scope.weekStartDate=moment($scope.viewDate).startOf("week").toDate(),$scope.weekEndDate=moment($scope.viewDate).endOf("week").toDate(),$scope.weekStart=appService.getAppDescriptor().getConfigValue("weekStart"),$scope.getAppointmentsSummaryForAWeek($scope.weekStartDate,$scope.weekEndDate)};$scope.getAppointmentsSummaryForAWeek=function(startDate,endDate){$scope.weekStartDate=startDate,$scope.weekEndDate=endDate;var params={startDate:startDate,endDate:endDate};spinner.forPromise(appointmentsService.getAppointmentsSummary(params).then(function(response){$scope.appointments=response.data,setWeekDatesInfo()}))},$scope.goToListView=function(date,service){var params={viewDate:moment(date).toDate(),filterParams:{statusList:_.without(Bahmni.Appointments.Constants.appointmentStatusList,"Cancelled")}};_.isUndefined(service)||(params.filterParams.serviceUuids=[service.uuid]),$state.go("home.manage.appointments.list",params)},$scope.isCurrentDate=function(date){return moment(date).format("YYYY-MM-DD")===moment().format("YYYY-MM-DD")};var setWeekDatesInfo=function(){$scope.weekDatesInfo=[];for(var i=$scope.weekStartDate;Bahmni.Common.Util.DateUtil.isBeforeDate(i,$scope.weekEndDate);i=Bahmni.Common.Util.DateUtil.addDays(i,1)){var weekDate={date:moment(i).format("YYYY-MM-DD")};weekDate.total=_.reduce($scope.appointments,function(total,appointment){var appointmentCount=appointment.appointmentCountMap[weekDate.date];return appointmentCount?{all:appointmentCount.allAppointmentsCount+total.all,missed:appointmentCount.missedAppointmentsCount+total.missed}:total},{all:0,missed:0}),$scope.weekDatesInfo.push(weekDate)}};return init()}]),angular.module("bahmni.appointments").controller("AppointmentsFilterController",["$scope","$state","$rootScope","$q","$translate","appointmentsServiceService","spinner","ivhTreeviewMgr","providerService","appService",function($scope,$state,$rootScope,$q,$translate,appointmentsServiceService,spinner,ivhTreeviewMgr,providerService,appService){var init=function(){$scope.isSpecialityEnabled=appService.getAppDescriptor().getConfigValue("enableSpecialities"),$scope.isServiceTypeEnabled=appService.getAppDescriptor().getConfigValue("enableServiceTypes"),$scope.isFilterOpen=$state.params.isFilterOpen,$scope.isSearchEnabled=$state.params.isSearchEnabled,$scope.statusList=_.map(Bahmni.Appointments.Constants.appointmentStatusList,function(status){return{name:status,value:status}}),$scope.selectedStatusList=_.filter($scope.statusList,function(status){return _.includes($state.params.filterParams.statusList,status.value)}),"calendar"===$state.current.tabName&&($scope.statusList=_.filter($scope.statusList,function(status){return"Cancelled"!==status.name}));var params={v:"custom:(display,person,uuid,retired,attributes:(attributeType:(display),value,voided))"};spinner.forPromise($q.all([appointmentsServiceService.getAllServicesWithServiceTypes(),providerService.list(params)]).then(function(response){$scope.providers=_.filter(response[1].data.results,function(provider){return _.find(provider.attributes,function(attribute){return!attribute.voided&&!provider.retired&&attribute.value&&attribute.attributeType.display===Bahmni.Appointments.Constants.availableForAppointments})}).map(function(provider){return provider.name=provider.person.display,provider}),$scope.providers.push({name:$translate.instant("NO_PROVIDER_COLUMN_KEY"),display:$translate.instant("NO_PROVIDER_COLUMN_KEY"),uuid:"no-provider-uuid"}),$scope.isSpecialityEnabled?($scope.specialities=_.groupBy(response[0].data,function(service){return service.speciality.name||$translate.instant("NO_SPECIALITY_KEY")}),$scope.selectedSpecialities=_.map($scope.specialities,function(speciality,key){return{label:key,id:speciality[0].speciality.uuid||"",children:_.map(speciality,function(service){return{label:service.name,id:service.uuid,color:service.color,children:$scope.isServiceTypeEnabled?_.map(service.serviceTypes,function(serviceType){return{label:serviceType.name+" ["+serviceType.duration+" "+$translate.instant("PLACEHOLDER_SERVICE_TYPE_DURATION_MIN")+"]",id:serviceType.uuid}}):[]}})}})):$scope.selectedSpecialities=_.map(response[0].data,function(service){return{label:service.name,id:service.uuid,color:service.color,children:$scope.isServiceTypeEnabled?_.map(service.serviceTypes,function(serviceType){return{label:serviceType.name+" ["+serviceType.duration+" "+$translate.instant("PLACEHOLDER_SERVICE_TYPE_DURATION_MIN")+"]",id:serviceType.uuid}}):[]}}),$scope.selectedProviders=_.filter($scope.providers,function(provider){return _.includes($state.params.filterParams.providerUuids,provider.uuid)}),_.isEmpty($state.params.filterParams)||ivhTreeviewMgr.selectEach($scope.selectedSpecialities,$state.params.filterParams.serviceUuids)}))};$scope.filterSelected=function(){$scope.filterSelectedValues=$scope.showSelected?{selected:!0}:void 0},$scope.expandFilter=function(){$state.params.isFilterOpen=!0,$scope.isFilterOpen=$state.params.isFilterOpen,$rootScope.$broadcast("filterClosedOpen",{filterViewStatus:$scope.isFilterOpen})},$scope.minimizeFilter=function(){$state.params.isFilterOpen=!1,$scope.isFilterOpen=$state.params.isFilterOpen,$rootScope.$broadcast("filterClosedOpen",{filterViewStatus:$scope.isFilterOpen})};var resetFilterParams=function(){$state.params.filterParams={serviceUuids:[],serviceTypeUuids:[],providerUuids:[],statusList:[]}};$scope.setSelectedSpecialities=function(selectedSpecialities){$scope.selectedSpecialities=selectedSpecialities},$scope.getCurrentAppointmentTabName=function(){return $state.current.tabName},$scope.resetFilter=function(){$scope.selectedSpecialities&&ivhTreeviewMgr.deselectAll($scope.selectedSpecialities,!1),$scope.selectedProviders=[],$scope.selectedStatusList=[],$scope.showSelected=!1,$scope.filterSelectedValues=void 0,$scope.searchText=void 0,resetFilterParams()},$scope.resetSearchText=function(){$scope.searchText=void 0},$scope.applyFilter=function(){resetFilterParams(),$scope.isSpecialityEnabled?($state.params.filterParams.serviceUuids=_.reduce($scope.selectedSpecialities,function(accumulator,speciality){var serviceUuids=_.chain(speciality.children).filter(function(service){return service.selected}).map(function(service){return service.id}).value();return serviceUuids.concat(accumulator)},[]),$scope.isServiceTypeEnabled?$state.params.filterParams.serviceTypeUuids=_.reduce($scope.selectedSpecialities,function(accumulator,speciality){var selectedServiceTypes=_.reduce(speciality.children,function(accumulator,service){var serviceTypesForService=[];return service.selected||(serviceTypesForService=_.filter(service.children,function(serviceType){return serviceType.selected}).map(function(serviceType){return serviceType.id})),serviceTypesForService.concat(accumulator)},[]);return selectedServiceTypes.concat(accumulator)},[]):$state.params.filterParams.serviceTypeUuids=[]):($state.params.filterParams.serviceUuids=_.chain($scope.selectedSpecialities).filter(function(service){
return service.selected}).map(function(service){return service.id}).value(),$scope.isServiceTypeEnabled?$state.params.filterParams.serviceTypeUuids=$scope.selectedSpecialities.filter(function(service){return!service.selected}).reduce(function(accumulator,service){return accumulator.concat(service.children)},[]).filter(function(serviceType){return serviceType.selected}).reduce(function(accumulator,serviceType){return accumulator.concat(serviceType.id)},[]):$state.params.filterParams.serviceTypeUuids=[]),$state.params.filterParams.providerUuids=_.map($scope.selectedProviders,function(provider){return provider.uuid}),$state.params.filterParams.statusList=_.map($scope.selectedStatusList,function(status){return status.value})},$scope.isFilterApplied=function(){return _.find($state.params.filterParams,function(filterParam){return!_.isEmpty(filterParam)})},$scope.$watch(function(){return $state.params.isFilterOpen},function(isFilterHidden){$scope.isFilterOpen=isFilterHidden,$scope.isSearchEnabled=isFilterHidden},!0),$scope.$watch(function(){return $state.params.isSearchEnabled},function(isSearchEnabled){$scope.isSearchEnabled=isSearchEnabled},!0),$scope.$watch(function(){return $state.current.tabName},function(newValue,oldValue){newValue!==oldValue&&("calendar"===newValue?($scope.statusList=_.filter($scope.statusList,function(status){return"Cancelled"!==status.name}),$scope.selectedStatusList=_.filter($scope.selectedStatusList,function(status){return"Cancelled"!==status.name})):$scope.statusList=_.map(Bahmni.Appointments.Constants.appointmentStatusList,function(status){return{name:status,value:status}}))},!0),init()}]),angular.module("bahmni.appointments").filter("appointments",[function(){var filterAppointmentsByService=function(appointments,serviceUuids){return _.filter(appointments,function(appointment){return appointment.service&&_.includes(serviceUuids,appointment.service.uuid)})},filterAppointmentsByServiceType=function(appointments,serviceTypeUuids){return _.filter(appointments,function(appointment){return appointment.serviceType&&_.includes(serviceTypeUuids,appointment.serviceType.uuid)})},filterAppointmentsByProviders=function(appointments,providerUuids){return _.isEmpty(providerUuids)?appointments:_.filter(appointments,function(appointment){return appointment.provider?appointment.provider&&_.includes(providerUuids,appointment.provider.uuid):_.includes(providerUuids,"no-provider-uuid")})},filterAppointmentsByStatus=function(appointments,statusList){return _.isEmpty(statusList)?appointments:_.filter(appointments,function(appointment){return _.includes(statusList,appointment.status)})};return function(appointments,filters){if(_.isEmpty(filters))return appointments;if(_.isEmpty(filters.serviceUuids)&&_.isEmpty(filters.serviceTypeUuids)){var appointmentsFilteredByProviders=filterAppointmentsByProviders(appointments,filters.providerUuids);return filterAppointmentsByStatus(appointmentsFilteredByProviders,filters.statusList)}var appointmentsFilteredByService=filterAppointmentsByService(appointments,filters.serviceUuids),appointmentsFilteredByServiceType=filterAppointmentsByServiceType(appointments,filters.serviceTypeUuids),appointmentsFilteredBySpeciality=appointmentsFilteredByService.concat(appointmentsFilteredByServiceType),appointmentsFilteredByProviders=filterAppointmentsByProviders(appointmentsFilteredBySpeciality,filters.providerUuids);return filterAppointmentsByStatus(appointmentsFilteredByProviders,filters.statusList)}}]);