Stored Functions

Content-Type: text/xml
URN: urn:ihe:iti:csd:2014:adhoc

Description



 
    Performs an ad-hoc search on a CSD document
  

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare namespace csd  =  "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;


let $expr :=$careServicesRequest/adhoc/text()

return 
  if ($expr) 
  then xquery:eval($expr,map{"":/.})
  else ()
Content-Type: text/xml
URN: urn:ihe:iti:csd:2014:stored-function:facility-search

Description



 
    
    Performs a search for all facilities by name, type, address or ID.   
    
    
      The result set consists of all facilities matching the  search parameters ( id, primaryName, name, codedType and address ).
     
        
      The results set may be further restricted according to the limit parameters (start, max, record/@status and record/@updated).  An ordering of the result set is not specified.
    
    
    Response
    Results are returned as a valid CSD document with a root document element of <CSD/>.  The results set is contained entirely within the <facilityDirectory/> element and consists of the full content of the <facility/> elements of matching facilities as maintained by the Care Services InfoManager.
    
    Parameters Query
    Parameters are defined as the content of following elements:
    
       <id/> csd:uniqueID: (optional) If present and the @entityID attribute contains a non-empty value, it is a ID which uniquely identifies a facility. This is an exact match.  
      
      <primaryName/> xs:string: (optional) If present and contains a non-empty value, then the result set should be restricted to those facilities whose <primaryName/> contains this value. Case insensitive.
      <name/> xs:string: (optional) If present and contains a non-empty value, then the result set should be restricted to those facilities which have a <primaryName/> or <otherName/> element containing this value. Case insensitive.      
      <codedType/> csd:codedtype:  If present and contains a non-empty value the result set should be restricted to those facilities whose <codedType/@code> equals this value for the coding schema specified by the @codingScheme attribute.  Case insensitive.
      
       <address/> csd:address: (optional) Contains of any-number of child <addressLine/> elements as follows:
        
          Text content xs:string: (optional) If present and contains a non-empty value, then the results set should be restricted to those facilities whose have an <addressLine/> with specified @component containing this value exactly.  Case insensitive.
           
          @component xs:string : (Required attribute) The component of the address we are searching. Case insensitive.
          
      
      <start/>  xs:int: (optional) The starting index for results returned. Defaults to 1, which indexes the first facility matching the search parameters
      <max/>  xs:int: (optional) The maximum number of results returned.  A value of less than zero implies no maximum.
      
	<record/>  csd:record : (optional) A child element to limit results according to
	
	  @status xs:string: (optional) If present and contains a non-empty value, the result set should be restricted to those facilities whose record/@status equals this value.  Case insensitive.
	  @updated xs:dateTime: (optional) If present and contains a non-empty value, the result set should be restricted to those facilities whose record/@updated is at least the given value.
	
      
    
    Example Request
    
         <careServicesRequest>
           <function urn='urn:ihe:iti:csd:2014:stored-function:facility-search'>
               <codedType code='OPC' codingScheme="USDVA"/>
               <address>
                 <addressLine component='city'>Chapel Hill</addressLine>
	       </address>
               <max>5</max>
           </function>
         </careServicesRequest>         
      
  

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare  variable $careServicesRequest as item() external;



(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory/>
  <facilityDirectory>
    {
      let $facs0 := if (exists($careServicesRequest/id))
	then csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id)
      else /CSD/facilityDirectory/*
         
      let $facs1 := if (exists($careServicesRequest/primaryName))
	then csd_bl:filter_by_primary_name($facs0,$careServicesRequest/primaryName)
      else $facs0
         
      let $facs2 := if (exists($careServicesRequest/name))
	then csd_bl:filter_by_name($facs1,$careServicesRequest/name)
      else $facs1
    
      let $facs3 := if(exists($careServicesRequest/codedType))
	then csd_bl:filter_by_coded_type($facs2,$careServicesRequest/codedType) 
      else $facs2
   
      let $facs4 := if(exists($careServicesRequest/address/addressLine))
	then csd_bl:filter_by_address($facs3, $careServicesRequest/address/addressLine) 
      else $facs3

      let $facs5 := if (exists($careServicesRequest/record))
	then csd_bl:filter_by_record($facs4,$careServicesRequest/record)      
      else $facs4

      let $facs6 := if(exists($careServicesRequest/otherID))
	then csd_bl:filter_by_other_id($facs5,$careServicesRequest/otherID)      
      else $facs5


      let $facs7 :=  if (exists($careServicesRequest/organizations/organization)) 
	then (csd_bl:filter_by_organizations($facs6,$careServicesRequest/organizations/organization)      )
      else  ($facs6)
	

      return if (exists($careServicesRequest/start)) then
	if (exists($careServicesRequest/max)) 
	  then csd_bl:limit_items($facs7,$careServicesRequest/start,$careServicesRequest/max)         
	else csd_bl:limit_items($facs7,$careServicesRequest/start,<max/>)         
      else
	if (exists($careServicesRequest/max)) 
	  then csd_bl:limit_items($facs7,<start/>,$careServicesRequest/max)         
	else $facs7


    }     
  </facilityDirectory>
  <providerDirectory/>
</CSD>
    
Content-Type: text/xml
URN: urn:openhie.org:openinfoman:modtimes

Description



 
    Gets the maximum modification times for each of the four directories
  

Definition

Source:
declare namespace csd = 'urn:ihe:iti:csd:2013';
declare variable $careServicesRequest as item() external;
let $ptime := max( for $dt in /csd:CSD/csd:providerDirectory/csd:provider/csd:record/@updated return xs:dateTime($dt))
let $otime := max( for $dt in /csd:CSD/csd:organizationDirectory/csd:provider/csd:record/@updated return xs:dateTime($dt))
let $ftime := max( for $dt in /csd:CSD/csd:facilityDirectory/csd:provider/csd:record/@updated return xs:dateTime($dt))
let $stime := max( for $dt in /csd:CSD/csd:serviceDirectory/csd:provider/csd:record/@updated return xs:dateTime($dt))
let $time := max (($ptime,$otime,$ftime,$stime))
return 
  <csd:CSD updated="{$time}">
    <csd:providerDirectory updated="{$ptime}"/>
    <csd:facilityDirectory updated="{$ftime}"/>
    <csd:organizationDirectory updated="{$otime}"/>
    <csd:serviceDirectory updated="{$stime}"/>
  </csd:CSD>
Content-Type: text/xml
URN: urn:ihe:iti:csd:2014:stored-function:organization-search

Description



 
    
    Performs a search for all organizations by name, coded type, address or ID.   
    
    
      The result set consists of all organizations matching the  search parameters ( id, primaryName, name, codedType and address ).
     
        
      The results set may be further restricted according to the limit parameters (start, max, record/@status and record/@updated).  An ordering of the result set is not specified.
    
    
    Response
    Results are returned as a valid CSD document with a root document element of <CSD/>.  The results set is contained entirely within the <organizationDirectory/> element and consists of the full content of the <organization/> elements of matching organizations as maintained by the Care Services InfoManager.
    
    Parameters Query
    Parameters are defined as the content of following elements:
    
       <id/> csd:uniqueID: (optional) If present and the @entityID attribute contains a non-empty value, it is a ID which uniquely identifies an organization. This is an exact match.  
      
      <primaryName/> xs:string: (optional) If present and contains a non-empty value, then the result set should be restricted to those organizations whose <primaryName/> contains this value. Case insensitive.
      <name/> xs:string: (optional) If present and contains a non-empty value, then the result set should be restricted to those organizations which have a <primaryName/> or <otherName/> element containing this value. Case insensitive.      
      <codedType/> csd:codedtype:  If present and contains a non-empty value the result set should be restricted to those organizations whose <codedType/@code> equals this value for the coding schema specified by the @codingScheme attribute.  Case insensitive.
      
       <address/> csd:address: (optional) Contains of any-number of child <addressLine/> elements as follows:
        
          Text content xs:string: (optional) If present and contains a non-empty value, then the results set should be restricted to those organizations whose have an <addressLine/> with specified @component containing this value exactly.  Case insensitive.
           
          @component xs:string : (Required attribute) The component of the address we are searching. Case insensitive.
          
      
      <start/>  xs:int: (optional) The starting index for results returned. Defaults to 1, which indexes the first organization matching the search parameters
      <max/>  xs:int: (optional) The maximum number of results returned.  A value of less than zero implies no maximum.
      
	<record/>  csd:record : (optional) A child element to limit results according to
	
	  @status xs:string: (optional) If present and contains a non-empty value, the result set should be restricted to those organizations whose record/@status equals this value.  Case insensitive.
	  @updated xs:dateTime: (optional) If present and contains a non-empty value, the result set should be restricted to those organizations whose record/@updated is at least the given value.
	
      
    
    Example Request
    
         <careServicesRequest>
           <function urn='urn:ihe:iti:csd:2014:stored-function:service-search'>
               <codedType codingScheme="moh.gov.rw" code="FBO" />
               <address>
                 <addressLine component='city'>Kigali</addressLine>
	       </address>
               <max>5</max>
           </function>
         </careServicesRequest>         
      
  

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 


<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory>
    {
      let $orgs0 := if (exists($careServicesRequest/id))
	then csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id)
      else /CSD/organizationDirectory/*
         
      let $orgs1 := if (exists($careServicesRequest/primaryName))
	then csd_bl:filter_by_primary_name($orgs0,$careServicesRequest/primaryName)
      else $orgs0
         
      let $orgs2 := if(exists($careServicesRequest/name))
	then csd_bl:filter_by_name($orgs1,$careServicesRequest/name)
      else $orgs1
    
      let $orgs3 := if(exists($careServicesRequest/codedType))
	then csd_bl:filter_by_coded_type($orgs2,$careServicesRequest/codedType)
      else $orgs2
   
      let $orgs4 :=if (exists($careServicesRequest/address/addressLine))
	then csd_bl:filter_by_address($orgs3, $careServicesRequest/address/addressLine)
      else $orgs3
      
      let $orgs5 := if (exists($careServicesRequest/record))
	then csd_bl:filter_by_record($orgs4,$careServicesRequest/record)
      else $orgs4

      let $orgs6 := if (exists($careServicesRequest/otherID))
	then csd_bl:filter_by_other_id($orgs5,$careServicesRequest/otherID)
      else $orgs5

      let $orgs7 := if (exists($careServicesRequest/parent))
	then csd_bl:filter_by_parent($orgs5,$careServicesRequest/parent)
      else $orgs6

      return if (exists($careServicesRequest/start)) then
	if (exists($careServicesRequest/max))
	  then csd_bl:limit_items($orgs7,$careServicesRequest/start,$careServicesRequest/max)
	else csd_bl:limit_items($orgs7,$careServicesRequest/start,<max/>)
      else
	if (exists($careServicesRequest/max))
	  then csd_bl:limit_items($orgs7,<start/>,$careServicesRequest/max)
	else $orgs7

    }     
  </organizationDirectory>
  <serviceDirectory/>
  <facilityDirectory/>
  <providerDirectory/>
</CSD>
Content-Type: text/xml
URN: urn:ihe:iti:csd:2014:stored-function:provider-search

Description



     Performs a search for all providers by name, coded type, address or ID. 
     The result set consists of all providers matching the search parameters ( id,
        otherID, commonName,codedType and address ). 
     The results set may be further restricted according to the limit parameters
        (start, max, record/@status and record/@updated). An ordering of
      the result set is not specified. 
    
      Response Results are returned as a valid CSD document with a root document element of
      <CSD/>. The results set is contained entirely within the <providerDirectory/>
      element and consists of the full content of the <provider/> elements of matching
      providers as maintained by the Care Services InfoManager. 
    Parameters Query Parameters are defined as the content of following elements: 
       <id/> csd:uniqueID: (optional) If present and the @entityID attribute contains a
        non-empty value, it is a ID which uniquely identifies a provider. This is an exact match. 
       <otherID/> csd:otherID: (optional) If present and the
        @assigningAuthorityName attribute contains a non-empty value, then the result set is
        restricted to only those providers which have a <otherID/> with the given
        assigingAuthorityName and @code  <commonName/> xsd:string: (optional)
        If present and contains a non-empty value, then the result set should be restricted to those
        providers which have a <demographic/name/commonName/> containing this value. Case
        insensitive.
      <codedType/> csd:codedtype: If present and contains a non-empty value the
        result set should be restricted to those providers whose <codeType/@code> equals this
        value for the coding schema specified by the @codingScheme attribute. Case insensitive. 
       <address/> csd:address: (optional) Contains of any-number of child
        <addressLine/> elements as follows: 
          Text content xsd:string: (optional) If present and contains a non-empty value,
            then the results set should be restricted to those providers whose have an
            <addressLine/> with specified @component containing this value exactly. Case
            insensitive. 
          @component xsd:string : (Required attribute) The component of the address we
            are searching. Case insensitive.
        
      
      <start/>  xsd:int: (optional) The starting index for results returned.
        Defaults to 1, which indexes the first provider matching the search parameters
      <max/>  xsd:int: (optional) The maximum number of results returned. A value
        of less than zero implies no maximum.
       <record/>  csd:record : (optional) A child element to limit results
        according to 
          @status xsd:string: (optional) If present and contains a non-empty value, the
            result set should be restricted to those providers whose record/@status equals this
            value. Case insensitive.
          @updated xsd:dateTime: (optional) If present and contains a non-empty value,
            the result set should be restricted to those providers whose record/@updated is at least
            the given value.
        
      
    
    Example Request
    
         <careServicesRequest>
           <function urn='urn:ihe:iti:csd:2014:stored-function:service-search'>
               <codedType code="2221" codingScheme="ISCO-08" /<
               <address>
                 <addressLine component='city'>Kigali</addressLine>
	       </address>
               <max>5</max>
           </function>
         </careServicesRequest>         
      
  

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory/>
  <facilityDirectory/>
  <providerDirectory>
    {

      let $provs0 := if (exists($careServicesRequest/id))
	then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id)
      else /CSD/providerDirectory/*

      let $provs1 := if(exists($careServicesRequest/otherID))
	then csd_bl:filter_by_other_id($provs0,$careServicesRequest/otherID)
      else $provs0
         
      let $provs2 := if(exists($careServicesRequest/commonName))
	then csd_bl:filter_by_common_name($provs1,$careServicesRequest/commonName)
      else $provs1
    
      let $provs3 := if (exists($careServicesRequest/codedType))
	then csd_bl:filter_by_coded_type($provs2,$careServicesRequest/codedType) 
      else $provs2
   
      let $provs4 := if (exists($careServicesRequest/address/addressLine))
	then csd_bl:filter_by_demographic_address($provs3, $careServicesRequest/address/addressLine) 
      else $provs3

      let $provs5 :=  if (exists($careServicesRequest/record)) 
	then csd_bl:filter_by_record($provs4,$careServicesRequest/record)      
      else  $provs4

      let $provs6 :=  if (exists($careServicesRequest/facilities/facility)) 
	then csd_bl:filter_by_facilities($provs5,$careServicesRequest/facilities/facility)
      else  $provs5

      let $provs7 :=  if (exists($careServicesRequest/organizations/organization)) 
	then csd_bl:filter_by_organizations($provs6,$careServicesRequest/organizations/organization)      
      else  $provs6

      let $provs7a := if(exists($careServicesRequest/language))
	then csd_bl:filter_by_languages($provs7,$careServicesRequest/language)
      else $provs7
    


      return if (exists($careServicesRequest/start)) then
	if (exists($careServicesRequest/max)) 
	  then csd_bl:limit_items($provs7a,$careServicesRequest/start,$careServicesRequest/max)         
	else csd_bl:limit_items($provs7a,$careServicesRequest/start,<max/>)         
      else
	if (exists($careServicesRequest/max)) 
	  then csd_bl:limit_items($provs7a,<start/>,$careServicesRequest/max)         
	else $provs7a

    }     
  </providerDirectory>
</CSD>
Content-Type: text/xml
URN: urn:ihe:iti:csd:2014:stored-function:service-search

Description



 
    
    Performs a search for all search by coded type or ID.   
    
    
      The result set consists of all serices matching the  search parameters ( id and codedType ).
     
        
      The results set may be further restricted according to the limit parameters (start, max, record/@status and record/@updated).  An ordering of the result set is not specified.
    
    
    Response
    Results are returned as a valid CSD document with a root document element of <CSD/>.  The results set is contained entirely within the <serviceDirectory/> element and consists of the full content of the <service/> elements of matching services as maintained by the Care Services InfoManager.
    
    Parameters Query
    Parameters are defined as the content of following elements:
    
       <id/> csd:uniqueID: (optional) If present and the @entityID attribute contains a non-empty value, it is a ID which uniquely identifies a service. This is an exact match.  
      
      <codedType/> csd:codedtype:  If present and contains a non-empty value the result set should be restricted to those services whose <codedType/@code> equals this value for the coding schema specified by the @codingScheme attribute.  Case insensitive.
      
      <start/>  xs:int: (optional) The starting index for results returned. Defaults to 1, which indexes the first service matching the search parameters
      <max/>  xs:int: (optional) The maximum number of results returned.  A value of less than zero implies no maximum.
      
	<record/>  csd:record : (optional) A child element to limit results according to
	
	  @status xs:string: (optional) If present and contains a non-empty value, the result set should be restricted to those serivces whose record/@status equals this value.  Case insensitive.
	  @updatedxs:dateTime: (optional) If present and contains a non-empty value, the result set should be restricted to those serivces whose record/@updated is at least the given value.
	
      
    
    Example Request
    
         <careServicesRequest>
           <function urn='urn:ihe:iti:csd:2014:stored-function:service-search'>
             <codedType code="76499" codingScheme="HCPCS" />
             <start>101</max>
           </function>
         </careServicesRequest>         
      
  

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory>
    {
      let $svcs0 := if (exists($careServicesRequest/id))
	then csd_bl:filter_by_primary_id(/CSD/serviceDirectory/*,$careServicesRequest/id)
      else /CSD/serviceDirectory/*
    	
      let $svcs1 := if(exists($careServicesRequest/codedType))
	then csd_bl:filter_by_coded_type($svcs0,$careServicesRequest/codedType) 
      else $svcs0

      let $svcs2 :=  if (exists($careServicesRequest/record))
	then csd_bl:filter_by_record($svcs1,$careServicesRequest/record)
      else $svcs1

      return if (exists($careServicesRequest/start)) then
	if (exists($careServicesRequest/max)) 
	  then csd_bl:limit_items($svcs2,$careServicesRequest/start,$careServicesRequest/max)         
	else csd_bl:limit_items($svcs2,$careServicesRequest/start,<max/>)         
      else
	if (exists($careServicesRequest/max)) 
	  then csd_bl:limit_items($svcs2,<start/>,$careServicesRequest/max)         
	else $svcs2

    }     
  </serviceDirectory>
  <facilityDirectory/>
  <providerDirectory/>
</CSD>
Content-Type: text/xml
URN: urn:openhie.org:openinfoman:delete_duplicate

Description



 
    Deletes duplicate record reference.  This is done by removing a <csd:otherID/> element on the duplicate record that  references the master record.  
    
    This a <csd:otherID/> is characterized as follows:
    
      The @assigningAuthorityName attribute will be the fixed valueurn:openhie.org:openinfoman attribute of the master record      
      The @code attribute will be the fixed value 'duplicate' to indicate this is for marking a duplicate
      The text() value will be the entity ID used to reference to the master record for the entity
    

    A Care Services Request can be submitted to delete the mark that the record as duplicate with the following request parameters:
    
      <masterEntity/> should have attribute @entityID which contains the entity ID of the master record that the duplicate record should refer to
      <duplicateEntity/> should have attribute @entityID which contains the entity ID of the  duplicate record
    

  

Definition

Source:
import module namespace csd_lsc = "https://github.com/openhie/openinfoman/csd_lsc";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
declare namespace csd  =  "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;

let $doc_name := string($careServicesRequest/@resource)
let $doc := csd_dm:open_document($doc_name)

let $masterID := $careServicesRequest/masterEntity/@entityID

let $dupID := $careServicesRequest/duplicateEntity/@entityID
let $dupEntity :=  if (exists($dupID)) then (/csd:CSD/*/*[@entityID = $dupID])[1] else ()


let $dupRef := $dupEntity/csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='duplicate' and text()=$masterID]

return 
  if (exists($dupRef))
  then delete node $dupRef
  else ()
Content-Type: text/xml
URN: urn:openhie.org:openinfoman:delete_potential_duplicate

Description



 
    Deletes potential duplicate record reference.  This is done by removing a <csd:otherID/> element on the potetnial duplicate record which references the master record.  
    
    This a <csd:otherID/> is characterized as follows:
    
      The @assigningAuthorityName attribute will be the fixed valueurn:openhie.org:openinfoman attribute of the master record      
      The @code attribute will be the fixed value 'duplicate' to indicate this is for marking a duplicate
      The text() value will be the entity ID used to reference to the master record for the entity
    

    A Care Services Request can be submitted to delete the mark that the record as potential duplicate with the following request parameters:
    
      <masterEntity/> should have attribute @entityID which contains the entity ID of the master record that the duplicate record should refer to
      <duplicateEntity/> should have attribute @entityID which contains the entity ID of the  duplicate record
    

  

Definition

Source:
import module namespace csd_lsc = "https://github.com/openhie/openinfoman/csd_lsc";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
declare namespace csd  =  "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;

let $doc_name := string($careServicesRequest/@resource)
let $doc := csd_dm:open_document($doc_name)

let $masterID := $careServicesRequest/masterEntity/@entityID

let $dupID := $careServicesRequest/duplicateEntity/@entityID
let $dupEntity :=  if (exists($dupID)) then (/csd:CSD/*/*[@entityID = $dupID])[1] else ()


let $dupRef := $dupEntity/csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='potential-duplicate' and text()=$masterID]

return 
  if (exists($dupRef))
  then delete node $dupRef
  else ()
Content-Type: text/xml
URN: urn:openhie.org:openinfoman:extract_hierachy

Description



 
    Performs an organization hierarch extraction from a source document into the target document.  Any existing elements in the target document are overwritten by those from the source document(s).

    There are two required parameters:
    
      
	The document is indicated via <document/%gt; element.    If  @resource attribute of the <document/> should be the name of a document available to OpenInfoMan.   Otherwise the content of the <document/> should be a valid CSD document.
      
    

    Under each  <document/> is the required elements:
    
      
	Aa <csd:organization/> element to indicate the part of the hiearchy that should be extracted.  
      
    
    Under each  <document/> are two optional elements:
    
      
	keepParents
	0..1 keepParents  element has integer attribute @value.  Defaults to 1 which means we keep the parents of the indicated organization when we extract.
      
      
	processFacilities
	0..1 processFacilities  element has integer attribute @value.  Defaults to 1 which means we also include the facilities associated to the organizations in the extracted hierarchy.
      
    


All parent nodes of the indicated organziation 
  

Definition

Source:
import module namespace csd_lsc = "https://github.com/openhie/openinfoman/csd_lsc";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace functx = "http://www.functx.com";
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare namespace csd  =  "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;



let $dest_doc := /.
let $dest := $careServicesRequest/@resource


return for $doc in $careServicesRequest/documents/document
  let $name := $doc/@resource
  let $src_doc :=
    if (not (functx:all-whitespace($name)))
    then if (not ($name = $dest)) then csd_dm:open_document($name) else ()
    else $doc/csd:CSD
  let $req_org_id :=  $doc/csd:organization/@entityID 

    
  let $processFacilities := 
    if (exists($doc/processFacilities/@value))
    then ($doc/processFacilities/@value = 1)
    else true()
  let $keepParents := 
    if (exists($doc/keepParents/@value))
    then ($doc/keepParents/@value = 1)
    else true()
    
  let $all_orgs := $src_doc/csd:CSD/csd:organizationDirectory/csd:organization
  let $org := $all_orgs[@entityID = $req_org_id]

  let $orgs := 
    if (not(exists($org)))
    then () (: nothing to extract:) 
    else
      (
	if ($keepParents)
	then csd_bl:get_parent_orgs($all_orgs,$org)
	else ()
	,
	$org
	,
	csd_bl:get_child_orgs($all_orgs,$org)
      )

  let $facs := 
    if (not ($processFacilities) )
    then ()
    else 
      for $org in $orgs
      return  $src_doc/csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization/@entityID = $org/@entityID]
	


  return
    (
      csd_lsc:update_directory($dest_doc/csd:CSD/csd:organizationDirectory,$orgs)
      ,csd_lsc:update_directory($dest_doc/csd:CSD/csd:facilityDirectory,$facs)
    )



Content-Type: text/xml
URN: urn:openhie.org:openinfoman:facility_create

Description



Create or update a facility entity.   Request parameters should be one or more CSD facility entities

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
(:
import module namespace random = "http://basex.org/modules/random";
:)
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
for $fac in $careServicesRequest/facility
  let $existing := if (exists($fac/@entityID)) then csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$fac) else ()
  return
    if (exists($existing)) 
    then replace node $existing with $fac
    else insert node $fac into /CSD/facilityDirectory
Content-Type: text/xml
URN: urn:openhie.org:openinfoman:mark_duplicate

Description



 
    Marks a record as a duplicate with another record.  This is done by adding a <csd:otherID/> element to the record that is duplicate which references the master record.  
    
    This a <csd:otherID/> is characterized as follows:
    
      The @assigningAuthorityName attribute will be the fixed valueurn:openhie.org:openinfoman attribute of the master record      
      The @code attribute will be the fixed value 'duplicate' to indicate this is for marking a duplicate
      The text() value will be the entity ID used to reference to the master record for the entity
    

    A Care Services Request can be submitted to mark the record as duplicate with the following request parameters:
    
      <masterEntity/> should have attribute @entityID which contains the entity ID of the master record that the duplicate record should refer to
      <duplicateEntity/> should have attribute @entityID which contains the entity ID of the  duplicate record
    

  

Definition

Source:
import module namespace csd_lsc = "https://github.com/openhie/openinfoman/csd_lsc";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
declare namespace csd  =  "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;

let $doc_name := string($careServicesRequest/@resource)
let $doc := csd_dm:open_document($doc_name)

let $masterID := $careServicesRequest/masterEntity/@entityID
let $masterEntity := if (exists($masterID)) then  (/csd:CSD/*/*[@entityID = $masterID])[1] else ()

let $dupID := $careServicesRequest/duplicateEntity/@entityID
let $dupEntity :=  if (exists($dupID)) then (/csd:CSD/*/*[@entityID = $dupID])[1] else ()


let $masterRef := <csd:otherID assigningAuthorityName='urn:openhie.org:openinfoman' code='duplicate'>{string($masterID)}</csd:otherID>

return 
  if (not(exists($masterEntity)) or not( exists($dupEntity)))
  then ()
  else 
    let $existingRef := ($dupEntity/csd:otherID[@assigningAuthorityName = 'urn:openhie.org:openinfoman' and @code='duplicate'])[1]
    return 
      (
	if (exists($existingRef))
	then (replace node $existingRef with $masterRef)
	else (insert node $masterRef before ($dupEntity/*)[1])
      ,
        for $entity in /csd:CSD/*/*[./csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='duplicate' and ./text()=$dupID]]
	let $e_existingRef := ($entity/csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='duplicate' and  ./text()=$dupID])[1]
	return 
	  if (not($e_existingRef = $existingRef)  )
	  then replace node $e_existingRef with $masterRef
	  else () (:avoid double replacelement in edge case in which a record is marked as duplicate to itself:)
     )


Content-Type: text/xml
URN: urn:openhie.org:openinfoman:mark_potential_duplicate

Description



 
    Marks a record as a potential duplicate with another record.  This is done by adding a <csd:otherID/> element to the record that is the potential duplicate which references the master record.  
    
    This a <csd:otherID/> is characterized as follows:
    
      The @assigningAuthorityName attribute will be the fixed valueurn:openhie.org:openinfoman attribute of the master record      
      The @code attribute will be the fixed value 'potential-duplicate' to indicate this is for marking a potential duplicate
      The text() value will be the entity ID used to reference to the master record for the entity
    

    A Care Services Request can be submitted to mark the record as potential duplicate with the following request parameters:
    
      <masterEntity/> should have attribute @entityID which contains the entity ID of the master record that the potential duplicate record should refer to
      <duplicateEntity/> should have attribute @entityID which contains the entity ID of the  duplicate record
    

  

Definition

Source:
import module namespace csd_lsc = "https://github.com/openhie/openinfoman/csd_lsc";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
declare namespace csd  =  "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;

let $doc_name := string($careServicesRequest/@resource)
let $doc := csd_dm:open_document($doc_name)

let $masterID := $careServicesRequest/masterEntity/@entityID
let $masterEntity := if (exists($masterID)) then  (/csd:CSD/*/*[@entityID = $masterID])[1] else ()

let $dupID := $careServicesRequest/duplicateEntity/@entityID
let $dupEntity :=  if (exists($dupID)) then (/csd:CSD/*/*[@entityID = $dupID])[1] else ()


let $masterRef := <csd:otherID assigningAuthorityName='urn:openhie.org:openinfoman' code='potential-duplicate'>{string($masterID)}</csd:otherID>

return 
  if (not(exists($masterEntity)) or not( exists($dupEntity)))
  then ()
  else 
    let $existingRef := ($dupEntity/csd:otherID[@assigningAuthorityName = 'urn:openhie.org:openinfoman' and @code='potential-duplicate' and text() = $masterID])[1]
    return 
      (
	if (exists($existingRef))
	then (replace node $existingRef with $masterRef)
	else (insert node $masterRef before ($dupEntity/*)[1])
      ,
        for $entity in /csd:CSD/*/*[./csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='potential-duplicate' and ./text()=$dupID]]
	let $e_existingRef := ($entity/csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='potential-duplicate' and  ./text()=$dupID])[1]
	return (replace node $e_existingRef with $masterRef)
     )


Content-Type: text/xml
URN: urn:openhie.org:openinfoman:identifier_merge

Description



 
    Performs a merge from the indicated source document(s) into the target document.   Any entities in the target document are overwritten by the corresponding entity in the source document except that <csd:otherID/> elements are preserved.

    Documents are indicated via <document/%gt; elements under the top-level <documents/> element.   
    The  @resource attribute of the <document/> should be the name of a document available to OpenInfoMan.   Otherwise the content of the <document/> should be a valid CSD document.


    The following optional elements are allowed under each <document/%gt; element :
    
      insertNew 0..1 insertNew has integer attribute @value. Defaults to 1 which means we insert any new entities from the source documents if they are not already a part of the destination document
    

  

Definition

Source:
import module namespace csd_lsc = "https://github.com/openhie/openinfoman/csd_lsc";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace functx = "http://www.functx.com";
declare namespace csd  =  "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;



let $dest_doc := /.
let $dest := $careServicesRequest/@resource
for $doc in $careServicesRequest/documents/document
  let $insertNew := 
    if (exists($doc/insertNew/@value))
    then ($doc/insertNew/@value = 1)
    else true()

  let $name := string($doc/@resource)
  let $src_doc :=
    if (not (functx:all-whitespace($name)))
    then if (not ($name = $dest)) then csd_dm:open_document( $name) else ()
    else $doc
  return 
    (
    let $src_dir := $src_doc/csd:CSD/csd:organizationDirectory
    let $dest_dir := $dest_doc/csd:CSD/csd:organizationDirectory
    return
      for $e in $src_dir/csd:organization 
      let $existing := $dest_dir/csd:organization[@entityID = $e/@entityID]
      return 
	if (exists($existing)) 
        then
          let $new := 
	    <csd:organization entityID="{$e/@entityID}">
	      {$existing/csd:otherID}  
	      {$e/*}
	    </csd:organization>
	  return replace node $existing with $new 
        else if ($insertNew) then insert node $e into $dest_dir else ()
    ,
    let $src_dir := $src_doc/csd:CSD/csd:providerDirectory
    let $dest_dir := $dest_doc/csd:CSD/csd:providerDirectory
    return
      for $e in $src_dir/csd:provider 
      let $existing := $dest_dir/csd:provider[@entityID = $e/@entityID]
      return 
	if (exists($existing)) 
	then
          let $new := 
	    <csd:provider entityID="{$e/@entityID}">
	      {$existing/csd:otherID}  
	      {$e/*}
	    </csd:provider>
	  return replace node $existing with $new 
        else if ($insertNew) then insert node $e into $dest_dir else ()
    ,
    let $src_dir := $src_doc/csd:CSD/csd:serviceDirectory
    let $dest_dir := $dest_doc/csd:CSD/csd:serviceDirectory
    return
      for $e in $src_dir/csd:service 
      let $existing := $dest_dir/csd:service[@entityID = $e/@entityID]
      return 
	if (exists($existing)) 
	then
          let $new := 
	    <csd:service entityID="{$e/@entityID}">
	      {$existing/csd:otherID}  
	      {$e/*}
	    </csd:service>
	  return replace node $existing with $new 
        else if ($insertNew) then insert node $e into $dest_dir else ()
    ,
    let $src_dir := $src_doc/csd:CSD/csd:facilityDirectory
    let $dest_dir := $dest_doc/csd:CSD/csd:facilityDirectory
    return
      for $e in $src_dir/csd:facility 
      let $existing := $dest_dir/csd:facility[@entityID = $e/@entityID]
      return 
	if (exists($existing)) 
	then
          let $new := 
	    <csd:facility entityID="{$e/@entityID}">
	      {$existing/csd:otherID}  
	      {$e/*}
	    </csd:facility>
	  return replace node $existing with $new 
        else if ($insertNew) then insert node $e into $dest_dir else ()

    )




Content-Type: text/xml
URN: urn:openhie.org:openinfoman:organization_create

Description



Create or update a organization entity.   Request parameters should be one or more CSD organization entities

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
(:
import module namespace random = "http://basex.org/modules/random";
:)
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
for $org in $careServicesRequest/organization
  let $existing := if (exists($org/@entityID)) then csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$org) else ()
  return
    if (exists($existing)) 
    then replace node $existing with $org
    else insert node $org into /CSD/organizationDirectory
Content-Type: text/xml
URN: urn:openhie.org:openinfoman:provider_create

Description



Create or update a provider entity.   Request parameters should be one or more CSD provider entities

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
(:
import module namespace random = "http://basex.org/modules/random";
:)
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
for $prov in $careServicesRequest/provider
  let $existing := if (exists($prov/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$prov) else ()
  return
    if (exists($existing)) 
    then replace node $existing with $prov
    else insert node $prov into /CSD/providerDirectory
Content-Type: text/xml
URN: urn:openhie.org:openinfoman:service_create

Description



Create or update a service entity.   Request parameters should be one or more CSD service entities

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
(:
import module namespace random = "http://basex.org/modules/random";
:)
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
for $srvc in $careServicesRequest/service
  let $existing := if (exists($srvc/@entityID)) then csd_bl:filter_by_primary_id(/CSD/serviceDirectory/*,$srvc) else ()
  return
    if (exists($existing)) 
    then replace node $existing with $srvc
    else insert node $srvc into /CSD/serviceDirectory
Content-Type: text/xml
URN: urn:openhie.org:openinfoman:simple_merge

Description



 
    Performs a simple merge from the indicated source document(s) into the target document.  

    Documents are indicated via <document/%gt; elements under the top-level <documents/> element.   
    If  @resource attribute of the <document/> should be the name of a document available to OpenInfoMan.   Otherwise the content of the <document/> should be a valid CSD document.

    The following optional elements are allowed:
    
      overwriteExisting 0..1 overwriteExisting has integer attribute @value. Defaults to 1 which aany existing elements in the target document are overwritten by those from the source document(s).
    

  

Definition

Source:
import module namespace csd_lsc = "https://github.com/openhie/openinfoman/csd_lsc";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace functx = "http://www.functx.com";
declare namespace csd  =  "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;


let $overwriteExisting := 
  if (exists($careServicesRequest/overwriteExisting/@value))
  then ($careServicesRequest/overwriteExisting/@value = 1)
  else true()


let $dest_doc := /.
let $dest := $careServicesRequest/@resource

for $doc  in $careServicesRequest/documents/document
  let $name := $doc/@resource
  let $src_doc :=
    if (not (functx:all-whitespace($name)))
    then if (not ($name = $dest)) then csd_dm:open_document($name) else ()
    else $doc
  return  
    csd_lsc:refresh_doc($dest_doc, $src_doc,$overwriteExisting) 



Content-Type: text/xml
URN: urn:dhis2.org:csd:stored-function:aggregate_hw_export

Description



 
    Returns DHIS2 DXF quaterly report of number of health workers by facility 
    
    Reuqest parameters:
      assigningAuthorityName: the assignining authority name for the csd:facility/csd:otherID in which the DHIS code is stored
  

Definition

Source:
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

let $facilities := /csd:CSD/csd:facilityDirectory/csd:facility
let $active_providers := /csd:CSD/csd:providerDirectory/csd:provider[./csd:record/@status = "106-001"]

let $year := year-from-date(current-date())
let $month := month-from-date(current-date())
let $quarter := 
  if ($month < 4) then "1"
  else if ($month < 7) then "2"
  else if ($month < 10) then "3"
  else "4"
let $period := concat($year , 'Q',$quarter)

return 
  <dxf xmlns="http://dhis2.org/schema/dxf/2.0"> 
    <dataValueSet>
      {
	for $fac in $facilities
	let $fac_id := upper-case(string($fac/@entityID))
	let $facurn := substring($fac_id,10)
	let $fac_providers := $active_providers[./csd:facilities/csd:facility[upper-case(./@entityID)=$fac_id]]
	let $count := count($fac_providers)
	where $facurn  and $count > 0   
	return <dataValue period="{$period}" orgUnit="{$facurn}" dataElement="numProviders" value="{$count}" />
      }
    </dataValueSet>
  </dxf>
Content-Type: text/xml
URN: urn:dhis2.org:csd:stored-function:csd2dxf

Description



 
    Returns DHIS2 DXF Metadata representation of CSD facilties and organizations for import into a DHIS2 instance 
  

Definition

Source:
import module namespace dxf2csd = "http://dhis2.org/csd/dxf/2.0";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace svs_lsvs = "https://github.com/openhie/openinfoman/svs_lsvs";

declare namespace svs = "urn:ihe:iti:svs:2008";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare namespace dxf = "http://dhis2.org/csd/dxf/2.0";

declare variable $careServicesRequest as item() external; 

let $doc_name := string($careServicesRequest/@resource)
let $doc := csd_dm:open_document($doc_name)

let $facilities := $doc/csd:CSD/csd:facilityDirectory/csd:facility
let $svcs := $doc/csd:CSD/csd:serviceDirectory/csd:service
let $orgs := $doc/csd:CSD/csd:organizationDirectory/csd:organization


let $fac_type_ids := ("1.3.6.1.4.1.21367.200.103")

let $org_unit_groups :=   
  for $fac_type_id in $fac_type_ids	  
  let $fac_types :=  svs_lsvs:get_single_version_value_set(string($fac_type_id) )	  
  return
    for $concept in $fac_types//svs:Concept
    let $code := string($concept/@code)
    let $scheme := string($concept/@codeSystem)
    let $name := string($concept/@displayName)
    return <dxf:organisationUnitGroup code="{$code}" name="{$name}" codeSystem="{$scheme}"/>

return 
    <dxf:metaData>
      <dxf:organisationUnits>
        {
	  for $org in dxf2csd:ensure_properly_ordered_orgs($orgs)
	  return dxf2csd:make_org_from_org($doc,$org) 
	}
        {
	  for $fac in $facilities
	  return dxf2csd:make_org_from_fac($doc,$fac) 
	}
      </dxf:organisationUnits>


      <dxf:organisationUnitGroups>
        { 
	  for $org_unit_group in $org_unit_groups
	  let $code := string($org_unit_group/@code)
	  let $scheme := string($org_unit_group/@codeSystem)
	  let $name := string($org_unit_group/@name)
	  let $short_name := substring(string($org_unit_group/@name),1,50)
	    return 
	    <dxf:organisationUnitGroup code="{$code}" name="{$name}" shortName="{$short_name}">
	      <dxf:organisationUnits>
		{
		  for $fac in $facilities[./csd:codedType[@codingScheme = $scheme and @code = $code]]
		  let $uuid := dxf2csd:extract_uuid_from_entityid($fac/@entityID)
		  let $fac_name := $fac/csd:primaryName/text()
		  let $id := string($fac/@entityID)
		  return     
		     <dxf:organisationUnit uuid="{$uuid}" id="{$id}" name="{$fac_name}" />
		}
	      </dxf:organisationUnits>
	    </dxf:organisationUnitGroup>
	}
      </dxf:organisationUnitGroups>

      { 
      if (count($org_unit_groups) > 0)
      then
        <dxf:organisationUnitGroupSets>
	  <dxf:organisationUnitGroupSet name='Facility Type'>
	    <dxf:description>Facility Type</dxf:description>
	    <dxf:compulsory>true</dxf:compulsory>
	    <dxf:dataDimension>true</dxf:dataDimension>
	    <dxf:organisationUnitGroups>
	      {
		for $org_unit_group in $org_unit_groups
		let $code := string($org_unit_group/@code)
		let $scheme := string($org_unit_group/@codeSystem)
		let $name := string($org_unit_group/@name)
		return   <dxf:organisationUnitGroup code="{$code}" name="{$name}" />
	      }
	    </dxf:organisationUnitGroups>
	  </dxf:organisationUnitGroupSet>	
	</dxf:organisationUnitGroupSets>
      else () 
      }

    </dxf:metaData>
Content-Type: application/zip
URN: urn:dhis.org:transform_to_dxf:v2.19

Description



 
    Returns DHIS2 DXF Metadata representation of CSD providers, facilties and organizations for import into a DHIS2 instance 
    
    Request parameters are:
    
      
	csd:organization
	0..1 csd:organization element with @entityID attribute.  If present, will generate only the organisation unit hierarchy
	underneath the specified organization. Will also include all the parent organization units.  
      
      
	processUsers
	0..1 processUsers  element has integer attribute @value.  Defaults to 1 which means we process provides as DHIS2 users.
      
      
	preserveUUIDs
	0..1 processUUIDs  element has integer attribute @value.  Defaults to 1 which means we preserve DHIS2 UUIDs, if present, when creating the DXF metadata for import.
      
    
  

Definition

Source:
import module namespace dxf2csd = "http://dhis2.org/csd/dxf/2.0";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace svs_lsvs = "https://github.com/openhie/openinfoman/svs_lsvs";
import module namespace util = "https://github.com/openhie/openinfoman-dhis/util";
import module namespace functx = "http://www.functx.com";
import module namespace archive = "http://basex.org/modules/archive";

declare namespace svs = "urn:ihe:iti:svs:2008";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare namespace dxf = "http://dhis2.org/schema/dxf/2.0";

declare variable $careServicesRequest as item() external; 

let $doc_name := string($careServicesRequest/@resource)
let $processUsers := 
  if (exists($careServicesRequest/processUsers/@value))
  then ($careServicesRequest/processUsers/@value = 1)
  else true()
let $preserveUUIDs := 
  if (exists($careServicesRequest/preserveUUIDs/@value))
  then ($careServicesRequest/preserveUUIDs/@value = 1)
  else true()

let $onlyDirectChildren := 
  if (exists($careServicesRequest/onlyDirectChildren/@value))
  then ($careServicesRequest/onlyDirectChildren/@value = 1)
  else true()

let $zip := 
  if (exists($careServicesRequest/zip/@value))
  then ($careServicesRequest/zip/@value = 1)
  else true()
let $req_org_id :=    $careServicesRequest/csd:organization/@entityID 
let $req_ou_group_schemes:= distinct-values($careServicesRequest/orgUnitGroupSchemes/orgUnitGroupScheme/text())


let $t0 :=
  (
    trace($processUsers,'Process users: '),
    trace($preserveUUIDs,'Preserve UUIDs: '),
    trace($onlyDirectChildren,'Only Direct Children: '),
    trace($zip,'Zip: '),
    trace($req_org_id,'Requested Org EntityID: '),
    trace($req_ou_group_schemes,'Request Org Group Schemes: ')
  )

let $doc := csd_dm:open_document($doc_name)
  (:the organziation we want to import to:)



let $svcs := $doc/csd:CSD/csd:serviceDirectory/csd:service

let $orgs := 
  if (functx:all-whitespace($req_org_id))
  then dxf2csd:ensure_properly_ordered_orgs($doc/csd:CSD/csd:organizationDirectory/csd:organization)
  else 
    let $all_orgs := $doc/csd:CSD/csd:organizationDirectory/csd:organization
    let $org := $all_orgs[@entityID = $req_org_id]
    return 
      if (not(exists($org)))
      then ()
      else
	if ($onlyDirectChildren)
	then (util:get_parent_orgs($all_orgs,$org),$org,$all_orgs[./csd:parent[@entityID = $req_org_id]])
	else (util:get_parent_orgs($all_orgs,$org),$org,util:get_child_orgs($all_orgs,$org))  (: this comes back properly ordered for DHIS2 import :)


let $facilities := 
  if (functx:all-whitespace($req_org_id))
  then $doc/csd:CSD/csd:facilityDirectory/csd:facility
  else  $doc/csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization = $orgs]

let $provs := 
  if ($processUsers)
  then $doc/csd:CSD/csd:providerDirectory/csd:provider
  else ()



let $ou_oids := 
  for $dhis_url in distinct-values(($orgs/csd:record/@sourceDirectory,$facilities/csd:record/@sourceDirectory))
  let $namespace_uuid := util:uuid_generate($dhis_url,$util:namespace_uuid)
  let $oid := concat('2.25.',util:hexdec(util:uuid_generate('rootoid',$namespace_uuid)))	
  return $oid

    
let $dxf := 
    <dxf:metaData>
      <dxf:users>
      {
	for $prov in $provs

	let $dhis_url := string(($prov/csd:record/@sourceDirectory)[1])
	let $dhis_id :=  ($prov/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/users") and @code="id"])[1]/text()	  
	let $namespace_uuid := util:uuid_generate($dhis_url,$util:namespace_uuid)
	let $oid := concat('2.25.',util:hexdec(util:uuid_generate('rootoid',$namespace_uuid)))	

	let $name := ($prov/csd:demographic/csd:name/csd:commonName)[1]/text()
	let $surname := ($prov/csd:demographic/csd:name/csd:surname)[1]/text()
	let $firstname := ($prov/csd:demographic/csd:name/csd:forename)[1]/text()
	let $username := dxf2csd:extract_uuid_from_entityid(string($prov/@entityID))
	let $phone := ($prov/csd:contactPoint/csd:codedType[@code="BP" and @codingScheme="urn:ihe:iti:csd:2013:contactPoint"])[1]/text()
	let $email := ($prov/csd:contactPoint/csd:codedType[@code="EMAIL" and @codingScheme="urn:ihe:iti:csd:2013:contactPoint"])[1]/text()
	let $ag_oid := concat($oid,'.4')
	let $ur_oid := concat($oid,'.1')
	let $urs := 
	   for $o_id in $prov/csd:codedType[@codingScheme = $ur_oid]
	   return <dxf:userRole id="{string($o_id/@code)}"/>
	let $uags := 
	   for $o_id in $prov/csd:codedType[@codingScheme = $ag_oid]
	   return <dxf:userAuthorityGroup id="{string($o_id/@code)}"/>
	let $p_orgs := 
	  for $org in $prov/csd:organizations/csd:organization
	  let $ou_uuid := 
	    if ($preserveUUIDs) 
	    then ($facilities[@entityID = $org/@entityID]/csd:otherID[@assigningAuthorityName = concat($dhis_url,"/api/organisationUnits") and @code="uuid"])[1]/text()
	    else ()
	  return 
	    if (functx:all-whitespace($ou_uuid)) 
	    then () 
	    else  <dxf:organisationUnit uuid="{$ou_uuid}"/>

	      
	return
	  <dxf:user name="{$name}" >
	    {if (functx:all-whitespace($dhis_id)) then () else  @id}
	    <dxf:surname>{$surname}</dxf:surname>
	    <dxf:firstName>{$firstname}</dxf:firstName>
	    {if (functx:all-whitespace($email)) then () else <dxf:email>{$email}</dxf:email>}
	    {if (functx:all-whitespace($phone)) then () else <dxf:phoneNumber>{$email}</dxf:phoneNumber>}
	    <dxf:userCredenitals>
	      <dxf:username>{$username}</dxf:username> 
	      <dxf:userRoles>{$urs}</dxf:userRoles>
	      <dxf:userAuthorityGroups>{$uags}</dxf:userAuthorityGroups>
	    </dxf:userCredenitals>
	    <dxf:organisationUnits>
	      {$p_orgs}
	    </dxf:organisationUnits>
	  </dxf:user>
        }
      </dxf:users>

      <dxf:userRoles>
	{
	  let $oids := 
	    for $dhis_url in distinct-values($provs/csd:record/@sourceDirectory)
	    let $namespace_uuid := util:uuid_generate($dhis_url,$util:namespace_uuid)
	    let $oid := concat('2.25.',util:hexdec(util:uuid_generate('rootoid',$namespace_uuid)))	
	    return $oid
	  
	  return 
	  for $oid in $oids
            let $ur_oid := concat($oid,'.1')
	    let $svs := svs_lsvs:get_single_version_value_set($ur_oid)
	    return
	      if (not(exists($svs)))
	      then ()
              else 
		for $val in $svs//svs:concept
		return 
		  <dxf:userRole name="{$val/@displayName}" id="{$val/@code}">
		    <dxf:description>{string($val/@displayName)}</dxf:description>
		  </dxf:userRole>
	}
      </dxf:userRoles>
      <dxf:userAuthorityGroups>
	{
	  let $oids := 
	    for $dhis_url in distinct-values($provs/csd:record/@sourceDirectory)
	    let $namespace_uuid := util:uuid_generate($dhis_url,$util:namespace_uuid)
	    let $oid := concat('2.25.',util:hexdec(util:uuid_generate('rootoid',$namespace_uuid)))	
	    return $oid
	  
	  return 
	  for $oid in $oids
            let $ag_oid := concat($oid,'.4')
	    let $svs := svs_lsvs:get_single_version_value_set($ag_oid)
	    return
	      if (not(exists($svs)))
	      then ()
              else 
		for $val in $svs//svs:concept
		return 
		  <dxf:userAuthorityGroup name="{$val/@displayName}" id="{$val/@code}">
		    <dxf:description>{string($val/@displayName)}</dxf:description>
		  </dxf:userAuthorityGroup>
	}
      </dxf:userAuthorityGroups>





      <dxf:organisationUnits>
        {	 
	  let $processOrgUnit := function($org) {
	    let $dhis_url := string($org/csd:record/@sourceDirectory)
	    let $dhis_uuid :=
	      if ($preserveUUIDs) 
	      then ($org/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="uuid"])[1]/text()
	      else ()
	    let $dhis_code := ($org/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="code"])[1]/text()
	   
	    let $level_code := string(($org/csd:codedType[@codingScheme=concat("urn:" ,$dhis_url,"/api/organisationUnitLevels")])[1]/@code)
	    let $level := 
	      if (not(functx:all-whitespace($level_code)))
	      then $level_code
	      else dxf2csd:get_level($doc,$org)

	    let $name := $org/csd:primaryName/text()

	    let $uuid :=
	      if ($preserveUUIDs)
	      then 
	        if (not(functx:all-whitespace($dhis_uuid)))
		then $dhis_uuid
	        else ()
	      else ()

	    let $entity_uuid := 
	      if (functx:all-whitespace($dhis_uuid))
	      then dxf2csd:extract_uuid_from_entityid(string($org/@entityID))
	      else string($dhis_uuid)


	    let $dhis_code := ($org/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="code"])[1]/text()

	    let $id_code := ($org/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="id"])[1]/text()
	    let $id :=
	      if (not(functx:all-whitespace($id_code)))
	      then $id_code
	      else dxf2csd:extract_id_from_entityid(string($org/@entityID)) 

	    let $created := dxf2csd:fixup_date($org/csd:record/@created)
	    let $lm := dxf2csd:fixup_date($org/csd:record/@updated)

	    let $porg_id := $org/csd:parent/@entityID
	    let $porg := $orgs[@entityID = $porg_id]
	    let $porg_dhis_uuid := ($porg/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="uuid"])[1]
	    let $parent :=
	      if (functx:all-whitespace($porg_id))
	      then () (: no parent :)
	      else if (not(functx:all-whitespace($porg_dhis_uuid)))
	      then <dxf:parent uuid="{$porg_dhis_uuid}"/>
  	      else <dxf:parent id="{dxf2csd:extract_id_from_entityid(string($porg_id))}"/>
	    let $avs :=
	      <dxf:attributeValues>
	        <dxf:attributeValue>
	  	  <dxf:attribute name="entityID"/>
		  <dxf:value>{$entity_uuid}</dxf:value>
	        </dxf:attributeValue>
	      </dxf:attributeValues>
		    
	    return 
	      <dxf:organisationUnit 
                level="{$level}"
		name="{$name}"
		shortName="{substring($name,1,50)}"
		id="{$id}"
		lastUpdated="{$lm}"
		created="{$created}"
		>
		{
		  if (($preserveUUIDs) and (not(functx:all-whitespace($uuid))))
		  then attribute uuid {$uuid}
		  else ()
	        }
		{ 
	          if (functx:all-whitespace($dhis_code))
		  then ()
	          else attribute code {$dhis_code}
		}
		{$parent}
		{$avs}
		<dxf:openingDate>1970-01-01</dxf:openingDate> 
	      </dxf:organisationUnit>
	  }	  

	  let $orgunit_funcs :=     
  	    for $orgUnit in $orgs
	    return function() {$processOrgUnit($orgUnit)}

	  return async:fork-join($orgunit_funcs)

	}
        {
	  let $processFac := function($fac) {
	    let $dhis_url := string($fac/csd:record/@sourceDirectory)
	    let $dhis_uuid := ($fac/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="uuid"])[1]
	    let $dhis_id := ($fac/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="id"])[1]
            let $dhis_code := ($fac/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="code"])[1]/text()
	    return 
  	      let $level := dxf2csd:get_level($doc,$fac)
	      let $name := $fac/csd:primaryName/text()
	      let $uuid := 
	        if (functx:all-whitespace($dhis_uuid))
	        then dxf2csd:extract_uuid_from_entityid(string($fac/@entityID))
	        else string($dhis_uuid)
              let $id := 
	        if (functx:all-whitespace($dhis_id))
	        then dxf2csd:extract_id_from_entityid(string($fac/@entityID)) 
	        else string($dhis_id)
	      let $created := dxf2csd:fixup_date($fac/csd:record/@created)
	      let $lm := dxf2csd:fixup_date($fac/csd:record/@updated)

	      (: in CSD we can have multiple "parents" but not so DXF.  We just choose the first one    :)
	      let $org_id := ($orgs[@entityID = ($fac/csd:organizations/csd:organization)[1]/@entityID ])[1]
	      let $org := $orgs[@entity_id = $org_id]
	      let $org_dhis_uuid := ($org/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="uuid"])[1]
	      let $parent := 
	        if (functx:all-whitespace($org_id))
	        then ()  (: no parent :)
	        else if (not(functx:all-whitespace($org_dhis_uuid)))
	          then <dxf:parent id="{$org_dhis_uuid}"/>
	          else <dxf:parent id="{dxf2csd:extract_id_from_entityid(string($org_id))}"/>
	      let $avs :=
	        <dxf:attributeValues>
  		  <dxf:attributeValue>  
		    <dxf:attribute name="entityID"/>
		    <dxf:value>{$uuid}</dxf:value>
		  </dxf:attributeValue>
	        </dxf:attributeValues>
	
	      return 
	        <dxf:organisationUnit 
                  level="{$level}"
		  name="{$name}"
		  shortName="{substring($name,1,50)}"
		  lastUpdated="{$lm}"
		  created="{$created}"
		  >
		  {
		    if (not(functx:all-whitespace($uuid)))
		    then attribute uuid {$uuid}
		    else ()
	          }
		  {
		    if (not(functx:all-whitespace($id)))
		    then attribute id {$id}
		    else ()
	          }
		  { 
		   if (functx:all-whitespace($dhis_code))
		   then ()
		   else attribute code {$dhis_code}
		  }
		 {$parent}
		 {$avs}
		 <dxf:openingDate>1970-01-01</dxf:openingDate> 
	       </dxf:organisationUnit>
	  }

	  let $fac_funcs :=     
  	    for $fac in $facilities
	    let $dhis_url := string($fac/csd:record/@sourceDirectory)
	    let $dhis_uuid := ($fac/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="uuid"])[1]
	    let $dhis_id := ($fac/csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="id"])[1]
	    let $org := 
	      if (functx:all-whitespace($dhis_uuid))
	      then ()
	      else ($orgs[./csd:otherID[@assigningAuthorityName=concat($dhis_url,"/api/organisationUnits") and @code="uuid" and ./text() = $dhis_uuid]])[1]
	    where not(exists($org)) 	    (: remove the facilities that have already been created from a DHIS2 org unit:)

	    return function() {$processFac($fac)}

	  return async:fork-join($fac_funcs)

	}
      </dxf:organisationUnits>


      <dxf:organisationUnitGroups>    
        {
	  
	  let $ou_group_schemes := distinct-values((
	    $req_ou_group_schemes,
	    for $oid in $ou_oids return  concat($oid,'.3')
	      ))
	    
	  for $ou_group_scheme in $ou_group_schemes
	  let $types :=  svs_lsvs:get_single_version_value_set(string($ou_group_scheme) )	  

	  let $org_unit_groups :=   
  	    for $concept in $types//svs:Concept
	    let $code := string($concept/@code)
	    let $scheme := string($concept/@codeSystem)
	    let $name := string($concept/@displayName)
	    return <dxf:organisationUnitGroup code="{$code}" name="{$name}" />

	  for $org_unit_group in $org_unit_groups
	  let $code := string($org_unit_group/@code)
	  let $scheme := string($org_unit_group/@codeSystem)
	  let $name := string($org_unit_group/@name)
	  let $short_name := substring(string($org_unit_group/@name),1,50)
	    return 
	    <dxf:organisationUnitGroup code="{$code}" name="{$name}" shortName="{$short_name}">
	      <dxf:organisationUnits>
		{
		  for $ent in ($facilities,$orgs)[./csd:codedType[@codingScheme = $scheme and @code = $code]]
		  let $uuid := dxf2csd:extract_uuid_from_entityid($ent/@entityID)
		  let $ent_name := $ent/csd:primaryName/text()
		  let $id := dxf2csd:extract_id_from_entityid(string($ent/@entityID)) 
		  return     
		     <dxf:organisationUnit uuid="{$uuid}" id="{$id}" name="{$ent_name}" />
		}
	      </dxf:organisationUnits>
	    </dxf:organisationUnitGroup>
	}
      </dxf:organisationUnitGroups>


      <dxf:organisationUnitLevels>
	{
	  
	  for $oid in $ou_oids
            let $level_oid := concat($oid,'.2')
	    let $svs := svs_lsvs:get_single_version_value_set($level_oid)
	    return
	      if (not(exists($svs)))
	      then ()
              else 
		for $val in $svs//svs:concept
		return 
		  <dxf:organisationUnitLevel name="{$val/@displayName}" id="{$val/@code}"/>

	}
       
      </dxf:organisationUnitLevels>

    </dxf:metaData>


let $out := 
  if ($zip)
  then archive:create(   <archive:entry>csd_dxf.xml</archive:entry>, serialize($dxf))
  else $dxf

return $out
Content-Type: text/xml
URN: urn:dhis2.org:csd:stored-function:dxf2csd

Description



 
    Updates the CSD document with a transform of the DHIS2 DXF.  
  

Definition

Source:
import module namespace dxf2csd = "http://dhis2.org/csd/dxf/2.0";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";


declare variable $careServicesRequest as item() external;


let $csd := dxf2csd:extract-directory($careServicesRequest/dxf,$careServicesRequest/oid)
let $doc_name := string($careServicesRequest/@resource)
let $doc := csd_dm:open_document($doc_name)
return  csd_dm:add($csd,$doc_name)

Content-Type: text/xml
URN: urn:dhis2.org:csd:stored-function:dxf2svs

Description



 
    Update SVS lists from a DHIS2 MetaData Export
  

Definition

Source:
import module namespace dxf2csd = "http://dhis2.org/csd/dxf/2.0";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace svs_lsvs = "https://github.com/openhie/openinfoman/svs_lsvs";

declare namespace dxf = "http://dhis2.org/schema/dxf/2.0";
declare namespace svs = "urn:ihe:iti:svs:2008";

declare variable $careServicesRequest as item() external;



let $version := concat(year-from-date(current-date()),'.',month-from-date(current-date()),'.',day-from-date(current-date()))

return (
  let $list_name := "DHIS2 Organization Unit Levels"
  let $id := dxf2csd:oid_orgtype($careServicesRequest/oid/text())
  let $svs := 
  <svs:ValueSet id="{$id}" version="{$version}" displayName="{$list_name}">
    <svs:ConceptList xml:lang="en-US">
      {
	for $level in $careServicesRequest/dxf/dxf:metaData/dxf:organisationUnitLevels/dxf:organisationUnitLevel
	return   <svs:Concept code="{$level/@level}" displayName="{$level/@name}" codeSystem="{$id}"/>
      }
    </svs:ConceptList>
  </svs:ValueSet>
  return svs_lsvs:insert($svs)
  ,
  let $list_name := "DHIS2 User Role List"
  let $id := dxf2csd:oid_hwtype($careServicesRequest/oid/text())
  let $svs := 
  <svs:ValueSet id="{$id}" version="{$version}" displayName="{$list_name}">
    <svs:ConceptList xml:lang="en-US">
      {
        for $role in $careServicesRequest/dxf/dxf:metaData/dxf:userRoles/dxf:userRole
        return   <svs:Concept code="{$role/@id}" displayName="{$role/@name}" codeSystem="{$id}"/>
      }
    </svs:ConceptList>
  </svs:ValueSet>
  return svs_lsvs:insert($svs)
)

Content-Type: text/xml
URN: urn:dhis.org:extract_from_dxf:v2.19

Description



    
This extracts all organisation units matching the given facility conditions as a CSD facility entity.  
It also extracts all organisation units a CSD organization entity.  
In the case that a CSD facility entity is created, it will have as an organizational association to it's corresponding organization entity.
These two entities will have distinct entity IDs (UUIDs)

This Also creates SVS for relevant terminologies (e.g. Organisation Unit Groups and Levels )

Imports: DHIS2 metadata export of Organsation Units, Organisation Unit Group,  Organisation Unit Group Set, Organization Unit Level from DHIS2 2.19

This optionally processes DHIS2 Users as health workers (CSD Providers).
In order to do so, you will need to have included Users, UserRoles and UserAuthorityGroups in your DXF2 meta-data extract.

    
  

Definition

Source:
declare namespace csd = "urn:ihe:iti:csd:2013"; 

declare namespace svs = "urn:ihe:iti:svs:2008";
declare namespace dxf = "http://dhis2.org/schema/dxf/2.0";
declare namespace adx = "http://www.openhie.org/adx";

import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace svs_lsvs = "https://github.com/openhie/openinfoman/svs_lsvs";
import module namespace functx = "http://www.functx.com";
import module namespace util = "https://github.com/openhie/openinfoman-dhis/util";
import module namespace async = "http://basex.org/modules/async";

declare variable $careServicesRequest as item() external; 



let $dhis_url := replace($careServicesRequest/URL/text(),'/+$','')
let $namespace_uuid := util:uuid_generate($dhis_url,$util:namespace_uuid)

let $dxf := $careServicesRequest/dxf
let $facility_group_codes := $careServicesRequest/groupCodes/groupCode/text()
let $facility_levels := $careServicesRequest/levels/level/text()
let $do_hws :=  ($careServicesRequest/usersAreHealthWorkers/text() = '1')
let $do_srvcs :=  ($careServicesRequest/dataelementsAreServices/text() = '1')

let $t_oid := $careServicesRequest/oid/text()  
let $oid :=      
  if (not(functx:all-whitespace($t_oid)))
  then $t_oid
  else 
    (:generate it from the uuid :)
    concat('2.25.',util:hexdec(util:uuid_generate('rootoid',$namespace_uuid)))

let $orgUnits := $dxf/dxf:metaData/dxf:organisationUnits/dxf:organisationUnit
let $orgGroups := $dxf/dxf:metaData/dxf:organisationUnitGroups/dxf:organisationUnitGroup
let $userRoles := $dxf/dxf:metaData/dxf:userRoles
let $dataSets := $dxf/dxf:metaData/dxf:dataSets
let $dataElements := $dxf/dxf:metaData/dxf:dataElements
let $catCombos := $dxf/dxf:metaData/dxf:categoryCombos
  
let $doc_name := string($careServicesRequest/@resource)
let $doc := csd_dm:open_document($doc_name)
let $org_dir := $doc/csd:CSD/csd:organizationDirectory
let $fac_dir := $doc/csd:CSD/csd:facilityDirectory
let $prov_dir := $doc/csd:CSD/csd:providerDirectory
let $srvc_dir := $doc/csd:CSD/csd:serviceDirectory

let $now := current-dateTime()



(: cache some node calculations :)
let $org_otherids := $org_dir/csd:organization/csd:otherID[@code='id']
let $orggroups_by_ou := $orgGroups/dxf:organisationUnits/dxf:organisationUnit

let $process_orgunit := function($orgUnit) {
  let $level := xs:integer($orgUnit/@level)
  let $id := $orgUnit/@id
  let $uuid := string($orgUnit/@uuid)

  let $displayName:=string($orgUnit/@name)
  let $org_code:=string($orgUnit/@code)
  let $pid:=string($orgUnit/dxf:parent/@id)

  let $lm := util:fixup_date($orgUnit/@lastUpdated)
  let $created := util:fixup_date($orgUnit/@created)
  let $groups := $orggroups_by_ou[@id = $id]/../..  (:clause should expect to match more than one. go to grandparent orgUnitGroup's :)
(:  let $groups := $orgGroups[./dxf:organisationUnits/dxf:organisationUnit[@id = $id]] :)
  let $group_codes := $groups/@code

  (:if there is an existing CSD UUID / entityID in DHIS2 we should keep it to referencer the org unit :)
  let $entity_uuid :=((($orgUnit/dxf:attributeValues/dxf:attributeValue[./dxf:attribute[@name='entityID']])[1])/dxf:value[1])/text()
  let $facEntityID := concat("urn:uuid:",util:uuid_generate(concat('facility:',$id),$namespace_uuid))
  let $orgEntityID :=
    if (not(functx:all-whitespace($entity_uuid)))
    then concat("urn:uuid:",$entity_uuid)
    else if (not(functx:all-whitespace($uuid)))
    then concat("urn:uuid:",$uuid)  
    else  concat("urn:uuid:",util:uuid_generate(concat('organization:',$id),$namespace_uuid))

          
  (:the parent org may be:
     1) in the dxf document being imported (highest precedence)
     2) in the destination csd document
     3) nowhere 

    in the case of 1) we want the parent's csd entity id to match the entity id of the parent org unit being imported
       case 1) happens if $porg is found
    in the case of 2) we want to use the parent id of the 
       in case is if $porg is not found but there is a csd:organization with the correct entity if in the dest. doc
    in the case of 3) we want to put it under our global root element for the import
    :)
    
  let $porg := ($orgUnits[@id=$pid])[1]
  let $parentEntityID :=     
    if (exists($porg))  (: there is a matching parent organization in the imported dxf document :)
    then  
      (:see if there is a DHIS2 attribute for the csd_entity ID :)
      let $p_entity_uuid :=((($porg/dxf:attributeValues/dxf:attributeValue[./dxf:attribute[@name='entityID']])[1])/dxf:value[1])/text()
      let $p_uuid := string($porg/@uuid)
      return
        if (not(functx:all-whitespace($p_entity_uuid))) 
        then concat("urn:uuid:",$p_entity_uuid)
	else if (not(functx:all-whitespace($p_uuid)))
        then concat("urn:uuid:",$p_uuid)
        else concat("urn:uuid:",util:uuid_generate(concat('organization:',$pid),$namespace_uuid))
    else (: we didn't find a matching parent organization in the dxf document, but may already be in target:)
      let $peorg := ($org_otherids[./text() = $pid])[1]/..  (: get the parent csd:organization element :)
(:      let $peorg := ($org_dir/csd:organization[./csd:otherID[@code='id' and ./text() = $pid]])[1] :)
      return
	if (exists($peorg))
        then $peorg/@entityID
        else ()

(:   let $puuid :=
     if (exists($porg))
     then  $porg/@uuid
     else if (exists($peorg))
     then  $peorg/@entityID
     else false
:)	  

  let $mainname := <csd:primaryName>{$displayName}</csd:primaryName>

  (:set up local identifiers:)
  let $other_ids := (
    <csd:otherID assigningAuthorityName="{$dhis_url}/api/organisationUnits" code="id">{string($id)}</csd:otherID>
    ,
    if (not(functx:all-whitespace($org_code)))
    then <csd:otherID assigningAuthorityName="{$dhis_url}/api/organisationUnits" code="code">{string($org_code)}</csd:otherID>
    else ()
    ,
    if (not(functx:all-whitespace($uuid)))
    then <csd:otherID assigningAuthorityName="{$dhis_url}/api/organisationUnits" code="uuid">{string($uuid)}</csd:otherID>
    else ()
    )

  (:set up codes:)
  let $level_code := <csd:codedType code="{$level}" codingScheme="urn:{$dhis_url}/api/organisationUnitLevels"/>
  let $group_cts :=
    for $group_code in $group_codes
    return <csd:codedType codingScheme="urn:{$dhis_url}/api/organisationUnitGroups" code="{$group_code}" />

  let $geo_data :=
     (
       util:get_geocode($orgUnit)
       ,util:get_shape($orgUnit)
     )
  let $name := <csd:primaryName>{string($orgUnit/@name)}</csd:primaryName>
  let $record :=  <csd:record created="{$created}" updated="{$lm}" status="Active" sourceDirectory="{$dhis_url}"/>
    

  (:first we extract all org units matching our facility conditions :)
  let $fac_srvcs :=
    if (not($do_srvcs))
    then ()
    else 
      (: get data sets that are associated to this org unit :)
      let $dsets := $dataSets/dxf:dataSet[dxf:organisationUnits/dxf:organisationUnit/@id = $id]
      return 
	(
	  (:each data set is a service :)
	  for $ds in $dsets
	  let $ds_id := string($ds/@id)
	  let $ds_uuid := string($ds/@uuid)
	  let $ds_entityID :=
	    if (not(functx:all-whitespace($ds_uuid)))
	    then concat("urn:uuid:",$ds_uuid)  
	    else  concat("urn:uuid:",util:uuid_generate(concat('service:',$ds_id),$namespace_uuid))
	  return <csd:service entityID="{$ds_entityID}"/>    
	  ,
	  (:each data element is a service :)
	  let $des :=
            for $dset in $dsets
	    return $dataElements/dxf:dataElement[@id = $dset/dxf:dataElements/dxf:dataElement/@id]
	  return 
            for $de in  $des
	    let $de_id := $de/@id
	    let $de_uuid := $de/@uuid
	    let $srvc_entity_id := 
	      if (not(functx:all-whitespace($de_uuid)))
	      then concat("urn:uuid:",$de_uuid)
	      else concat("urn:uuid:",util:uuid_generate(concat('service:',$de_id),$namespace_uuid))
	    return <csd:service entityID="{$srvc_entity_id}"/>
	  )

  let $fac_entity :=
    if (($group_codes = $facility_group_codes) or ( $level = $facility_levels)) 
    then
      <csd:facility entityID="{$facEntityID}">
	{$other_ids}
	{$level_code}
	{$group_cts}
	{$mainname}
	{$geo_data}
	<csd:organizations><csd:organization entityID="{$orgEntityID}">{$fac_srvcs}</csd:organization></csd:organizations>
	{$record}
      </csd:facility>
    else ()

  (:next we create an organization for each organisation unit.

    NOTE: this means that each organisation unit which matches as a facility will have two CSD 
          entities created a facility and an organization.  These two entities will have distinct
          UUIDs.  
   :)
     (:Should put in a CP to point geo codes for orgs as service delivery area :)

  let $org_entity :=
  <csd:organization entityID="{$orgEntityID}">
      {$other_ids}
      {$level_code}
      {$group_cts}
      {$mainname}
      {$geo_data}
      <csd:parent  entityID="{$parentEntityID}"/>
      {$record}
    </csd:organization>
  return ($org_entity,$fac_entity)

}


let $entities :=  
  let $orgunit_funcs :=     
    for $orgUnit in $orgUnits
    return function() {$process_orgunit($orgUnit)}
  return async:fork-join($orgunit_funcs)



let $process_users := function($user) {  
    let $id := string($user/@id)
    let $entityID := concat("urn:uuid:",util:uuid_generate(concat('provider:',$id),$namespace_uuid))
    let $ur_oid := concat($oid,'.1')
    let $ag_oid := concat($oid,'.4')
    let $uuid := string($user/@uuid)
    let $code:=string($user/dxf:userCredentials/@code)
    let $fore := $user/dxf:firstName/text()
    let $sur := $user/dxf:surname/text()
    let $email := $user/dxf:email/text()
    let $phone := $user/dxf:phoneNumber/text()
    let $lm := util:fixup_date($user/@lastUpdated)
    let $created := util:fixup_date($user/@created)
    let $urs := $user/dxf:userCredentials/dxf:userRoles/dxf:userRole
    let $ags := $user/dxf:userCredentials/dxf:userAuthorityGroups/dxf:userAuthorityGroup


    let $entity_uuid :=((($user/dxf:attributeValues/dxf:attributeValue[./dxf:attribute[@name='entityID']])[1])/dxf:value[1])/text()
    let $provEntityID :=
      if (not(functx:all-whitespace($entity_uuid)))
      then concat("urn:uuid:",$entity_uuid)
      else if (not(functx:all-whitespace($uuid)))
      then concat("urn:uuid:",$uuid)  
      else  concat("urn:uuid:",util:uuid_generate(concat('provider:',$id),$namespace_uuid))

    return 
    <csd:provider entityID="{$provEntityID}">
      <csd:otherID assigningAuthorityName="{$dhis_url}/api/users" code="id">{$id}</csd:otherID>
      {
	if (not(functx:all-whitespace($code)))
	then <csd:otherID assigningAuthorityName="{$dhis_url}/api/users" code="code">{$code}</csd:otherID>
        else ()
      }
      {
	if (not(functx:all-whitespace($uuid)))
	then <csd:otherID assigningAuthorityName="{$dhis_url}/api/users" code="uuid">{$uuid}</csd:otherID>
	else ()
      }
      {
	for $ag in $ags
	return 
	<csd:codedType code="{$ag/@id}" codingScheme="{$ag_oid}"/>
      }
      {
	for $ur in $urs
	return 
	<csd:codedType code="{$ur/@id}" codingScheme="{$ur_oid}"/>
      }
      {
	if (count(($urs,$ags)) = 0) 
	  then <csd:codedType code="NOROLE" codingScheme="{$ur_oid}"/>
	else ()

      }
      <csd:demographic>
	<csd:name>
	  <csd:commonName>{$sur}, {$fore}</csd:commonName>
	  <csd:forename>{$fore}</csd:forename>
	  <csd:surname>{$sur}</csd:surname>
	</csd:name>
	{
	  if ($phone) then
	  <csd:contactPoint>
	    <csd:codedType code="BP" codingScheme="urn:ihe:iti:csd:2013:contactPoint">{$phone}</csd:codedType>
	  </csd:contactPoint>
        else ()
	}
	{
	  if ($email) then
	  <csd:contactPoint>
	    <csd:codedType code="EMAIL" codingScheme="urn:ihe:iti:csd:2013:contactPoint">{$email}</csd:codedType>
	  </csd:contactPoint>
	else ()
	}
      </csd:demographic>
      {
	let $torgs := $user/dxf:organisationUnits/dxf:organisationUnit
	let $orgs := 
          for $torg in $torgs 
	  let $tid :=  $torg/@id
	  let $torg1 := ($orgUnits[@id=$tid])[1]
	  let $entity_uuid :=((($torg1/dxf:attributeValues/dxf:attributeValue[./dxf:attribute[@name='entityID']])[1])/dxf:value[1])/text()

    	  let $orgEntityID :=
	     if (not(functx:all-whitespace($entity_uuid)))
	     then concat("urn:uuid:" , $entity_uuid)
	     else concat("urn:uuid:",util:uuid_generate(concat('organization:',string($torg/@id)),$namespace_uuid))
          where  (exists($entities[@entityID = $orgEntityID]) or exists( $org_dir/csd:organization[@entityID = $orgEntityID]))
	  return <csd:organization entityID="{$orgEntityID}"/>
	  
	return 
	  if (count($orgs) > 0) then
	  <csd:organizations>{$orgs}</csd:organizations>
	  else ()
      }
      {
	let $tfacs := $user/dxf:organisationUnits/dxf:organisationUnit
	let $facs := 
          for $tfac in $tfacs 
	  let $tfac_id := $tfac/@id
    	  let $facEntityID := concat("urn:uuid:",util:uuid_generate(concat('facility:',string($tfac_id)),$namespace_uuid))
	  let $fac_srvcs := 
	    if (not($do_srvcs))
	    then ()
	    else 
	      for $r in $urs
	      let $r_id := $r/@id
	      let $role := ($userRoles/dxf:userRole[@id = $r_id])[1]
	      for $ds_ref in $role/dxf:dataSets/dxf:dataSet
	        let $ds_id := $ds_ref/@id
		let $ds := ($dataSets/dxf:dataSet[@id = $ds_id])[1]
		let $ds_orgunit := $ds/dxf:organisationUnits/dxf:organisationUnit[@id = $tfac_id]
		for $de in  $ds_orgunit/../../dxf:dataElements/dxf:dataElement
		  let $de_id := $de/@id
		  let $de_uuid := $de/@uuid
		  let $srvc_entity_id := 
		    if (not(functx:all-whitespace($de_uuid)))
		    then concat("urn:uuid:",$de_uuid)
		    else concat("urn:uuid:",util:uuid_generate(concat('service:',$de_id),$namespace_uuid))
	          return <csd:service entityID="{$srvc_entity_id}"/>
	  where  (exists($entities[@entityID = $facEntityID]) or exists( $org_dir/csd:facility[@entityID = $facEntityID]))
	  return <csd:facility entityID="{$facEntityID}">{$fac_srvcs}</csd:facility>
	  
	return 
	  if (count($facs) > 0) then
	  <csd:facilities>{$facs}</csd:facilities>
	  else ()
      }
    <csd:record created="{$created}" updated="{$lm}" status="106-001" sourceDirectory="{$dhis_url}"/>
    </csd:provider>
}


let $process_dataelements := function($de) {
    let $de_id := string($de/@id)
    let $name := string($de/@name)
    let $code := string($de/@code)
(:    let $entityID := concat("urn:uuid:",util:uuid_generate(concat('service:',$de_id),$namespace_uuid)) :)
    let $cat_id := $de/dxf:categoryCombo/@id
    let $cc :=  ($catCombos/dxf:categoryCombo[@id = $cat_id])[1]
    let $cc_code := string($cc/@code)
    let $created := util:fixup_date($de/@created)
    let $lm := util:fixup_date($de/@lastUpdated)

    let $uuid := string($de/@uuid)
    let $entity_uuid :=((($de/dxf:attributeValues/dxf:attributeValue[./dxf:attribute[@name='entityID']])[1])/dxf:value[1])/text()
    let $srvcEntityID :=
      if (not(functx:all-whitespace($entity_uuid)))
      then concat("urn:uuid:",$entity_uuid)
      else if (not(functx:all-whitespace($uuid)))
      then concat("urn:uuid:",$uuid)  
      else  concat("urn:uuid:",util:uuid_generate(concat('service:',$de_id),$namespace_uuid))
 

(:
    let $cc_id := $cc/@id
    let $cc_oid := string-join(for $cp in string-to-codepoints(string($cc_id)) return string($cp))
:)  
    let $disaggregatorSet := 
      for $disag in  $cc/dxf:categories/dxf:category
      let $disag_id := $disag/@id
      let $disag_code := $disag/@code
      let $disag_oid := string-join(for $cp in string-to-codepoints(string($disag_code)) return string($cp))
      let $doid :=  concat($oid , '.6.' , $disag_oid )
      let $attr_display:= string($disag/@name)
      let $attr := $disag_code
	(:need to be able to make it into an attribute for compatibility with ADX :)
(:
        try {
	  attribute {xs:string($disag_code)} {()}
	} catch * {
	  ''
	}
:)
      let $attr_name := string($attr)
      where ( not(functx:all-whitespace($attr_name))  and  not($attr_display = 'default')) 
      return <adx:disaggregator  id="{$doid}" refid="{$disag_id}" code="{$attr_name}">{$attr_display}</adx:disaggregator>

    return 
      <csd:service entityID="{$srvcEntityID}">
	<csd:primaryName>{$name}</csd:primaryName>
	<csd:otherID assigningAuthorityName="{$dhis_url}/api/dataElements" code="id">{$de_id}</csd:otherID>
	{     
	  if (not(functx:all-whitespace($uuid)))
	  then <csd:otherID assigningAuthorityName="{$dhis_url}/api/dataElements" code="uuid">{string($uuid)}</csd:otherID>
	  else ()
	}
	{ if (not(functx:all-whitespace($code)))
	  then <csd:otherID assigningAuthorityName="{$dhis_url}/api/dataElements" code="code">{$code}</csd:otherID>
	  else ()
	}

	{
	  if (count($disaggregatorSet) = 0) 
	  then ()
	  else 
	    <csd:extension urn="urn:http://www.openhie.org/adx" type="disaggregators">
	      <adx:disaggregatorSet id="{$cat_id}" code="{$cc_code}">
		{$disaggregatorSet}
	      </adx:disaggregatorSet>
	    </csd:extension>
	}
	{
	   <csd:extension urn="urn:http://www.dhis2.org/api/dataElement">
	     <dxf:dataElement shortname="{$de/@shortName}">
	       {$de/dxf:aggregationType}
	       {$de/dxf:dataDimension}
	       {$de/dxf:domainType}
	       {$de/dxf:type}
	       {$de/dxf:numberType}
	       {$de/dxf:aggregationOperator}
	       {$de/dxf:url}
	       {$de/dxf:zeroIsSignificant}
	     </dxf:dataElement>
	   </csd:extension>
	}

	<csd:record 
          created="{util:fixup_date($de/@created)}" 
          updated="{util:fixup_date($de/@lastUpdated)}" 
          status="Active" 
	  sourceDirectory="{$dhis_url}"/>        
      </csd:service>

}


let $process_dataset := function($ds) {
    let $ds_id := string($ds/@id)
    let $des := $ds/dxf:dataElements/dxf:dataElement
    let $name := string($ds/@name)
    let $s_name := string($ds/@shortName)
    let $pt := string($ds/dxf:periodType) 
    let $code := string($ds/@code)

    let $uuid := string($ds/@uuid)
    let $entityID :=
      if (not(functx:all-whitespace($uuid)))
      then concat("urn:uuid:",$uuid)  
      else  concat("urn:uuid:",util:uuid_generate(concat('service:',$ds_id),$namespace_uuid))


    let $cat_id := $ds/dxf:categoryCombo/@id
    let $cc :=  ($catCombos/dxf:categoryCombo[@id = $cat_id])[1]
    let $cc_code := string($cc/@code)

    let $disaggregatorSet := 
      for $disag in  $cc/dxf:categories/dxf:category
      let $disag_id := $disag/@id
      let $disag_code := $disag/@code
      let $disag_oid := string-join(for $cp in string-to-codepoints(string($disag_code)) return string($cp))
      let $doid :=  concat($oid , '.6.' , $disag_oid )
      let $attr_display:= string($disag/@name)
      let $attr := $disag_code
      let $attr_name := string($attr)
      where ( not(functx:all-whitespace($attr_name))  and  not($attr_display = 'default')) 
      return <adx:disaggregator  id="{$doid}"  code="{$attr_name}">{$attr_display}</adx:disaggregator>
 
    return 
      <csd:service entityID="{$entityID}">
	<csd:primaryName>{$name}</csd:primaryName>
	<csd:otherID assigningAuthorityName="{$dhis_url}/api/dataSets" code="id">{$ds_id}</csd:otherID>
	{     
	  if (not(functx:all-whitespace($uuid)))
	  then <csd:otherID assigningAuthorityName="{$dhis_url}/api/dataSets" code="uuid">{string($uuid)}</csd:otherID>
	  else ()
	}
	{ if (not(functx:all-whitespace($code)))
	  then <csd:otherID assigningAuthorityName="{$dhis_url}/api/dataSets" code="code">{$code}</csd:otherID>
	  else ()
	}
	{
	  if (count($disaggregatorSet) = 0) 
	  then ()
	  else 
	    <csd:extension urn="urn:http://www.openhie.org/adx" type="disaggregators">
	      <adx:disaggregatorSet id="{$cat_id}" code="{$cc_code}">
		{$disaggregatorSet}
	      </adx:disaggregatorSet>
	    </csd:extension>
	}

	{
	  if (count($des) = 0) 
	  then ()
	  else 
	    <csd:extension urn="urn:http://www.openhie.org/adx" type="dataSet">
	      {
              for $de in $des
	      let $de_id := string($de/@id)
	      let $uuid := string($de/@uuid)
	      let $entity_uuid :=((($de/dxf:attributeValues/dxf:attributeValue[./dxf:attribute[@name='entityID']])[1])/dxf:value[1])/text()
	      let $srvcEntityID :=
		if (not(functx:all-whitespace($entity_uuid)))
		then concat("urn:uuid:",$entity_uuid)
	        else if (not(functx:all-whitespace($uuid)))
		then concat("urn:uuid:",$uuid)  
	        else  concat("urn:uuid:",util:uuid_generate(concat('service:',$de_id),$namespace_uuid))
 	      return <csd:service entityID="{$srvcEntityID}"/>
	      }
	    </csd:extension>
	}

	<csd:record 
          created="{util:fixup_date($ds/@created)}" 
          updated="{util:fixup_date($ds/@lastUpdated)}" 
          status="Active" 
	  sourceDirectory="{$dhis_url}"/>        
      </csd:service>


(:    let $entityID := concat("urn:uuid:",util:uuid_generate(concat('service:',$de_id),$namespace_uuid)) :)

}




let $process_categories := function($category) {
    let $disag_code := string($category/@code)
    let $disag_oid := string-join(for $cp in string-to-codepoints(string($disag_code)) return string($cp))      
    let $disag_date := xs:dateTime(substring(string($category/@lastUpdated),1,19))
    let $disag_name := string($category/@name)
    let $disag_id := string($category/@id)
    let $svs_vals_0 :=    
      for $catOption in $category/dxf:categoryOptions/dxf:categoryOption
      let $disag_opt_date := xs:dateTime(substring(string($catOption/@lastUpdated),1,19))
      let $disag_opt_name := string($catOption/@name)
      let $date := max(($disag_date,$disag_date,$disag_opt_date))
      where (not((functx:all-whitespace($disag_opt_name)) )) 
      return <svs:Concept code="{$disag_opt_name}" displayName="{$disag_opt_name}" codeSystem="{$dhis_url}/adx/disaggregators/{$disag_code}" lu="{$date}"/>

    let $date := max(( for $d in $svs_vals_0/@lu return xs:dateTime($d)))
    let $svs_vals_1 := functx:remove-attributes-deep($svs_vals_0,'lu')
    
    let $oid :=  concat($oid , '.6.' , $disag_oid)	

    let $attr := $disag_code

    let $svs_doc :=
      <svs:ValueSet  xmlns:svs="urn:ihe:iti:svs:2008" id="{$oid}" version="{$date}" displayName="[ADX {$disag_code}] Disaggregator for {$disag_name}. ( {$disag_id
} ) Published {$date}.  ">
	<svs:ConceptList xml:lang="en-US" >{$svs_vals_1}</svs:ConceptList>
      </svs:ValueSet>
    where ( not(functx:all-whitespace($disag_code))  and not($disag_name = 'default'))   
    return $svs_doc
}
	

(: create dhis2 users as health workers/providers if requested :)

let $providers := 
  if (not($do_hws))
  then ()
  else 
    let $prov_funcs := 
      for $user in $dxf/dxf:metaData/dxf:users/dxf:user 
      return function() {$process_users($user)}
    return async:fork-join($prov_funcs)


(: Create CSD Services for DHIS2 Data Elements :) 


let $srvcs := 
  if (not($do_srvcs))
  then ()
  else 
    (
    let $de_funcs := 
      for $de in ($dataElements/dxf:dataElement)
      return function() {$process_dataelements($de)}
    return async:fork-join($de_funcs)
    ,
    let $ds_funcs := 
      for $ds in $dataSets/dxf:dataSet
      return function() {$process_dataset($ds)}
    return async:fork-join($ds_funcs)
    )


(: Create an SVS list for each of the disaggregator sets in  the service :)
let $categories := $dxf/dxf:metaData/dxf:categories/dxf:category

let $svs_srvcs := 
  if (not($do_srvcs))
  then ()
  else
(:    for $category in $categories :)
    let $cat_funcs := 
       for $category in $categories[ @id  = $catCombos/dxf:categoryCombo/dxf:categories/dxf:category/@id]
       return function() {$process_categories($category)}
    return async:fork-join($cat_funcs)



(: Create an SVS list for the Org Unit Levels :)
	
let $level_oid := concat($oid,'.2')
let $levels := $dxf/dxf:metaData/dxf:organisationUnitLevels/dxf:organisationUnitLevel
let $level_version := max(for $date in $levels/@lastUpdated return xs:dateTime(util:fixup_date($date)))
let $svs_levels :=
  <svs:ValueSet  xmlns:svs="urn:ihe:iti:svs:2008" id="{$level_oid}" version="{$level_version}" displayName="Organisation Unit Levels for DHIS at {$dhis_url}">
    <svs:ConceptList xml:lang="en-US" >
      {
	for $level in $levels
	return <svs:Concept code="{$level/@level}" displayName="{$level/@name}" codeSystem="{$dhis_url}/api/organisationUnitLevels" />
      }
    </svs:ConceptList>
  </svs:ValueSet>


(: Create an SVS list for the Org Unit Groups :)
let $group_oid := concat($oid,'.3')
let $group_version := max(for $date in $orgGroups/@lastUpdated return xs:dateTime(util:fixup_date($date)))
let $svs_groups :=
  <svs:ValueSet  xmlns:svs="urn:ihe:iti:svs:2008" id="{$group_oid}" version="{$group_version}" displayName="Organisation Unit Groups at {$dhis_url}">
    <svs:ConceptList xml:lang="en-US" >
      {
	for $group in $orgGroups
	return <svs:Concept code="{$group/@code}" displayName="{$group/@name}" codeSystem="{$dhis_url}/api/organisationUnitGroups" />
      }
    </svs:ConceptList>
  </svs:ValueSet>



let $svs_providers := 
  if (not($do_hws))
  then ()
  else 
    let $urs := $dxf/dxf:metaData/dxf:userRoles/dxf:userRole
    let $ags := $dxf/dxf:metaData/dxf:userAuthorityGroups/dxf:userAuthorityGroup
    let $urs_version := max(for $date in $urs/@lastUpdated return xs:dateTime(util:fixup_date($date)))
    let $ags_version := max(for $date in $ags/@lastUpdated return xs:dateTime(util:fixup_date($date)))
    let $ur_oid := concat($oid,'.1')
    let $ag_oid := concat($oid,'.4')
    let $svs_urs := 
      <svs:ValueSet  xmlns:svs="urn:ihe:iti:svs:2008" id="{$ur_oid}" version="{$group_version}" displayName="User Role at {$dhis_url}">
	<svs:ConceptList xml:lang="en-US" >
	  {
	    for $ur in ($urs,<userRole id='NOROLE' name='No Role'/>)
	    return <svs:Concept code="{$ur/@id}" displayName="{$ur/@name}" codeSystem="{$dhis_url}/api/userRoles" />
	  }
	</svs:ConceptList>
      </svs:ValueSet>
    let $svs_ags := 
      <svs:ValueSet  xmlns:svs="urn:ihe:iti:svs:2008" id="{$ag_oid}" version="{$group_version}" displayName="Authority Groups at {$dhis_url}">
	<svs:ConceptList xml:lang="en-US" >
	  {
	    for $ag in $ags
	    return <svs:Concept code="{$ag/@id}" displayName="{$ag/@name}" codeSystem="{$dhis_url}/api/userAuthorityGroups" />
	  }
	</svs:ConceptList>
      </svs:ValueSet>


    return ($svs_urs, $svs_ags)

let $svs_docs := ($svs_levels,$svs_groups,$svs_providers,$svs_srvcs)

 
(:Insert everything we generated into the database :)

return (
  for $entity in ( $entities,$providers, $srvcs)
  let $id := $entity/@entityID
  return 
    if (local-name($entity) = 'facility')
    then 
      let $existing_fac := $fac_dir/csd:facility[@entityID = $id]
      return
        if (not(exists($existing_fac)))
        then (insert node $entity into $fac_dir)
        else (replace node $existing_fac with $entity)
    else if (local-name($entity) = 'organization')
    then
      let $existing_org := $org_dir/csd:organization[@entityID = $id]
      return
        if (not(exists($existing_org)))
        then (insert node $entity into $org_dir)
        else (replace node $existing_org with $entity)
    else if (local-name($entity) = 'provider')
    then
      let $existing_prov := $prov_dir/csd:provider[@entityID = $id]
      return
        if (not(exists($existing_prov)))
        then (insert node $entity into $prov_dir)
        else (replace node $existing_prov with $entity)
    else if (local-name($entity) = 'service')
    then
      let $existing_srvc := $srvc_dir/csd:service[@entityID = $id]
      return
        if (not(exists($existing_srvc)))
        then (insert node $entity into $srvc_dir)
        else (replace node $existing_srvc with $entity)

    else (insert node $entity into /)
    

  ,
  for $svs_doc in $svs_docs return svs_lsvs:insert($svs_doc) 

)
Content-Type: text/csv
URN: urn:openhie.org:openinfoman-rapidpro:get_csv_for_import

Description



 
    Creates selection menu of all the CSD organizations and faciltiies with a specified parent.  Designed as part of heierarchical facility selection menus in RapidPro webhooks.
  

Definition

Source:
import module namespace oi_csv =  "https://github.com/openhie/openinfoman/adapter/csv";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

oi_csv:get_serialized(/,$careServicesRequest)
Content-Type: application/json
URN: urn:openhie.org:openinfoman-rapidpro:get_json_for_import

Description



 
    Get JSON representation of CSD for import to RapidPro via API
  

Definition

Source:
import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";

declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;



let $careServicesSubRequest :=  
  <csd:careServicesRequest>
    <csd:function  urn="urn:ihe:iti:csd:2014:stored-function:provider-search" >
      <csd:requestParams/>
    </csd:function>
  </csd:careServicesRequest> 

let $providers := csr_proc:process_CSR_stored_results( /. , $careServicesSubRequest)


let $contacts :=  
  <json type='object'>
    <contacts type="array">
    {
      for $provider in  $providers/csd:providerDirectory/csd:provider
      let $uuid := lower-case(string($provider/@entityID))
      let $name := ($provider/csd:demographic/csd:name/csd:commonName)[1]/text()
      let $tels := $provider/csd:demographic/csd:contactPoint/csd:codedType[@code="BP" and  @codingScheme="urn:ihe:iti:csd:2013:contactPoint"]
      let $tel_1 := $tels[1]/text()
      let $tel_2 := $tels[2]/text()
      let $tel_3 := $tels[3]/text()
      return 
	if (true()) (:  ($uuid and $name)  :)
       then 
         <_  type="object">
	   <name>{$name}</name>
	   <urns type="array">
             { if ($tel_1) then   <_ type='string'>tel:{$tel_1}</_> else ()} 
             { if ($tel_2) then   <_ type='string'>tel:{$tel_2}</_> else ()} 
             { if ($tel_3) then   <_ type='string'>tel:{$tel_3}</_> else ()} 
	   </urns>
	   <fields type="object">
             <globalid>{$uuid}</globalid>
	   </fields>
         </_>
       else ()
    }
    </contacts>
  </json>


return json:serialize($contacts,map{"format":"direct"})  
Content-Type: text/html
URN: urn:openhie.org:openinfoman-rapidpro:phone_stats

Description



 
    Statistics on phone numbers
  

Definition

Source:
import module namespace functx = "http://www.functx.com";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;


let $country_code := '+231'
let $cellcom_code := '77'

let $get_clean_phones := function($provider) {
  let $all_phones := $provider/csd:demographic/csd:contactPoint/csd:codedType[@code = "BP" and @codingScheme="urn:ihe:iti:csd:2013:contactPoint"]
  let $clean_phones :=
    for $phone in $all_phones
    let $raw_phones := tokenize($phone/text(),'[/\s]+')
    let $normalized_phones := 
      for $raw_phone in $raw_phones
      let $clean_phone := replace($raw_phone,'[^\d\+]/', '')
      return 
	if (string-length($clean_phone) = 0)
	then ()
        else 
	  if (starts-with($clean_phone,'0'))
	  then concat($country_code, substring($clean_phone,2))
	  else $clean_phone
    return $normalized_phones
  return $clean_phones
}

let $clean_providers := 
  for $provider in /csd:CSD/csd:providerDirectory/csd:provider
  let $clean_phones := $get_clean_phones($provider)
  where count($clean_phones) > 0
  return $provider

let $cellcom_providers := 
  for $provider in $clean_providers 
  let $clean_phones := $get_clean_phones($provider)
  let $cellcom_phones := 
    for $clean_phone in $clean_phones
    return 
      if (starts-with($clean_phone,concat($country_code,$cellcom_code))) 
      then $clean_phone
      else ()
  where (count($cellcom_phones) > 0)
  return $provider

let $multi_providers :=
  for $provider in $clean_providers
  let $clean_phones := $get_clean_phones($provider)
  where (count($clean_phones) > 1)
  return $provider

return 
  <div>
    <ul>
      <li>Total number of health workers: {count(/csd:CSD/csd:providerDirectory/csd:provider)}</li>
      <li>Total number of health workers with phone: {count($clean_providers)}</li>
      <li>Total number of health workers with cellcom phone: {count($cellcom_providers)}</li>
      <li>Total number of health workers with multiple phones: {count($multi_providers)}</li>      
    </ul>
  </div>


Content-Type: application/json
URN: urn:openhie.org:openinfoman-rapidpro:select_facility

Description



 
    Creates selection menu of all the CSD organizations and faciltiies with a specified parent.  Designed as part of heierarchical facility selection menus in RapidPro webhooks.
  

Definition

Source:
import module namespace functx = "http://www.functx.com";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

let $t_top_orgid  :=  $careServicesRequest/query[@name = 'orgid']/text()
let $top_org :=  (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $t_top_orgid])[1]



let $selected_text := $careServicesRequest/query[@name = 'input']/text()
(:
let $selections := $careServicesRequest/values/item[./pair[@name = 'label' and ./text() = 'facilityselection']]
let $selected_text := 
  if (count($selections) > 0)
  then
    let $max_time := max(for $time in $selections/pair[@name='time'] return xs:dateTime($time))
    return $selections[./pair[@name = 'time'] = $max_time]/pair[@name='text']/text()
   else ()
:)

let $selected_index := if ($selected_text castable as xs:integer) then xs:integer($selected_text) else -1


let $selected :=
  if ($selected_index = 0)
  then
    /csd:CSD/csd:organizationDirectory/csd:organization[
      @entityID = /csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $top_org/@entityID]/csd:parent/@entityID
    ]
  else if ($selected_index > 0)
  then
    let $select_orgs := 
      if (exists($top_org))
      then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $top_org/@entityID]
      else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]
	
    let $select_facs := 
      if (exists($top_org))
      then /csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization[@entityID = $top_org/@entityID]]
      else ()
    return ($select_orgs,$select_facs)[ $selected_index]
  else ()

    
let $orgs := 
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $selected/@entityID]
  else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]
	
let $facs := 
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization[@entityID = $selected/@entityID]]
  else ()



let $output := 
  if ( local-name($selected ) = 'facility')
  then
    <json type='object'>
      <menutext>You already selected a facility.  You shouldn't see this message</menutext>
      <facility>{string($selected/@entityID)}</facility>
      <facilityname>{$selected/csd:primaryName/text()}</facilityname>
    </json>
  else  if ( local-name($selected ) = 'organization'  or not(exists($selected)))
  then
    <json type='object'>
      <menutext >
 	{ if (exists($selected)) then concat("In ", $selected/csd:primaryName/text(), ". ")  else () }
	{
	  let $parent := (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $selected/csd:parent/@entityID])[1]/csd:primaryName/text()
	  return
	    if ($parent)
	    then concat("O) Up to ", $parent, " ") 
	    else ()
        }
	{ for $ent at $pos in ($orgs,$facs)  return concat( $pos, ") ", $ent/csd:primaryName/text())    }
      </menutext>
      <orgid>{if (exists($selected)) then string($selected/@entityID) else ()}</orgid>
      <facility/>
      <facilityname/>      
    </json>
   else <json type='object'/>

(:return $output :)
return json:serialize($output,map{'format':'direct'})
Content-Type: application/json
URN: urn:openhie.org:openinfoman-hwr:stored-function:bulk_health_worker_read_otherids_json

Description



bulk_health_worker_read_otherids_json

Definition

Source:
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;




(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 


let $code := $careServicesRequest/code/text()
let $aa := $careServicesRequest/assigningAuthorityName/text()

let $xml:= 
  <json  type="object">
    <results type='array'>
      { 
      for $ent_id in $careServicesRequest/id
      let $req_id := upper-case(string($ent_id/@entityID))
      let $provider := (/CSD/providerDirectory/provider[upper-case(string(@entityID)) = $req_id])[1]
      let $other_ids_0 := 
	if ($code) 
	then $provider/otherID[@code = $code]
	else $provider/otherID
      let $other_ids_1 := 
	if ($aa) 
	then $other_ids_0[@assigningAuthorityName = $aa]
        else $other_ids_0

      return
	if (exists($provider) and count($other_ids_1) > 0)
	then
	  <_ type='object'>
	    <entityID>{string($provider/@entityID)}</entityID>	    
	    <otherID type="array">
	      {
		for $id in $other_ids_1
		return       
		  <_ type='object'>
		    <code>{string($id/@code)}</code>
		    <authority>{string($id/@assigningAuthorityName)}</authority>
		    <value>{$id/text()}</value>
		  </_>
	        }
	    </otherID>
	 </_>
	else ()
	      
      }
    </results>
  </json>
return json:serialize($xml,map{"format":"direct"})  
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_get_urns

Description



facility_get_urns

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $facs0 := if (exists($careServicesRequest/id)) then csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else /CSD/facilityDirectory/*
  let $facs1 := if (exists($careServicesRequest/otherID)) then csd_bl:filter_by_other_id($facs0,$careServicesRequest/otherID) else $facs0
  let $facs2 := if (exists($careServicesRequest/codedType)) then csd_bl:filter_by_coded_type($facs1,$careServicesRequest/codedType)    else $facs1
  let $facs3 := if (exists($careServicesRequest/address/addressLine)) then csd_bl:filter_by_address($facs2, $careServicesRequest/address/addressLine) else $facs2
  let $facs4 := if (exists($careServicesRequest/record)) then csd_bl:filter_by_record($facs3,$careServicesRequest/record) else $facs3
  let $facs5 := if (exists($careServicesRequest/start) and exists($careServicesRequest/max)) then csd_bl:limit_items($facs4,$careServicesRequest/start,$careServicesRequest/max) else $facs4
  let $facs6 := for $entityID in $facs5/@entityID         
   return <facility entityID="{$entityID}"/>

  return csd_bl:wrap_facilities(($facs6))
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_indices_address

Description



facility_indices_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $facs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) 
    else (/CSD/facilityDirectory/*)
  let $facs1:=     
      for $facility in  $facs0
      return
      <facility entityID="{$facility/@entityID}">
	  {
	    for $address in  $facility/address
	    return <address type="{$address/@type}"/> 
	  }
      </facility>
      
    return csd_bl:wrap_facilities($facs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_indices_contact_point

Description



facility_indices_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $facs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) 
    else (/CSD/facilityDirectory/*)
  let $facs1:=     
      for $facility in  $facs0
      return
      <facility entityID="{$facility/@entityID}">
	  {
	    for $cp at $pos  in  $facility/contactPoint
	    return <contactPoint position="{$pos}"/> 
	  }
    </facility>
      
    return csd_bl:wrap_facilities($facs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_indices_organization

Description



facility_indices_organization

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $facs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) 
    else (/CSD/facilityDirectory/*)
  let $facs1:=     
      for $facility in  $facs0
      return
      <facility entityID="{$facility/@entityID}">
	<organizations>
          {
	    for $org in $facility/organizations/organization 
	    return
	    <organization entityID="{$org/@entityID}"></organization>
	  }
	</organizations>
      </facility>
      
    return csd_bl:wrap_facilities($facs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_indices_otherid

Description



facility_indices_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $facs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) 
    else (/CSD/facilityDirectory/*)
  let $facs1:=     
      for $facility in  $facs0
      return
      <facility entityID="{$facility/@entityID}">
	{
	  for $id at $pos  in  $facility/otherID
	  return <otherID position="{$pos}"/> 
	}
    </facility>
      
    return csd_bl:wrap_facilities($facs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_service

Description



facility_indices_service

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $facs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) 
    else (/CSD/facilityDirectory/*)
  let $facs1:=     
      for $facility in  $facs0
      return
      <facility entityID="{$facility/@entityID}">
	<organizations>
	  {
	    let $facs := 
	      if (exists($careServicesRequest/organization/@entityID)) 
		then 
		$facility/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]
	      else    $facility/organizations/organization
            for $fac in $facs
	      return 
	       <organization entityID="{$fac/@entityID}">
		  {
		    for $srvc at $pos in $fac/service
		    return <service position="{$pos}" entityID="{$srvc/@entityID}"/> 
		  }
		</organization>
	  }
	</organizations>
    </facility>
      
    return csd_bl:wrap_facilities($facs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_name_search

Description



 
    
    Performs a search for all facilities by name, type, address or ID.   
    
    
      The result set consists of the primary name of all facilities matching the  search parameters ( id, primaryName, name, codedType and address ).
     
        
      The results set may be further restricted according to the limit parameters (start, max, record/@status and record/@updated).  An ordering of the result set is not specified.
    
    
    Response
    Results are returned as a valid CSD document with a root document element of <CSD/>.  The results set is contained entirely within the <facilityDirectory/> element and consists of the full content of the <facility/> elements of matching facilities as maintained by the Care Services InfoManager.
    
    Parameters Query
    Parameters are defined as the content of following elements:
    
       <id/> csd:uniqueID: (optional) If present and the @urn attribute contains a non-empty value, it is a ID which uniquely identifies a facility. This is an exact match.  
      
      <primaryName/> xs:string: (optional) If present and contains a non-empty value, then the result set should be restricted to those facilities whose <primaryName/> contains this value. Case insensitive.
      <name/> xs:string: (optional) If present and contains a non-empty value, then the result set should be restricted to those facilities which have a <primaryName/> or <otherName/> element containing this value. Case insensitive.      
      <codedType/> csd:codedtype:  If present and contains a non-empty value the result set should be restricted to those facilities whose <codedType/@code> equals this value for the coding schema specified by the @codingSchema attribute.  Case insensitive.
      
       <address/> csd:address: (optional) Contains of any-number of child <addressLine/> elements as follows:
        
          Text content xs:string: (optional) If present and contains a non-empty value, then the results set should be restricted to those facilities whose have an <addressLine/> with specified @component containing this value exactly.  Case insensitive.
           
          @component xs:string : (Required attribute) The component of the address we are searching. Case insensitive.
          
      
      <start/>  xs:int: (optional) The starting index for results returned. Defaults to 1, which indexes the first facility matching the search parameters
      <max/>  xs:int: (optional) The maximum number of results returned.  A value of less than zero implies no maximum.
      
	<record/>  csd:record : (optional) A child element to limit results according to
	
	  @status xs:string: (optional) If present and contains a non-empty value, the result set should be restricted to those facilities whose record/@status equals this value.  Case insensitive.
	  @updated xs:dateTime: (optional) If present and contains a non-empty value, the result set should be restricted to those facilities whose record/@updated is at least the given value.
	
      
    
    Example Request
    
         <careServicesRequest>
           <function uuid='c7640530-f600-11e2-b778-0800200c9a66'>
               <codedType code='OPC' codingSchema="USDVA"/>
               <address>
                 <addressLine component='city'>Chapel Hill</addressLine>
	       </address>
               <max>5</max>
           </function>
         </careServicesRequest>         
      
  

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare  variable $careServicesRequest as item() external;



(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory/>
  <facilityDirectory>
    {
      let $facs0 := if (exists($careServicesRequest/id))
	then csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id)
      else /CSD/facilityDirectory/*
         
      let $facs1 := if (exists($careServicesRequest/primaryName))
	then csd_bl:filter_by_primary_name($facs0,$careServicesRequest/primaryName)
      else $facs0
         
      let $facs2 := if (exists($careServicesRequest/name))
	then csd_bl:filter_by_name($facs1,$careServicesRequest/name)
      else $facs1
    
      let $facs3 := if(exists($careServicesRequest/codedType))
	then csd_bl:filter_by_coded_type($facs2,$careServicesRequest/codedType) 
      else $facs2
   
      let $facs4 := if(exists($careServicesRequest/address/addressLine))
	then csd_bl:filter_by_address($facs3, $careServicesRequest/address/addressLine) 
      else $facs3

      let $facs5 := if (exists($careServicesRequest/record))
	then csd_bl:filter_by_record($facs4,$careServicesRequest/record)      
      else $facs4

      let $facs6 := if(exists($careServicesRequest/otherID))
	then csd_bl:filter_by_other_id($facs5,$careServicesRequest/otherID)      
      else $facs5

      let $facs7:= if (exists($careServicesRequest/start)) then
	if (exists($careServicesRequest/max)) 
	  then csd_bl:limit_items($facs6,$careServicesRequest/start,$careServicesRequest/max)         
	else csd_bl:limit_items($facs6,$careServicesRequest/start,<max/>)         
      else
	if (exists($careServicesRequest/max)) 
	  then csd_bl:limit_items($facs6,<start/>,$careServicesRequest/max)         
	else $facs6

      return for $fac in $facs7
        return 
	 <facility entityID='{$fac/@entityID}'>
	   {$fac/primaryName}
	 </facility>


    }     
  </facilityDirectory>
  <providerDirectory/>
</CSD>
    
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_read_address

Description



facilty_read_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $facs0 := if (exists($careServicesRequest/address/@type)) then /CSD/facilityDirectory/*  else ()
let $facs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($facs0,$careServicesRequest/id) else ()
let $facs2 := 
  if (count($facs1) = 1) 
    then 
    let $facility :=  $facs1[1] 
    return 
    <facility entityID="{$facility/@entityID}">
	{(
	  for $address in $facility/address[@type = $careServicesRequest/address/@type]
	  return $address
	 )}
      {$facility/record}
    </facility>
  else ()        
return csd_bl:wrap_facilities($facs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_read_contact_point

Description



facility_read_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $facs0 := if (exists($careServicesRequest/contactPoint/@position)) then /CSD/facilityDirectory/*  else ()
let $facs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($facs0,$careServicesRequest/id) else ()
let $facs2 := 
  if (count($facs1) = 1) 
    then 
    let $facility :=  $facs1[1] 
    return 
    <facility entityID="{$facility/@entityID}">
      {
	if (exists($careServicesRequest/contactPoint) and exists($careServicesRequest/contactPoint/@position)) 
	  then 
	      for $cp in $facility/contactPoint[position() = $careServicesRequest/contactPoint/@position]
	      return       <contactPoint position="{$careServicesRequest/contactPoint/@position}">{$cp/*}</contactPoint>
	else
	  ()
      }
      {$facility/record}
    </facility>
  else ()    
    
return csd_bl:wrap_facilities($facs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_read_organization

Description



facility_read_organization

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $facs0 := if (exists($careServicesRequest/organization/@entityID)) then /CSD/facilityDirectory/*  else ()
let $facs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($facs0,$careServicesRequest/id) else ()
let $facs2 := 
  if (count($facs1) = 1) 
    then 
    let $facility :=  $facs1[1] 
    return 
      <facility entityID="{$facility/@entityID}">
	  {
	    (
	    <organizations>
	      {
		for $org in $facility/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID ) ]
		return
		<organization entityID="{$org/@entityID}"></organization>
	      }
	    </organizations>
	       
	      ,
	      $facility/record
	    )
	  }
      </facility>
  else ()    
    
return csd_bl:wrap_facilities($facs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_read_otherid

Description



facility_read_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $facs0 := if (exists($careServicesRequest/otherID/@position)) then /CSD/facilityDirectory/*  else ()
let $facs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($facs0,$careServicesRequest/id) else ()
let $facs2 := 
  if (count($facs1) = 1) 
    then 
    let $facility :=  $facs1[1] 
    return 
    <facility entityID="{$facility/@entityID}">
      {(
	if (exists($careServicesRequest/otherID/@position))
	  then 
	  for $id in $facility/otherID[position() = $careServicesRequest/otherID/@position]
	  return       
	  <otherID 
	  position="{$careServicesRequest/otherID/@position}"
	  code="{$id/@code}"
	  assigningAuthorityName="{$id/@assigningAuthorityName}">{string($id)}</otherID>
	else
	  ()
        ,      
	$facility/record
	)}
    </facility>
  else ()    
    
return csd_bl:wrap_facilities($facs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_read_service

Description



facility_read_service

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $facs0 := if (exists($careServicesRequest/organization/@entityID)) then /CSD/providerDirectory/*  else ()
let $facs1 := if (exists($careServicesRequest/organization/service/@position)) then $facs0  else ()
let $facs2 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($facs1,$careServicesRequest/id) else ()
let $facs3 := 
  if (count($facs2) = 1) 
    then 
    let $facility :=  $facs2[1] 
    return 
    <facility entityID="{$facility/@entityID}">
      {
	if (exists($careServicesRequest/organization/@entityID) and exists($careServicesRequest/organization/service/@position)) 
	  then 
	  <organizations>
	    <organization entityID="{$careServicesRequest/organization/@entityID}">
	    {
	      for $srvc in $facility/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]/service[position() = $careServicesRequest/organization/service/@position]
	      return       <service position="{$careServicesRequest/organization/service/@position}" entityID="{$srvc/@entityID}">{$srvc/*}</service>
	  }
	    </organization>
	  </organizations>
	else
	  ()
      }
      {$facility/record}
    </facility>
  else ()    
    
return csd_bl:wrap_facilities($facs3)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_get_urns

Description



health_worker_get_urns

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := if (exists($careServicesRequest/id)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else /CSD/providerDirectory/*
  let $provs1 := if (exists($careServicesRequest/otherID)) then csd_bl:filter_by_other_id($provs0,$careServicesRequest/otherID) else $provs0
  let $provs2 := if (exists($careServicesRequest/commonName)) then csd_bl:filter_by_common_name($provs1,$careServicesRequest/commonName) else $provs1
  let $provs3 := if (exists($careServicesRequest/codedType)) then csd_bl:filter_by_coded_type($provs2,$careServicesRequest/codedType)    else $provs2
  let $provs4 := if (exists($careServicesRequest/address/addressLine)) then csd_bl:filter_by_address($provs3, $careServicesRequest/address/addressLine) else $provs3
  let $provs5 := if (exists($careServicesRequest/record)) then csd_bl:filter_by_record($provs4,$careServicesRequest/record) else $provs4
  let $provs6 := if (exists($careServicesRequest/start) and exists($careServicesRequest/max)) then csd_bl:limit_items($provs5,$careServicesRequest/start,$careServicesRequest/max) else $provs5
  let $provs7 := for $entityID in $provs6/@entityID         
   return <provider entityID="{$entityID}"/>

  return csd_bl:wrap_providers($provs7)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_address

Description



health_worker_indices_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	<demographic>
	  {
	    for $address in  $provider/demographic/address
	    return <address type="{$address/@type}"/> 
	  }
	</demographic>
    </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_contact_point

Description



health_worker_indices_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	<demographic>
	  {
	    for $cp at $pos  in  $provider/demographic/contactPoint
	    return <contactPoint position="{$pos}"/> 
	  }
	</demographic>
    </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_credential

Description



health_worker_indices_credential

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
        {
	  for $cred in $provider/credential
	  return
	  <credential >{$cred/codedType}</credential>
	}
      </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_name

Description



health_worker_indices_name

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	<demographic>
	  {
	    for $name at $pos  in  $provider/demographic/name
	    return <name position="{$pos}"/> 
	  }
	</demographic>
    </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_operating_hours

Description



health_worker_indices_operating_hours

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	<facilities>
	  {
	    let $facs := 
	      if (exists($careServicesRequest/facility/@entityID)) 
		then 
		$provider/facilities/facility[upper-case(@entityID) = upper-case($careServicesRequest/facility/@entityID)]
	      else    $provider/facilities/facility
            for $fac in $facs
	      return 
	       <facility entityID="{$fac/@entityID}">
		  {
		    if ($careServicesRequest/facility/service/@position) 
		      then
			for $srvc in $fac/service[position()= $careServicesRequest/facility/service/@position] 
			return 
			<service position="{$careServicesRequest/facility/service/@position}">
			  {for $oh at $ohpos in $srvc/operatingHours return <operatingHours position="{$ohpos}"/>}
			</service>
		    else 
		      for $srvc at $spos in $fac/service
			return 
			<service position="{$spos}">
			  {for $oh at $ohpos in $srvc/operatingHours return <operaingHours position="{$ohpos}"/>}
			</service>
		  }
		</facility>
	  }
	</facilities>
    </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_org_address

Description



health_worker_indices_org_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	<organizations>
          {
	    let $orgs := 
	      if (exists($careServicesRequest/organization/@entityID)) 
		then 
		$provider/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]
	      else    $provider/organizations/organization
            for $org in $orgs
	      return 
	       <organization entityID="{$org/@entityID}">
		  {
		    for $address  in $org/address
		    return <address type="{$address/@type}"/> 
		  }
		</organization>
	  }
	</organizations>
    </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_org_contact_point

Description



health_worker_indices_org_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	<organizations>
	  {
	    let $orgs := 
	      if (exists($careServicesRequest/organization/@entityID)) 
		then 
		$provider/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]
	      else    $provider/organizations/organization
            for $org in $orgs
	      return 
	       <organization entityID="{$org/@entityID}">
		  {
		    for $cp at $pos in $org/contactPoint
		    return <contactPoint position="{$pos}"/> 
		  }
		</organization>
	  }
	</organizations>
    </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_otherid

Description



health_worker_indices_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	{
	  for $id at $pos  in  $provider/otherID
	  return <otherID position="{$pos}"/> 
	}
    </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_provider_facility

Description



health_worker_indices_provider_facility

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	<facilities>
          {
	    for $fac in $provider/facilities/facility 
	    return
	    <facility entityID="{$fac/@entityID}"></facility>
	  }
	</facilities>
      </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_provider_organization

Description



health_worker_indices_provider_organization

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	<organizations>
          {
	    for $org in $provider/organizations/organization 
	    return
	    <organization entityID="{$org/@entityID}"></organization>
	  }
	</organizations>
      </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_indices_service

Description



health_worker_indices_service

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	<facilities>
	  {
	    let $facs := 
	      if (exists($careServicesRequest/facility/@entityID)) 
		then 
		$provider/facilities/facility[upper-case(@entityID) = upper-case($careServicesRequest/facility/@entityID)]
	      else    $provider/facilities/facility
            for $fac in $facs
	      return 
	       <facility entityID="{$fac/@entityID}">
		  {
		    for $srvc at $pos in $fac/service
		    return <service position="{$pos}" entityID="{$srvc/@entityID}"/> 
		  }
		</facility>
	  }
	</facilities>
    </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_address

Description



health_worker_read_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/address/@type)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    return 
    <provider entityID="{$provider/@entityID}">
      <demographic>
	{(
	  for $address in $provider/demographic/address[@type = $careServicesRequest/address/@type]
	  return $address
	 )}
      </demographic>
      {$provider/record}
    </provider>
  else ()        
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_contact_point

Description



health_worker_read_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/contactPoint/@position)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    return 
    <provider entityID="{$provider/@entityID}">
      {
	if (exists($careServicesRequest/contactPoint) and exists($careServicesRequest/contactPoint/@position)) 
	  then 
	  <demographic>
	    {
	      for $cp in $provider/demographic/contactPoint[position() = $careServicesRequest/contactPoint/@position]
	      return       <contactPoint position="{$careServicesRequest/contactPoint/@position}">{$cp/*}</contactPoint>
	  }
	  </demographic>
	else
	  ()
      }
      {$provider/record}
    </provider>
  else ()    
    
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_credential

Description



health_worker_read_credential

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/credential/codedType/@code) and exists($careServicesRequest/credential/codedType/@codingScheme) ) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    let $code:= $careServicesRequest/credential/codedType/@code
    let $codingScheme:= $careServicesRequest/credential/codedType/@codingScheme
    return 
      <provider entityID="{$provider/@entityID}">
	  {
	    (
	      $provider/credential/codedType[@code = $code and @codingScheme = $codingScheme]/..
	      ,
	      $provider/record
	    )
	  }
      </provider>
  else ()    
    
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_name

Description



health_worker_read_name

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/name/@position)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    return 
    <provider entityID="{$provider/@entityID}">
      {
	if (exists($careServicesRequest/name) and exists($careServicesRequest/name/@position)) 
	  then 
	  <demographic>
	    {
	      for $name in $provider/demographic/name[position() = $careServicesRequest/name/@position]
	      return       <name position="{$careServicesRequest/name/@position}">{$name/*}</name>
	  }
	  </demographic>
	else
	  ()
      }
      {$provider/record}
    </provider>
  else ()    
    
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_operating_hours

Description



health_worker_read_operating_hours

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $provs0 := if (exists($careServicesRequest/facility/@entityID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/facility/service/@position)) then $provs0  else ()
let $provs2 := if (exists($careServicesRequest/facility/service/operatingHours/@position)) then $provs1  else ()
let $provs3 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs2,$careServicesRequest/id) else ()
let $srvc := $provs3[1]/facilities/facility[upper-case(@entityID) =upper-case($careServicesRequest/facility/@entityID)]/service[position() = $careServicesRequest/facility/service/@position]
let  $provs4:=   
  if (count($srvc) = 1) 
    then
    let $oh := $srvc/operatingHours[position() = $careServicesRequest/facility/service/operatingHours/@position]
    return <provider entityID="{$careServicesRequest/id/@entityID}">
      <facilities>
	<facility entityID="{$careServicesRequest/facility/@entityID}">
	  <service position="{$careServicesRequest/facility/service/@position}" >
	    <operatingHours position="{$careServicesRequest/facility/service/operatingHours/@position}">{$oh/*}</operatingHours>
	  </service>
	</facility>
      </facilities>
      {$careServicesRequest}
    </provider>
  else ()


return csd_bl:wrap_providers($provs4)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_org_address

Description



health_worker_read_org_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/organization/@entityID) and exists($careServicesRequest/organization/address/@type)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    return 
    <provider entityID="{$provider/@entityID}">
      <organizations>
	<organization entityID="{$careServicesRequest/organization/@entityID}">
	  {
	    $provider/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]/address[@type = $careServicesRequest/organization/address/@type]
	  }
	</organization>
      </organizations>
      {$provider/record}
    </provider>
  else ()        
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_org_contact_point

Description



health_worker_read_org_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/organization/@entityID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/organization/contactPoint/@position)) then $provs0  else ()
let $provs2 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs1,$careServicesRequest/id) else ()
let $provs3 := 
  if (count($provs2) = 1) 
    then 
    let $provider :=  $provs2[1] 
    return 
    <provider entityID="{$provider/@entityID}">
      {
	if (exists($careServicesRequest/organization/@entityID) and exists($careServicesRequest/organization/contactPoint/@position)) 
	  then 
	  <organizations>
	    <organization entityID="{$careServicesRequest/organization/@entityID}">
	    {
	      for $cp in $provider/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]/contactPoint[position() = $careServicesRequest/organization/contactPoint/@position]
	      return       <contactPoint position="{$careServicesRequest/organization/contactPoint/@position}">{$cp/*}</contactPoint>
	  }
	    </organization>
	  </organizations>
	else
	  ()
      }
      {$provider/record}
    </provider>
  else ()    
    
return csd_bl:wrap_providers($provs3)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_otherid

Description



health_worker_read_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/otherID/@position)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    return 
    <provider entityID="{$provider/@entityID}">
      {(
	if (exists($careServicesRequest/otherID/@position))
	  then 
	  for $id in $provider/otherID[position() = $careServicesRequest/otherID/@position]
	  return       
	  <otherID 
	  position="{$careServicesRequest/otherID/@position}"
	  code="{$id/@code}"
	  assigningAuthorityName="{$id/@assigningAuthorityName}">{string($id)}</otherID>
	else
	  ()
        ,      
	$provider/record
	)}
    </provider>
  else ()    
    
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_otherids

Description



health_worker_read_otherids

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/otherID/@position)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()

let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    let $other_ids := 
      if ($careServicesRequest/code/text())
      then $provider/otherID[@code = $careServicesRequest/code/text()]
      else $provider/otherID

    return 
    <provider entityID="{$provider/@entityID}">
      {(
	$other_ids
        ,      
	$provider/record
	)}
    </provider>
  else ()    
    
return csd_bl:wrap_providers($provs2)
Content-Type: application/json
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_otherids_json

Description



health_worker_read_otherids_json

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;




(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id( /CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provider :=  $provs1[1] 
let $other_ids := 
  if ($careServicesRequest/code/text())
  then $provider/otherID[@code = $careServicesRequest/code/text()]
  else $provider/otherID
let $xml:= 
  <json  type="object">
    <entityID>{string($provider/@entityID)}</entityID>
    <otherID type="array">
      {
	for $id in $other_ids 
	return       
	  <_ type='object'>
	    <code>{string($id/@code)}</code>
	    <authority>{string($id/@assigningAuthorityName)}</authority>
	    <value>{$id/text()}</value>
	 </_>
      }
    </otherID>
  </json>
return json:serialize($xml,map{"format":"direct"})  
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_provider

Description



health_worker_read_provider

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $provs0 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()  
let $provs1 :=  if (count($provs0) = 1) then
  let $prov := $provs0[1]
  return 
  <provider entityID="{$prov/@entityID}">  
  {(
      $prov/codedType,
      <demographic>
      {(
	if (exists($prov/demographic/gender)) then $prov/demographic/gender else (),
	if (exists($prov/demographic/dateOfBirth)) then $prov/demographic/dateOfBirth else ()
      )}
      </demographic>,
      $prov/language,
      $prov/specialty,
      $prov/record
  )}
  </provider>
  else ()
  return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_provider_facility

Description



health_worker_read_provider_facility

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/facility/@entityID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    return 
      <provider entityID="{$provider/@entityID}">
	  {
	    (
	    <facilities>
	      {
		for $fac in $provider/facilities/facility[upper-case(@entityID) = upper-case($careServicesRequest/facility/@entityID)  ]
		return
		<facility entityID="{$fac/@entityID}"></facility>
	      }
	    </facilities>
	       
	      ,
	      $provider/record
	    )
	  }
      </provider>
  else ()    
    
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_provider_organization

Description



health_worker_read_provider_organization

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/organization/@entityID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    return 
      <provider entityID="{$provider/@entityID}">
	  {
	    (
	    <organizations>
	      {
		for $org in $provider/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID ) ]
		return
		<organization entityID="{$org/@entityID}"></organization>
	      }
	    </organizations>
	       
	      ,
	      $provider/record
	    )
	  }
      </provider>
  else ()    
    
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_read_service

Description



health_worker_read_service

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/facility/@entityID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/facility/service/@position)) then $provs0  else ()
let $provs2 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs1,$careServicesRequest/id) else ()
let $provs3 := 
  if (count($provs2) = 1) 
    then 
    let $provider :=  $provs2[1] 
    return 
    <provider entityID="{$provider/@entityID}">
      {
	if (exists($careServicesRequest/facility/@entityID) and exists($careServicesRequest/facility/service/@position)) 
	  then 
	  <facilities>
	    <facility entityID="{$careServicesRequest/facility/@entityID}">
	    {
	      for $srvc in $provider/facilities/facility[upper-case(@entityID) = upper-case($careServicesRequest/facility/@entityID)]/service[position() = $careServicesRequest/facility/service/@position]
	      return       <service position="{$careServicesRequest/facility/service/@position}" entityID="{$srvc/@entityID}">{$srvc/*}</service>
	  }
	    </facility>
	  </facilities>
	else
	  ()
      }
      {$provider/record}
    </provider>
  else ()    
    
return csd_bl:wrap_providers($provs3)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_urn_search_by_id

Description



health_worker_urn_search_by_id

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := if (exists($careServicesRequest/otherID)) then csd_bl:filter_by_other_id(/CSD/providerDirectory/*,$careServicesRequest/otherID) else ()
  let $provs1 := if (exists($careServicesRequest/start) and exists($careServicesRequest/max)) then csd_bl:limit_items($provs0,$careServicesRequest/start,$careServicesRequest/max) else $provs0
  let $provs2:= for $entityID in $provs1/@entityID     
   return <provider entityID="{$entityID}"/>

  return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_get_urns

Description



organization_get_urns

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $orgs0 := if (exists($careServicesRequest/id)) then csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id) else /CSD/organizationDirectory/*
  let $orgs1 := if (exists($careServicesRequest/otherID)) then csd_bl:filter_by_other_id($orgs0,$careServicesRequest/otherID) else $orgs0
  let $orgs2 := if (exists($careServicesRequest/codedType)) then csd_bl:filter_by_coded_type($orgs1,$careServicesRequest/codedType)    else $orgs1
  let $orgs3 := if (exists($careServicesRequest/address/addressLine)) then csd_bl:filter_by_address($orgs2, $careServicesRequest/address/addressLine) else $orgs2
  let $orgs4 := if (exists($careServicesRequest/record)) then csd_bl:filter_by_record($orgs3,$careServicesRequest/record) else $orgs3
  let $orgs5 := if (exists($careServicesRequest/start) and exists($careServicesRequest/max)) then csd_bl:limit_items($orgs4,$careServicesRequest/start,$careServicesRequest/max) else $orgs4
  let $orgs6 := for $entityID in $orgs5/@entityID         
   return <organization entityID="{$entityID}"/>

  return csd_bl:wrap_organizations(($orgs6))
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_indices_address

Description



organization_indices_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $orgs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id) 
    else (/CSD/organizationDirectory/*)
  let $orgs1:=     
      for $organization in  $orgs0
      return
      <organization entityID="{$organization/@entityID}">
	  {
	    for $address in  $organization/address
	    return <address type="{$address/@type}"/> 
	  }
      </organization>
      
    return csd_bl:wrap_organizations($orgs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_indices_contact_point

Description



organization_indices_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $orgs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id) 
    else (/CSD/organizationDirectory/*)
  let $orgs1:=     
      for $organization in  $orgs0
      return
      <organization entityID="{$organization/@entityID}">
	  {
	    for $cp at $pos  in  $organization/contactPoint
	    return <contactPoint position="{$pos}"/> 
	  }
    </organization>
      
    return csd_bl:wrap_organizations($orgs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_indices_credential

Description



organization_indices_credential

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $orgs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id) 
    else (/CSD/organizationDirectory/*)
  let $orgs1:=     
      for $organization in  $orgs0
      return
      <organization entityID="{$organization/@entityID}">
        {
	  for $cred in $organization/credential
	  return
	  <credential >{$cred/codedType}</credential>
	}
      </organization>
      
    return csd_bl:wrap_organizations($orgs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_indices_otherid

Description



organization_indices_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $orgs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id) 
    else (/CSD/organizationDirectory/*)
  let $orgs1:=     
      for $organization in  $orgs0
      return
      <organization entityID="{$organization/@entityID}">
	{
	  for $id at $pos  in  $organization/otherID
	  return <otherID position="{$pos}"/> 
	}
    </organization>
      
    return csd_bl:wrap_organizations($orgs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_name_search

Description



 
    
    Performs a search for all organizations by name, coded type, address or ID.   
    
    
      The result set consists of the primary name of all organizations matching the  search parameters ( id, primaryName, name, codedType and address ).
     
        
      The results set may be further restricted according to the limit parameters (start, max, record/@status and record/@updated).  An ordering of the result set is not specified.
    
    
    Response
    Results are returned as a valid CSD document with a root document element of <CSD/>.  The results set is contained entirely within the <organizationDirectory/> element and consists of the full content of the <organization/> elements of matching organizations as maintained by the Care Services InfoManager.
    
    Parameters Query
    Parameters are defined as the content of following elements:
    
       <id/> csd:uniqueID: (optional) If present and the @urn attribute contains a non-empty value, it is a ID which uniquely identifies an organization. This is an exact match.  
      
      <primaryName/> xs:string: (optional) If present and contains a non-empty value, then the result set should be restricted to those organizations whose <primaryName/> contains this value. Case insensitive.
      <name/> xs:string: (optional) If present and contains a non-empty value, then the result set should be restricted to those organizations which have a <primaryName/> or <otherName/> element containing this value. Case insensitive.      
      <codedType/> csd:codedtype:  If present and contains a non-empty value the result set should be restricted to those organizations whose <codedType/@code> equals this value for the coding schema specified by the @codingSchema attribute.  Case insensitive.
      
       <address/> csd:address: (optional) Contains of any-number of child <addressLine/> elements as follows:
        
          Text content xs:string: (optional) If present and contains a non-empty value, then the results set should be restricted to those organizations whose have an <addressLine/> with specified @component containing this value exactly.  Case insensitive.
           
          @component xs:string : (Required attribute) The component of the address we are searching. Case insensitive.
          
      
      <start/>  xs:int: (optional) The starting index for results returned. Defaults to 1, which indexes the first organization matching the search parameters
      <max/>  xs:int: (optional) The maximum number of results returned.  A value of less than zero implies no maximum.
      
	<record/>  csd:record : (optional) A child element to limit results according to
	
	  @status xs:string: (optional) If present and contains a non-empty value, the result set should be restricted to those organizations whose record/@status equals this value.  Case insensitive.
	  @updated xs:dateTime: (optional) If present and contains a non-empty value, the result set should be restricted to those organizations whose record/@updated is at least the given value.
	
      
    
    Example Request
    
         <careServicesRequest>
           <function uuid='dc6aedf0-f609-11e2-b778-0800200c9a66'>
               <codedType codingSchema="moh.gov.rw" code="FBO" />
               <address>
                 <addressLine component='city'>Kigali</addressLine>
	       </address>
               <max>5</max>
           </function>
         </careServicesRequest>         
      
  

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 


<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory>
    {
      let $orgs0 := if (exists($careServicesRequest/id))
	then csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id)
      else /CSD/organizationDirectory/*
         
      let $orgs1 := if (exists($careServicesRequest/primaryName))
	then csd_bl:filter_by_primary_name($orgs0,$careServicesRequest/primaryName)
      else $orgs0
         
      let $orgs2 := if(exists($careServicesRequest/name))
	then csd_bl:filter_by_name($orgs1,$careServicesRequest/name)
      else $orgs1
    
      let $orgs3 := if(exists($careServicesRequest/codedType))
	then csd_bl:filter_by_coded_type($orgs2,$careServicesRequest/codedType)
      else $orgs2
   
      let $orgs4 :=if (exists($careServicesRequest/address/addressLine))
	then csd_bl:filter_by_address($orgs3, $careServicesRequest/address/addressLine)
      else $orgs3
      
      let $orgs5 := if (exists($careServicesRequest/record))
	then csd_bl:filter_by_record($orgs4,$careServicesRequest/record)
      else $orgs4

      let $orgs6 := if (exists($careServicesRequest/otherID))
	then csd_bl:filter_by_other_id($orgs5,$careServicesRequest/otherID)
      else $orgs5

      let $orgs7 := if (exists($careServicesRequest/start)) then
	if (exists($careServicesRequest/max))
	  then csd_bl:limit_items($orgs6,$careServicesRequest/start,$careServicesRequest/max)
	else csd_bl:limit_items($orgs6,$careServicesRequest/start,<max/>)
      else
	if (exists($careServicesRequest/max))
	  then csd_bl:limit_items($orgs6,<start/>,$careServicesRequest/max)
	else $orgs6
	  
      return for $org in $orgs7
	return<organization urn='{$org/@urn}'>
	  {$org/primaryName}
	</organization>

    }     
  </organizationDirectory>
  <serviceDirectory/>
  <facilityDirectory/>
  <providerDirectory/>
</CSD>
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_read_address

Description



facilty_read_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $orgs0 := if (exists($careServicesRequest/address/@type)) then /CSD/organizationDirectory/*  else ()
let $orgs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($orgs0,$careServicesRequest/id) else ()
let $orgs2 := 
  if (count($orgs1) = 1) 
    then 
    let $organization :=  $orgs1[1] 
    return 
    <organization entityID="{$organization/@entityID}">
	{(
	  for $address in $organization/address[@type = $careServicesRequest/address/@type]
	  return $address
	 )}
      {$organization/record}
    </organization>
  else ()        
return csd_bl:wrap_organizations($orgs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_read_contact_point

Description



organization_read_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $orgs0 := if (exists($careServicesRequest/contactPoint/@position)) then /CSD/organizationDirectory/*  else ()
let $orgs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($orgs0,$careServicesRequest/id) else ()
let $orgs2 := 
  if (count($orgs1) = 1) 
    then 
    let $organization :=  $orgs1[1] 
    return 
    <organization entityID="{$organization/@entityID}">
      {
	if (exists($careServicesRequest/contactPoint) and exists($careServicesRequest/contactPoint/@position)) 
	  then 
	      for $cp in $organization/contactPoint[position() = $careServicesRequest/contactPoint/@position]
	      return       <contactPoint position="{$careServicesRequest/contactPoint/@position}">{$cp/*}</contactPoint>
	else
	  ()
      }
      {$organization/record}
    </organization>
  else ()    
    
return csd_bl:wrap_organizations($orgs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_read_credential

Description



organization_read_credential

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $orgs0 := if (exists($careServicesRequest/credential/codedType/@code) and exists($careServicesRequest/credential/codedType/@codingScheme) ) then /CSD/organizationDirectory/*  else ()
let $orgs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($orgs0,$careServicesRequest/id) else ()
let $orgs2 := 
  if (count($orgs1) = 1) 
    then 
    let $organization :=  $orgs1[1] 
    let $code:= $careServicesRequest/credential/codedType/@code
    let $codingScheme:= $careServicesRequest/credential/codedType/@codingScheme
    return 
      <organization entityID="{$organization/@entityID}">
	  {
	    (
	      $organization/credential/codedType[@code = $code and @codingScheme = $codingScheme]/..
	      ,
	      $organization/record
	    )
	  }
      </organization>
  else ()    
    
return csd_bl:wrap_organizations($orgs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_read_otherid

Description



organization_read_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $orgs0 := if (exists($careServicesRequest/otherID/@position)) then /CSD/organizationDirectory/*  else ()
let $orgs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($orgs0,$careServicesRequest/id) else ()
let $orgs2 := 
  if (count($orgs1) = 1) 
    then 
    let $organization :=  $orgs1[1] 
    return 
    <organization entityID="{$organization/@entityID}">
      {(
	if (exists($careServicesRequest/otherID/@position))
	  then 
	  for $id in $organization/otherID[position() = $careServicesRequest/otherID/@position]
	  return       
	  <otherID 
	  position="{$careServicesRequest/otherID/@position}"
	  code="{$id/@code}"
	  assigningAuthorityName="{$id/@assigningAuthorityName}">{string($id)}</otherID>
	else
	  ()
        ,      
	$organization/record
	)}
    </organization>
  else ()    
    
return csd_bl:wrap_organizations($orgs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:provider_name_search

Description



     Performs a search for all providers by name, coded type, address or ID. 
     The result set consists of all names  providers matching the search parameters ( id,
        otherID, commonName,codedType and address ). 
     The results set may be further restricted according to the limit parameters
        (start, max, record/@status and record/@updated). An ordering of
      the result set is not specified. 
    
      Response Results are returned as a valid CSD document with a root document element of
      <CSD/>. The results set is contained entirely within the <providerDirectory/>
      element and consists of the full content of the <provider/> elements of matching
      providers as maintained by the Care Services InfoManager. 
    Parameters Query Parameters are defined as the content of following elements: 
       <id/> csd:uniqueID: (optional) If present and the @urn attribute contains a
        non-empty value, it is a ID which uniquely identifies a provider. This is an exact match. 
       <otherID/> csd:otherID: (optional) If present and the
        @assigningAuthorityName attribute contains a non-empty value, then the result set is
        restricted to only those providers which have a <otherID/> with the given
        assigingAuthorityName and @code  <commonName/> xsd:string: (optional)
        If present and contains a non-empty value, then the result set should be restricted to those
        providers which have a <demographic/name/commonName/> containing this value. Case
        insensitive.
      <codedType/> csd:codedtype: If present and contains a non-empty value the
        result set should be restricted to those providers whose <codeType/@code> equals this
        value for the coding schema specified by the @codingSchema attribute. Case insensitive. 
       <address/> csd:address: (optional) Contains of any-number of child
        <addressLine/> elements as follows: 
          Text content xsd:string: (optional) If present and contains a non-empty value,
            then the results set should be restricted to those providers whose have an
            <addressLine/> with specified @component containing this value exactly. Case
            insensitive. 
          @component xsd:string : (Required attribute) The component of the address we
            are searching. Case insensitive.
        
      
      <start/>  xsd:int: (optional) The starting index for results returned.
        Defaults to 1, which indexes the first provider matching the search parameters
      <max/>  xsd:int: (optional) The maximum number of results returned. A value
        of less than zero implies no maximum.
       <record/>  csd:record : (optional) A child element to limit results
        according to 
          @status xsd:string: (optional) If present and contains a non-empty value, the
            result set should be restricted to those providers whose record/@status equals this
            value. Case insensitive.
          @updated xsd:dateTime: (optional) If present and contains a non-empty value,
            the result set should be restricted to those providers whose record/@updated is at least
            the given value.
        
      
    
    Example Request
    
         <careServicesRequest>
           <function uuid='4e8bbeb9-f5f5-11e2-b778-0800200c9a66'>
               <codedType code="2221" codingSchema="ISCO-08" /<
               <address>
                 <addressLine component='city'>Kigali</addressLine>
	       </address>
               <max>5</max>
           </function>
         </careServicesRequest>         
      
  

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory/>
  <facilityDirectory/>
  <providerDirectory>
    {

      let $provs0 := if (exists($careServicesRequest/id))
	then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id)
      else /CSD/providerDirectory/*

      let $provs1 := if(exists($careServicesRequest/otherID))
	then csd_bl:filter_by_other_id($provs0,$careServicesRequest/otherID)
      else $provs0
         
      let $provs2 := if(exists($careServicesRequest/commonName))
	then csd_bl:filter_by_common_name($provs1,$careServicesRequest/commonName)
      else $provs1
    
      let $provs3 := if (exists($careServicesRequest/codedType))
	then csd_bl:filter_by_coded_type($provs2,$careServicesRequest/codedType) 
      else $provs2
   
      let $provs4 := if (exists($careServicesRequest/address/addressLine))
	then csd_bl:filter_by_demographic_address($provs3, $careServicesRequest/address/addressLine) 
      else $provs3

      let $provs5 :=  if (exists($careServicesRequest/record)) 
	then csd_bl:filter_by_record($provs4,$careServicesRequest/record)      
      else  $provs4

      let $provs6:= if (exists($careServicesRequest/start)) then
	if (exists($careServicesRequest/max)) 
	  then csd_bl:limit_items($provs5,$careServicesRequest/start,$careServicesRequest/max)         
	else csd_bl:limit_items($provs5,$careServicesRequest/start,<max/>)         
      else
	if (exists($careServicesRequest/max)) 
	  then csd_bl:limit_items($provs5,<start/>,$careServicesRequest/max)         
	else $provs5

     return 
       for $prov in $provs6
	 return 
	 <provider entityID='{$prov/@entityID}'>
	   <demogrpahic>
	   {$prov/demographic/name}
	   </demogrpahic>
	 </provider>

    }     
  </providerDirectory>
</CSD>
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:service_get_urns

Description



service_get_urns

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $srvcs0 := if (exists($careServicesRequest/id)) then csd_bl:filter_by_primary_id(/CSD/serviceDirectory/*,$careServicesRequest/id) else /CSD/serviceDirectory/*
  let $srvcs1 := if (exists($careServicesRequest/codedType)) then csd_bl:filter_by_coded_type($srvcs0,$careServicesRequest/codedType)    else $srvcs0
  let $srvcs2 := if (exists($careServicesRequest/record)) then csd_bl:filter_by_record($srvcs1,$careServicesRequest/record) else $srvcs1
  let $srvcs3 := if (exists($careServicesRequest/start) and exists($careServicesRequest/max)) then csd_bl:limit_items($srvcs2,$careServicesRequest/start,$careServicesRequest/max) else $srvcs2
  let $srvcs4 := for $entityID in $srvcs3/@entityID         
   return <service entityID="{$entityID}"/>

  return csd_bl:wrap_services(($srvcs4))
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_create_address

Description



facility_create_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/address/@type))  then $fac1 else ()
return  
  if ( count($fac2) = 1 )
    then
    let $facility:= $fac2[1]
    return
      let $fac3:=  
      <facility entityID="{$facility/@entityID}">
        <address type="{$careServicesRequest/address/@type}"/>
      </facility>
       return (
	   insert node
	   $careServicesRequest/address
	   into $facility
	   ,
	csd_blu:wrap_updating_facilities($fac3)
	)
  else  csd_blu:wrap_updating_facilities(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_create_contact_point

Description



facility_create_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/contactPoint))  then $fac1 else ()
return  
  if ( count($fac2) = 1 )
    then
    let $facility:= $fac2[1]
    let $position := count($facility/contactPoint) +1
    let $cp := 
      <contactPoint>
	{(
	  if (exists($careServicesRequest/contactPoint/codedType)) then  $careServicesRequest/contactPoint/codedType else (),
	  if (exists($careServicesRequest/contactPoint/equipment)) then  $careServicesRequest/contactPoint/equipment else (),
	  if (exists($careServicesRequest/contactPoint/purpose)) then  $careServicesRequest/contactPoint/purpose else (),
	  if (exists($careServicesRequest/contactPoint/certificate)) then  $careServicesRequest/contactPoint/certificate else ()
	 )}
      </contactPoint>
    let $fac3:=  
    <facility entityID="{$facility/@entityID}">
	<contactPoint position="{$position}"/>
    </facility>
    return 
      (insert node $cp into $facility ,    
      csd_blu:wrap_updating_facilities($fac3)
      )
  else  csd_blu:wrap_updating_facilities(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_create_geocode

Description



facility_create_geocode

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/geocode) and count($fac1/geocode) = 0)  then $fac1 else ()
return  
  if ( count($fac2) = 1 )
    then
    let $facility:= $fac2[1]
    return
      let $fac3:=  
      <facility entityID="{$facility/@entityID}">
        <geocode/>
      </facility>
       return (
	   insert node
	   $careServicesRequest/geocode
	   into $facility
	   ,
	csd_blu:wrap_updating_facilities($fac3)
	)
  else  csd_blu:wrap_updating_facilities(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_create_language

Description



facility_create_language

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/language/@code) and exists($careServicesRequest/language/@codingScheme))  then $fac1 else ()
let $lang0 := $fac2/language[@code = $careServicesRequest/language/@code and @codingScheme = $fac2/language/@codingScheme] 
return  
  if ( count($fac2) = 1 and count($lang0) = 0)
    then
    let $facility:= $fac2[1]
    return
      let $fac3:=  
      <facility entityID="{$facility/@entityID}">
        <language code="{$careServicesRequest/language/@code}" codingScheme="{$careServicesRequest/language/@codingScheme}"/>
      </facility>
       return (
	   insert node
	   $careServicesRequest/language
	   into $facility
	   ,
	csd_blu:wrap_updating_facilities($fac3)
	)
  else  csd_blu:wrap_updating_facilities(())
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_create_operating_hours

Description



facility_create_operating_hours

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/operatingHours))  then $fac1 else ()
return  
  if ( count($fac2) = 1 )
    then
    let $facility:= $fac2[1]
    return
      let $fac3:=  
      <facility entityID="{$facility/@entityID}">
        <operatingHours/>
      </facility>
       return (
	   insert node
	   $careServicesRequest/operatingHours
	   into $facility
	   ,
	csd_blu:wrap_updating_facilities($fac3)
	)
  else  csd_blu:wrap_updating_facilities(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_create_otherid

Description



facility_create_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/otherID/@code))  then $fac1 else ()
return  
  if ( count($fac2) = 1 )
    then
    let $facility:= $fac2[1]
    let $position := count($facility/otherID) +1
    let $id := 
      if (exists($careServicesRequest/otherID/@assigningAuthorityName)) then
      <otherID code="{$careServicesRequest/otherID/@code}" assigningAuthorityName="{$careServicesRequest/otherID/@assigningAuthorityName}">{string($careServicesRequest/otherID)}</otherID>
    else 
      <otherID code="{$careServicesRequest/otherID/@code}">{string($careServicesRequest/otherID)}</otherID>
    let $fac3:=  
    <facility entityID="{$facility/@entityID}">
      <otherID position="{$position}"/>
    </facility>
    return 
      (insert node $id into $facility ,    
      csd_blu:wrap_updating_facilities($fac3)
      )
  else  csd_blu:wrap_updating_facilities(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_delete_address

Description



facility_delete_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/address/@type))  then $fac1 else ()
let $address:= $fac2[1]/address[@type = $careServicesRequest/address/@type]
return 
let $fac:=  
      <facility entityID="{$fac2/@entityID}">
        <address type="{$careServicesRequest/address/@type}"/>
      </facility>
       return (
	   if (exists($address)) then (delete node $address) else ()
	   ,
	csd_blu:wrap_updating_facilities($fac)
	)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_delete_contact_point

Description



facility_delete_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  if (exists($careServicesRequest/contactPoint/@position)) 
    then 
    let $facilities := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($facilities) = 1 )
	then
	let  $cp :=  $facilities[1]/contactPoint[position() = $careServicesRequest/contactPoint/@position]
	return if (exists($cp)) then (delete node $cp) else ()
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_delete_geocode

Description



facility_delete_geocode

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/geocode))  then $fac1 else ()
let $geocode:= $fac2[1]/geocode
return 
let $fac:=  
      <facility entityID="{$fac2/@entityID}">
        <geocode/>
      </facility>
       return (
	   if (exists($geocode)) then (delete node $geocode) else ()
	   ,
	csd_blu:wrap_updating_facilities($fac)
	)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_delete_language

Description



facility_delete_language

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/language/@code))  then $fac1 else ()
let $language:= $fac2[1]/language[@code = $careServicesRequest/language/@code]
return 
let $fac:=  
      <facility entityID="{$fac2/@entityID}">
        <language code="{$careServicesRequest/language/@code}"/>
      </facility>
       return (
	   if (exists($language)) then (delete node $language) else ()
	   ,
	csd_blu:wrap_updating_facilities($fac)
	)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_delete_name

Description



facility_delete_name

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  if (exists($careServicesRequest/primaryName/@position)) 
    then 
    let $facilities := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($facilities) = 1 )
	then
	let  $name :=  $facilities[1]/primaryName[position() = $careServicesRequest/primaryName/@position]
	return if (exists($name)) then (delete node $name) else ()
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_delete_operating_hours

Description



facility_delete_operating_hours

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $fac0 := if (exists($careServicesRequest/organization/@entityID)) then /CSD/facilityDirectory/*  else ()
let $fac1 := if (exists($careServicesRequest/organization/service/@position)) then $fac0  else ()
let $fac2 := if (exists($careServicesRequest/organization/service/operatingHours/@position)) then $fac1  else ()
let $fac3 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($fac2,$careServicesRequest/id) else ()
let $oh := $fac3[1]/organizations/organization[upper-case(@entityID) =upper-case($careServicesRequest/organization/@entityID)]/service[position() = $careServicesRequest/organization/service/@position]/operatingHours[position() = $careServicesRequest/organization/service/operatingHours/@position]
return
  if (count($oh) = 1)
    then (delete node $oh) else ()
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_delete_otherid

Description



facility_delete_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu" ;
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  if (exists($careServicesRequest/otherID/@position)) 
    then 
    let $facilities := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($facilities) = 1 )
	then
	let  $id :=  $facilities[1]/otherID[position() = $careServicesRequest/otherID/@position]
	return if (exists($id)) then (delete node $id) else ()
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_update_address

Description



facility_update_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/address/@type))  then $fac1 else ()
let $facility:= $fac2[1]
let $address:= $facility/address[@type = $careServicesRequest/address/@type]
return  
  if ( not(exists($address))) then
    csd_blu:wrap_updating_facilities(()) (: Address does not exist.  Do not update:)
  else
    let $fac3:=  
    <facility entityID="{$facility/@entityID}">
      <address type="{$careServicesRequest/address/@type}"/>
    </facility>
    return (
      csd_blu:bump_timestamp($facility),
      replace  node  $address with $careServicesRequest/address
      ,
      csd_blu:wrap_updating_facilities($fac3)
    )
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_update_contact_point

Description



facility_update_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $fac0 := if (exists($careServicesRequest/contactPoint/@position)) then /CSD/facilityDirectory/*  else ()
let $fac1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($fac0,$careServicesRequest/id) else ()
let $old_cp := $fac1[1]/contactPoint[position() = $careServicesRequest/contactPoint/@position]
return
  if (count($fac1) = 1 and exists($old_cp)) 
    then
    let $new_cp := $careServicesRequest/contactPoint
    let $fac2 := 
    <facility entityID="{$fac1[1]/@entityID}">
	  <contactPoint position="{$careServicesRequest/contactPoint/@position}"/>
    </facility>
    return
      (
	csd_blu:bump_timestamp($fac1[1]),
	if (exists($new_cp/codedType)) then (delete node $old_cp/codedType,insert node $new_cp/codedType into $old_cp) else (),
	if (exists($new_cp/equipment)) then (delete node $old_cp/equipment,insert node $new_cp/equipment into $old_cp) else (),
	if (exists($new_cp/purpose)) then (delete node $old_cp/purpose,insert node $new_cp/purpose into $old_cp) else (),
	if (exists($new_cp/certificate)) then (delete node $old_cp/certificate,insert node $new_cp/certificate into $old_cp) else (),
	csd_blu:wrap_updating_facilities($fac2)
     )
  else 	csd_blu:wrap_updating_facilities(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_update_name

Description



facility_update_name

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $fac0 := if (exists($careServicesRequest/primaryName/@position)) then /CSD/facilityDirectory/*  else ()
let $fac1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($fac0,$careServicesRequest/id) else ()
let $name := $fac1[1]/primaryName[position() = $careServicesRequest/primaryName/@position]
return
  if (count($fac1) = 1 and exists($name)) 
    then
    let $fac2 := 
    <facility entityID="{$fac1[1]/@entityID}">
	  <name position="{$careServicesRequest/primaryName/@position}"/>
    </facility>
    let $new_name := $careServicesRequest/primaryName
    return
      (
	csd_blu:bump_timestamp($fac1[1]),
	replace  node $name with $new_name,
	csd_blu:wrap_updating_facilities($fac2)
     )
  else 	csd_blu:wrap_updating_facilities(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_update_operating_hours

Description



facility_update_operating_hours

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $fac0 := if (exists($careServicesRequest/organization/@entityID)) then /CSD/facilityDirectory/*  else ()
let $fac1 := if (exists($careServicesRequest/organization/service/@position)) then $fac0  else ()
let $fac2 := if (exists($careServicesRequest/organization/service/operatingHours/@position)) then $fac1  else ()
let $fac3 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($fac2,$careServicesRequest/id) else ()
let $oh := $fac3[1]/organizations/organization[upper-case(@entityID) =upper-case($careServicesRequest/organization/@entityID)]/service[position() = $careServicesRequest/organization/service/@position]/operatingHours[position() = $careServicesRequest/organization/service/operatingHours/@position]
return
  if (count($oh) = 1 and count($fac3) = 1)
    then
    let $new_oh := $careServicesRequest/organization/service/operatingHours
    let $fac4 := 
    <facility entityID="{$fac1[1]/@entityID}">
      <organizations>
	<organization entityID="{$careServicesRequest/organization/@entityID}">
	  <service position="{$careServicesRequest/organization/service/@position}" >
	    <operatingHours position="{$careServicesRequest/organization/service/operatingHours/@position}"/>
	  </service>
	</organization>
      </organizations>
    </facility>
    return
      (
	csd_blu:bump_timestamp($fac3[1]),
	if (exists($new_oh/openFlag)) then (delete node $oh/openFlag,insert node $new_oh/openFlag into $oh) else (),
	if (exists($new_oh/dayOfTheWeek)) then (delete node $oh/dayOfTheWeek,insert node $new_oh/dayOfTheWeek into $oh) else (),
	if (exists($new_oh/beginningHour)) then (delete node $oh/beginningHour,insert node $new_oh/beginningHour into $oh) else (),
	if (exists($new_oh/endingHour)) then (delete node $oh/endingHour,insert node $new_oh/endingHour into $oh) else (),
	if (exists($new_oh/beginEffectiveDate)) then (delete node $oh/beginEffectiveDate,insert node $new_oh/beginEffectiveDate into $oh) else (),
	if (exists($new_oh/endEffectiveDate)) then (delete node $oh/endEffectiveDate,insert node $new_oh/endEffectiveDate into $oh) else (),
	csd_blu:wrap_updating_facilities($fac4)
     )
  else 	csd_blu:wrap_updating_facilities(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_update_otherid

Description



facility_update_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $fac0 := if (exists($careServicesRequest/otherID)) then /CSD/facilityDirectory/*  else ()
let $fac1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($fac0,$careServicesRequest/id) else ()
let $id := $fac1[1]/otherID[position() = $careServicesRequest/otherID/@position]
return
  if (count($fac1) = 1 and exists($id)) 
    then
    let $fac2 := 
    <facility entityID="{$fac1[1]/@entityID}">
      <otherID position="{$careServicesRequest/otherID/@position}"/>
    </facility>
    return
      (
	csd_blu:bump_timestamp($fac1[1]),
	if ($careServicesRequest/otherID/@code) 
	  then 	    
	    if (exists($id/@code))
	      then  (replace value of node $id/@code with $careServicesRequest/otherID/@code)
	      else (insert node  $careServicesRequest/otherID/@code into $id)
	  else (),
	if (exists($careServicesRequest/otherID/@assigningAuthorityName) )
	  then 
	    if (exists($id/@assigningAuthorityName))
	      then replace value of node $id/@assigningAuthorityName with $careServicesRequest/otherID/@assigningAuthorityName
	      else insert node $careServicesRequest/otherID/@assigningAuthorityName into $id		
	  else (),
	if (not(string($careServicesRequest/otherID) = '')) 
	  then (replace value of node $id with string($careServicesRequest/otherID))
	  else (),
	csd_blu:wrap_updating_facilities($fac2)
     )
  else 	csd_blu:wrap_updating_facilities(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_address

Description



health_worker_create_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/address/@type))  then $provs1 else ()
return  
  if ( count($provs2) = 1 )
    then
    let $provider:= $provs2[1]
    let $demo := $provider/demographic
    return if (exists($demo/address[@type = $careServicesRequest/address/@type])) 
      then
      csd_blu:wrap_updating_providers(()) (: Do not allow the same type to be created more than once:)
    else
      let $provs3:=  
      <provider entityID="{$provider/@entityID}">
        <demographic><address type="{$careServicesRequest/address/@type}"/></demographic>
      </provider>
       return (
	 if (not(exists($demo)))
	   then
	   insert node
	   <demographic>{$careServicesRequest/address}</demographic>
	   into $provider	
	 else	
	   insert node  $careServicesRequest/address into $demo
	   ,
	csd_blu:wrap_updating_providers($provs3)
	)
  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_contact_point

Description



health_worker_create_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/contactPoint))  then $provs1 else ()
return  
  if ( count($provs2) = 1 )
    then
    let $provider:= $provs2[1]
    let $position := count($provider/demographic/contactPoint) +1
    let $cp := 
      <contactPoint>
	{(
	  if (exists($careServicesRequest/contactPoint/codedType)) then  $careServicesRequest/contactPoint/codedType else (),
	  if (exists($careServicesRequest/contactPoint/equipment)) then  $careServicesRequest/contactPoint/equipment else (),
	  if (exists($careServicesRequest/contactPoint/purpose)) then  $careServicesRequest/contactPoint/purpose else (),
	  if (exists($careServicesRequest/contactPoint/certificate)) then  $careServicesRequest/contactPoint/certificate else ()
	 )}
      </contactPoint>
    let $provs3:=  
    <provider entityID="{$provider/@entityID}">
      <demographic>
	<contactPoint position="{$position}"/>
      </demographic>
    </provider>
    return 
      (insert node $cp into $provider/demographic ,    
      csd_blu:wrap_updating_providers($provs3)
      )
  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_credential

Description



health_worker_create_credential

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/credential/codedType/@code) and exists($careServicesRequest/credential/codedType/@codingScheme) ) then $provs1  else ()
let $cred_request := $careServicesRequest/credential
let $code:= $cred_request/codedType/@code
let $codingScheme:= $cred_request/codedType/@codingScheme
let $creds0 := $provs2/credential/codedType[@code = $code and @codingScheme = $codingScheme]
return  
  if ( count($provs2) = 1 and count($creds0) = 0)  (:DO NOT ALLOW SAME CRED TWICE :)
    then
    let $provider:= $provs2[1]
    let $cred_rec :=
    <credential>
      <codedType code="{$code}" codingScheme="{$codingScheme}"/>
    </credential>
    let $cred_new :=
    <credential>
      <codedType code="{$code}" codingScheme="{$codingScheme}"/>
      {(
	if (exists($cred_request/number)) then $cred_request/number else (),
	if (exists($cred_request/issuingAuthority)) then $cred_request/issuingAuthority else (),
	if (exists($cred_request/credentialIssueDate)) then $cred_request/credentialIssueDate else (),
        if (exists($cred_request/credentialRenewalDate)) then $cred_request/credentialRenewalDate else ()
      )}
    </credential>
    let $provs3:=  
    <provider entityID="{$provider/@entityID}">{$cred_rec}</provider>
    return 
	(
	insert node $cred_new into $provider,
	csd_blu:wrap_updating_providers($provs3)
	)

  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_name

Description



health_worker_create_name

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/name))  then $provs1 else ()
return  
  if ( count($provs2) = 1 )
    then
    let $provider:= $provs2[1]
    let $position := count($provider/demographic/name) +1
    let $provs3:=  
    <provider entityID="{$provider/@entityID}">
      <demographic>
	<name position="{$position}"/>
      </demographic>
    </provider>
    return 
      (
	if (exists($provider/demographic))
	  then insert node $careServicesRequest/name into $provider/demographic 
	else
	  insert node <demographic>{$careServicesRequest/name}</demographic> into $provider
	  ,   csd_blu:wrap_updating_providers($provs3)
	)
  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_operating_hours

Description



health_worker_create_operating_hours

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $provs0 := if (exists($careServicesRequest/facility/@entityID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/facility/service/@position)) then $provs0  else ()
let $provs2 := if (exists($careServicesRequest/facility/service/operatingHours)) then $provs1  else ()
let $provs3 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs2,$careServicesRequest/id) else ()
let $srvc := $provs3[1]/facilities/facility[upper-case(@entityID) = upper-case($careServicesRequest/facility/@entityID)]/service[position() = $careServicesRequest/facility/service/@position]
return if (count($srvc) = 1) 
  then
  let $position := count($srvc/operatingHours)
  let $provs4:=  
  <provider entityID="{$careServicesRequest/id/@entityID}">
    <facilities>
      <facility entityID="{$careServicesRequest/facility/@entityID}">
	<service position="{$careServicesRequest/facility/service/@position}" entityID="{$careServicesRequest/facility/service/@entityID}">
	  <operatingHours position="{$position}" />
	</service>
      </facility>
    </facilities>
  </provider>
  return 
    (insert node $careServicesRequest/facility/service/operatingHours into $srvc[1] ,    
    csd_blu:wrap_updating_providers($provs4)
  )
else   csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_org_address

Description



health_worker_create_org_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/organization/@entityID))  then $provs1 else ()
let $provs3 := if (exists($careServicesRequest/organization/address/@type))  then $provs2 else ()
let $provider:= $provs3[1]
let $orgs := $provider/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]
let $org := if(count($orgs) =1) then $orgs[1] else ()
let $address := $org/address[@type = $careServicesRequest/organization/address/@type]
return if (not(exists($org)) or exists($address))
  then   csd_blu:wrap_updating_providers(()) (:do not create an already existing one :)	  
else
  (
    insert node $careServicesRequest/organization/address into $org,
    csd_blu:wrap_updating_providers(    
	<provider entityID="{$provider/@entityID}">
	  <organizations>
	    <organization entityID="{$org/@entityID}">
	      <contactPoint position="{$careServicesRequest/organization/address/@type}"/>
	    </organization>
	  </organizations>
	</provider>
     )
)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_org_contact_point

Description



health_worker_create_org_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/organization/@entityID))  then $provs1 else ()
let $provs3 := if (exists($careServicesRequest/organization/contactPoint))  then $provs2 else ()
return  
  if ( count($provs3) = 1 )
    then
    let $provider:= $provs3[1]
    let $orgs := $provider/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]
    return 
      if (count($orgs) = 1) 
	then
	let $org := $orgs[1]
	let $position := count($org/contactPoint) +1
	let $new_cp := $careServicesRequest/organization/contactPoint
	let $cp := 
	<contactPoint>
	  {(
	    if (exists($new_cp/codedType)) then  $new_cp/codedType else (),
            if (exists($new_cp/equipment)) then  $new_cp/equipment else (),
            if (exists($new_cp/purpose)) then  $new_cp/purpose else (),
            if (exists($new_cp/certificate)) then  $new_cp/certificate else ()
	   )}
	</contactPoint>
	let $provs3:=  
	<provider entityID="{$provider/@entityID}">
	  <organizations>
	    <organization entityID="{$org/@entityID}">
	      <contactPoint position="{$position}"/>
	    </organization>
	  </organizations>
	</provider>
	return 
	  (insert node $cp into $org ,    
	  csd_blu:wrap_updating_providers($provs3)
	)
      else   csd_blu:wrap_updating_providers(())
    else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_otherid

Description



health_worker_create_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/otherID/@code))  then $provs1 else ()
return  
  if ( count($provs2) = 1 )
    then
    let $provider:= $provs2[1]
    let $position := count($provider/otherID) +1
    let $id := 
      if (exists($careServicesRequest/otherID/@assigningAuthorityName)) then
      <otherID code="{$careServicesRequest/otherID/@code}" assigningAuthorityName="{$careServicesRequest/otherID/@assigningAuthorityName}">{string($careServicesRequest/otherID)}</otherID>
    else 
      <otherID code="{$careServicesRequest/otherID/@code}">{string($careServicesRequest/otherID)}</otherID>
    let $provs3:=  
    <provider entityID="{$provider/@entityID}">
      <otherID position="{$position}"/>
    </provider>
    return 
      (insert node $id into $provider ,    
      csd_blu:wrap_updating_providers($provs3)
      )
  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_provider

Description



health_worker_create_provider

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
(:
import module namespace random = "http://basex.org/modules/random";
:)
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $provs0 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()  
return
  if (count($provs0) > 0) then (csd_blu:wrap_updating_providers(()))     (:do not allow duplicate ENTITYIDs:)
else
  let $entityID := 
    if (exists($careServicesRequest/id/@entityID) and not($careServicesRequest/id/@entityID = '')) then $careServicesRequest/id/@entityID
  else concat('urn:uuid:', random:uuid())
  let $time :=current-dateTime()
  let $prov := 
  <provider entityID="{$entityID}">
    {(
      $careServicesRequest/codedType,
      <demographic>
	{(
	  $careServicesRequest/gender,
	  $careServicesRequest/dateOfBirth
	 )}
	 </demographic>,
	 $careServicesRequest/language,
         $careServicesRequest/specialty,
	 if ($careServicesRequest/status) 
	   then
	   <record created="{$time}" updated="{$time}" status="{$careServicesRequest/status}" sourceDirectory="{$careServicesRequest/sourceDirectory}"/>
	 else 
	   <record created="{$time}" updated="{$time}" status="Active" sourceDirectory="{$careServicesRequest/sourceDirectory}"/>
     )}
  </provider>
  
  return (
    insert node $prov into /CSD/providerDirectory,  
    csd_blu:wrap_updating_providers(<provider entityID="{$entityID}"/>)
  )

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_provider_facility

Description



health_worker_create_provider_facility

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/facility/@entityID))  then $provs1 else ()
let $facs0 := $provs2/facilities/facility[upper-case(@entityID) = upper-case($careServicesRequest/facility/@entityID)]
let $facilities := $provs2/facilities[1]
return  
  if ( count($provs2) = 1 and count($facs0) = 0)  (:DO NOT ALLOW SAME ORG TWICE :)
    then
    let $provider:= $provs2[1]
    let $fac :=  <facility entityID="{$careServicesRequest/facility/@entityID}"/>
    let $facs_new :=  <facilities>{$fac}</facilities>

    let $provs3:=  
    <provider entityID="{$provider/@entityID}">{$facs_new}</provider>
    return 
      if (exists($facilities)) 
	then
	(insert node $fac into $facilities, 
	csd_blu:wrap_updating_providers($provs3)
	)
      else
	(
	insert node $facs_new into $provider,
	csd_blu:wrap_updating_providers($provs3)
	)

  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_provider_organization

Description



health_worker_create_provider_organization

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/organization/@entityID))  then $provs1 else ()
let $orgs0 := $provs2/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]
let $organizations := $provs2/organizations[1]
return  
  if ( count($provs2) = 1 and count($orgs0) = 0)  (:DO NOT ALLOW SAME ORG TWICE :)
    then
    let $provider:= $provs2[1]
    let $org :=  <organization entityID="{$careServicesRequest/organization/@entityID}"/>
    let $orgs_new :=  <organizations>{$org}</organizations>

    let $provs3:=  
    <provider entityID="{$provider/@entityID}">{$orgs_new}</provider>
    return 
      if (exists($organizations)) 
	then
	(insert node $org into $organizations, 
	csd_blu:wrap_updating_providers($provs3)
	)
      else
	(
	insert node $orgs_new into $provider,
	csd_blu:wrap_updating_providers($provs3)
	)

  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_create_service

Description



health_worker_create_service

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/facility/@entityID))  then $provs1 else ()
let $provs3 := if (exists($careServicesRequest/facility/service/@entityID))  then $provs2 else ()
let $provider:=   if ( count($provs3) = 1 ) then $provs3[1] else ()
let $facs := $provider/facilities/facility[upper-case(@entityID) = upper-case($careServicesRequest/facility/@entityID)]
let $fac := if (count($facs) = 1) then $facs[1] else ()
return if (exists($fac))
  then
  let $position := count($fac/service) +1
  let $srvc := 
  <service entityID="{$careServicesRequest/facility/service/@entityID}">
    {(
      $careServicesRequest/facility/service/organization,
      $careServicesRequest/facility/service/language,
      $careServicesRequest/facility/service/freeBusyURI
     )}
  </service>
  let $provs3:=  
  <provider entityID="{$provider/@entityID}">
    <facilities>
      <facility entityID="{$fac/@entityID}">
	<service position="{$position}" entityID="{$careServicesRequest/facility/service/@entityID}"/>
      </facility>
    </facilities>
  </provider>
  return 
    (insert node $srvc into $fac ,    
    csd_blu:wrap_updating_providers($provs3)
  )
else   csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_address

Description



health_worker_delete_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/address/@type))  then $provs1 else ()
let $address:= $provs2[1]/demographic/address[@type = $careServicesRequest/address/@type]
return if (exists($address)) then (delete node $address) else ()
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_contact_point

Description



health_worker_delete_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  if (exists($careServicesRequest/contactPoint/@position)) 
    then 
    let $providers := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($providers) = 1 )
	then
	let  $cp :=  $providers[1]/demographic/contactPoint[position() = $careServicesRequest/contactPoint/@position]
	return if (exists($cp)) then (delete node $cp) else ()
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_credential

Description



health_worker_delete_credential

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/credential/codedType/@code) and exists($careServicesRequest/credential/codedType/@codingScheme) ) then $provs1  else ()
let $cred_new := $careServicesRequest/credential
let $code:= $cred_new/codedType/@code
let $codingScheme:= $cred_new/codedType/@codingScheme
let $creds0 := $provs2/credential[@code = $code and @codingScheme = $codingScheme]
return  
  if ( count($provs2) = 1 and count($creds0) = 1)  then
    delete node $creds0[1]
  else
    ()
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_name

Description



health_worker_delete_name

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  if (exists($careServicesRequest/name/@position)) 
    then 
    let $providers := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($providers) = 1 )
	then
	let  $name :=  $providers[1]/demographic/name[position() = $careServicesRequest/name/@position]
	return if (exists($name)) then (delete node $name) else ()
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_operating_hours

Description



health_worker_delete_operating_hours

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $provs0 := if (exists($careServicesRequest/facility/@entityID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/facility/service/@position)) then $provs0  else ()
let $provs2 := if (exists($careServicesRequest/facility/service/operatingHours/@position)) then $provs1  else ()
let $provs3 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs2,$careServicesRequest/id) else ()
let $oh := $provs3[1]/facilities/facility[upper-case(@entityID) =upper-case($careServicesRequest/facility/@entityID)]/service[position() = $careServicesRequest/facility/service/@position]/operatingHours[position() = $careServicesRequest/facility/service/operatingHours/@position]
return
  if (count($oh) = 1)
    then (delete node $oh) else ()
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_org_address

Description



health_worker_delete_org_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/organization/@entityID))  then $provs1 else ()
let $provs3 := if (exists($careServicesRequest/organization/address/@type))  then $provs2 else ()
let $provider:= $provs3[1]
let $orgs := $provider/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]
let $org := if(count($orgs) =1) then $orgs[1] else ()
let $address := $org/address[@type = $careServicesRequest/organization/address/@type]
return if (exists($address)) then (delete node $address) else ()
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_org_contact_point

Description



health_worker_delete_org_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  if (exists($careServicesRequest/organization/contactPoint/@position) and exists($careServicesRequest/organization/@entityID)) 
    then 
    let $providers := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($providers) = 1 )
	then
	let $orgs := $providers[1]/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]
	return
	  if (count($orgs) = 1) then
	    let  $cp :=  $orgs[1]/contactPoint[position() = $careServicesRequest/organization/contactPoint/@position]
	    return if (exists($cp)) then (delete node $cp) else ()
	  else () 
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_otherid

Description



health_worker_delete_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu" ;
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  if (exists($careServicesRequest/otherID/@position)) 
    then 
    let $providers := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($providers) = 1 )
	then
	let  $id :=  $providers[1]/otherID[position() = $careServicesRequest/otherID/@position]
	return if (exists($id)) then (delete node $id) else ()
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_provider

Description



health_worker_delete_provider

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $provs0 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()  
return  if (count($provs0) = 1) then
  delete node $provs0[1] else ()
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_provider_facility

Description



health_worker_delete_provider_facility

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  if (exists($careServicesRequest/facility/@entityID)) 
    then 
    let $providers := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($providers) = 1 )
	then
	let  $fac :=  $providers[1]/facilities/facility[upper-case(@entityID) = upper-case($careServicesRequest/facility/@entityID)]
	return if (exists($fac)) then (delete node $fac) else ()
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_provider_organization

Description



health_worker_delete_provider_organization

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  if (exists($careServicesRequest/organization/@entityID)) 
    then 
    let $providers := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($providers) = 1 )
	then
	let  $org :=  $providers[1]/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]
	return if (exists($org)) then (delete node $org) else ()
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_delete_service

Description



health_worker_delete_service

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  if (exists($careServicesRequest/facility/service/@position) and exists($careServicesRequest/facility/@entityID)) 
    then 
    let $providers := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($providers) = 1 )
	then
	let $facs := $providers[1]/facilities/facility[upper-case(@entityID) = upper-case($careServicesRequest/facility/@entityID)]
	return
	  if (count($facs) = 1) then
	    let  $srvc :=  $facs[1]/service[position() = $careServicesRequest/facility/service/@position]
	    return if (exists($srvc)) then (delete node $srvc) else ()
	  else () 
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_address

Description



health_worker_update_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/address/@type))  then $provs1 else ()
let $provider:= $provs2[1]
let $demo := $provider/demographic
let $address:= $demo/address[@type = $careServicesRequest/address/@type]
return  
  if ( not(exists($address))) then
    csd_blu:wrap_updating_providers(()) (: Address does not exist.  Do not update:)
  else
    let $provs3:=  
    <provider entityID="{$provider/@entityID}">
      <demographic><address type="{$careServicesRequest/address/@type}"/></demographic>
    </provider>
    return (
      csd_blu:bump_timestamp($provider),
      replace  node  $address with $careServicesRequest/address
      ,
      csd_blu:wrap_updating_providers($provs3)
    )
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_contact_point

Description



health_worker_update_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $provs0 := if (exists($careServicesRequest/contactPoint/@position)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $old_cp := $provs1[1]/demographic/contactPoint[position() = $careServicesRequest/contactPoint/@position]
return
  if (count($provs1) = 1 and exists($old_cp)) 
    then
    let $new_cp := $careServicesRequest/contactPoint
    let $provs2 := 
    <provider entityID="{$provs1[1]/@entityID}">
      <demographic>
	<contactPoint position="{$careServicesRequest/contactPoint/@position}"/>
      </demographic>
    </provider>
    return
      (
	csd_blu:bump_timestamp($provs1[1]),
	delete node $old_cp/codeType,
	if (exists($new_cp/codeType)) then insert node $new_cp/codeType into $old_cp else (),
	delete node $old_cp/equipment,
	if (exists($new_cp/equipment)) then insert node $new_cp/equipment into $old_cp else (),
	delete node $old_cp/purpose,
	if (exists($new_cp/purpose)) then insert node $new_cp/purpose into $old_cp else (),
	delete node $old_cp/certificate,
	if (exists($new_cp/certificate)) then insert node $new_cp/certificate into $old_cp else (),
	csd_blu:wrap_updating_providers($provs2)
     )
  else 	csd_blu:wrap_updating_providers(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_credential

Description



health_worker_update_credential

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/credential/codedType/@code) and exists($careServicesRequest/credential/codedType/@codingScheme) ) then $provs1  else ()
let $cred_new := $careServicesRequest/credential
let $code:= $cred_new/codedType/@code
let $codingScheme:= $cred_new/codedType/@codingScheme
let $creds0 := $provs2/credential/codedType[@code = $code and @codingScheme = $codingScheme]
return  
  if ( count($provs2) = 1 and count($creds0) = 1)  (:Update only:)
    then
    let $cred_old := $creds0[1]/..
    let $provider:= $provs2[1]
    let $provs3 := 
      <provider entityID="{$provider/@entityID}">
	<credential>
	  <codedType code="{$code}" codingScheme="{$codingScheme}"/>
	</credential>
      </provider>


    return
      
      (
	csd_blu:bump_timestamp($provider),
	if (exists($cred_new/issuingAuthority)) then
	  (if (exists($cred_old/issuingAuthority)) then (delete node $cred_old/issuingAuthority) else (),
	  insert node $cred_new/issuingAuthority into $cred_old)
	else (),
	if (exists($cred_new/number)) then
	  (if (exists($cred_old/number)) then (delete node $cred_old/number) else (),
	  insert node $cred_new/number into $cred_old)
	else (),
	if (exists($cred_new/credentialIssueDate)) then
	  (if (exists($cred_old/credentialIssueDate)) then (delete node $cred_old/credentialIssueDate) else (),
	  insert node $cred_new/credentialIssueDate into $cred_old)
	else (),
	if (exists($cred_new/credentialRenewalDate)) then
	  (if (exists($cred_old/credentialRenewalDate)) then (delete node $cred_old/credentialRenewalDate) else (),
	  insert node $cred_new/credentialRenewalDate into $cred_old)
	else (),
	csd_blu:wrap_updating_providers($provs3)
       )
  else 	csd_blu:wrap_updating_providers(())
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_name

Description



health_worker_update_name

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $provs0 := if (exists($careServicesRequest/name/@position)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $name := $provs1[1]/demographic/name[position() = $careServicesRequest/name/@position]
return
  if (count($provs1) = 1 and exists($name)) 
    then
    let $provs2 := 
    <provider entityID="{$provs1[1]/@entityID}">
      <demographic>
	<name position="{$careServicesRequest/name/@position}"/>
      </demographic>
    </provider>
    let $new_name := 
    <name>
     {$careServicesRequest/name/*}
    </name>
    return
      (
	csd_blu:bump_timestamp($provs1[1]),
	replace  node $name with $new_name,
	csd_blu:wrap_updating_providers($provs2)
     )
  else 	csd_blu:wrap_updating_providers(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_operating_hours

Description



health_worker_update_operating_hours

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $provs0 := if (exists($careServicesRequest/facility/@entityID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/facility/service/@position)) then $provs0  else ()
let $provs2 := if (exists($careServicesRequest/facility/service/operatingHours/@position)) then $provs1  else ()
let $provs3 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs2,$careServicesRequest/id) else ()
let $oh := $provs3[1]/facilities/facility[upper-case(@entityID) =upper-case($careServicesRequest/facility/@entityID)]/service[position() = $careServicesRequest/facility/service/@position]/operatingHours[position() = $careServicesRequest/facility/service/operatingHours/@position]
return
  if (count($oh) = 1 and count($provs3) = 1)
    then
    let $new_oh := $careServicesRequest/facility/service/operatingHours
    let $provs4 := 
    <provider entityID="{$provs1[1]/@entityID}">
      <facilities>
	<facility entityID="{$careServicesRequest/facility/@entityID}">
	  <service position="{$careServicesRequest/facility/service/@position}" >
	    <operatingHours position="{$careServicesRequest/facility/service/operatingHours/@position}"/>
	  </service>
	</facility>
      </facilities>
    </provider>
    return
      (
	csd_blu:bump_timestamp($provs3[1]),
	delete node $oh/openFlag,
	if (exists($new_oh/openFlag)) then insert node $new_oh/openFlag into $oh else (),
	delete node $oh/dayOfTheWeek,
	if (exists($new_oh/dayOfTheWeek)) then insert node $new_oh/dayOfTheWeek into $oh else (),
	delete node $oh/beginningHour,
	if (exists($new_oh/beginningHour)) then insert node $new_oh/beginningHour into $oh else (),
	delete node $oh/endingHour,
	if (exists($new_oh/endingHour)) then insert node $new_oh/endingHour into $oh else (),
	delete node $oh/beginEffectiveDate,
	if (exists($new_oh/beginEffectiveDate)) then insert node $new_oh/beginEffectiveDate into $oh else (),
	delete node $oh/endEffectiveDate,
	if (exists($new_oh/endEffectiveDate)) then insert node $new_oh/endEffectiveDate into $oh else (),
	csd_blu:wrap_updating_providers($provs4)
     )
  else 	csd_blu:wrap_updating_providers(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_org_address

Description



health_worker_update_org_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/organization/@entityID))  then $provs1 else ()
let $provs3 := if (exists($careServicesRequest/organization/address/@type))  then $provs2 else ()
let $provider:= $provs3[1]
let $org_container := $provider/organizations[1]
let $orgs := $provider/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID)]
let $org := if(count($orgs) =1) then $orgs[1] else ()
let $address := $org/address[@type = $careServicesRequest/organization/address/@type]
return if (not(exists($address)))
  then   csd_blu:wrap_updating_providers((<bad0/>,$careServicesRequest)) (:do not update an non-existent one :)
else
  (
    csd_blu:bump_timestamp($provider),
    replace node $address with  $careServicesRequest/organization/address ,
     csd_blu:wrap_updating_providers(    
       <provider entityID="{$provider/@entityID}">
	 <organizations>
	   <organization entityID="{$org/@entityID}">
	     <contactPoint position="{$address/@type}"/>
	   </organization>
	 </organizations>
       </provider>
    )
)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_org_contact_point

Description



health_worker_update_org_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $provs0 := if (exists($careServicesRequest/organization/@entityID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/organization/contactPoint/@position)) then $provs0  else ()
let $provs2 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs1,$careServicesRequest/id) else ()
let $old_cp := $provs2[1]/organizations/organization[upper-case(@entityID) =upper-case($careServicesRequest/organization/@entityID)]/contactPoint[position() = $careServicesRequest/organization/contactPoint/@position]
return
  if (count($provs2) = 1 and exists($old_cp)) 
    then
    let $new_cp := $careServicesRequest/organization/contactPoint
    let $provs3 := 
    <provider entityID="{$provs1[1]/@entityID}">
      <organizations>
	<organization entityID="{$careServicesRequest/organization/@entityID}">
	  <contactPoint position="{$careServicesRequest/organization/contactPoint/@position}"/>
	</organization>
      </organizations>
    </provider>
    return
      (
	csd_blu:bump_timestamp($provs2[1]),
	delete node $old_cp/codeType,
	if (exists($new_cp/codeType)) then insert node $new_cp/codeType into $old_cp else (),
	delete node $old_cp/equipment,
	if (exists($new_cp/equipment)) then insert node $new_cp/equipment into $old_cp else (),
	delete node $old_cp/purpose,
	if (exists($new_cp/purpose)) then insert node $new_cp/purpose into $old_cp else (),
	delete node $old_cp/certificate,
	if (exists($new_cp/certificate)) then insert node $new_cp/certificate into $old_cp else (),
	csd_blu:wrap_updating_providers($provs3)
     )
  else 	csd_blu:wrap_updating_providers(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_otherid

Description



health_worker_update_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $provs0 := if (exists($careServicesRequest/otherID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $id := $provs1[1]/otherID[position() = $careServicesRequest/otherID/@position]
return
  if (count($provs1) = 1 and exists($id)) 
    then
    let $provs2 := 
    <provider entityID="{$provs1[1]/@entityID}">
      <otherID position="{$careServicesRequest/otherID/@position}"/>
    </provider>
    return
      (
	csd_blu:bump_timestamp($provs1[1]),
	if ($careServicesRequest/otherID/@code) 
	  then 	    
	    if (exists($id/@code))
	      then  (replace value of node $id/@code with $careServicesRequest/otherID/@code)
	      else (insert node  $careServicesRequest/otherID/@code into $id)
	  else (),
	if (exists($careServicesRequest/otherID/@assigningAuthorityName) )
	  then 
	    if (exists($id/@assigningAuthorityName))
	      then replace value of node $id/@assigningAuthorityName with $careServicesRequest/otherID/@assigningAuthorityName
	      else insert node $careServicesRequest/otherID/@assigningAuthorityName into $id		
	  else (),
	if (not(string($careServicesRequest/otherID) = '')) 
	  then (replace value of node $id with string($careServicesRequest/otherID))
	  else (),
	csd_blu:wrap_updating_providers($provs2)
     )
  else 	csd_blu:wrap_updating_providers(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_provider

Description



health_worker_update_provider

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $provs0 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()  
return
  if (not (count($provs0) = 1)) 
    then ( csd_blu:wrap_updating_providers((<bad/>)))     (:do nothing :)
  else
    let $provider := $provs0[1]
    let $demo := $provider/demographic
    let $dob := $demo/dateOfBirth
    let $gender := $demo/gender
    return 
      (
	csd_blu:bump_timestamp($provider),
	delete node $provider/codedType,
	insert node $careServicesRequest/codedType into $provider,
	if (not(exists($demo)))
	  then
	  insert node
	  <demographic>
	    {($careServicesRequest/gender,$careServicesRequest/dateOfBirth)}
	  </demographic>
	  into $provider	
	else	
	  (
	    if (not(exists($dob))) then  insert node $careServicesRequest/dateOfBirth into $demo else replace value of node  $demo/dateOfBirth with $careServicesRequest/dateOfBirth,
	    if (not(exists($gender))) then  insert node $careServicesRequest/gender into $demo else replace value of node  $demo/gender with $careServicesRequest/gender
	),
	delete node $provider/language,
	insert node $careServicesRequest/language into $provider,
	delete node $provider/specialty,
	insert node $careServicesRequest/specialty into $provider,
	if (exists($provider/record/@status)) 
	  then replace value of node $provider/record/@status with $careServicesRequest/status 
	else insert node attribute { 'status' } { string($careServicesRequest/status) } into $provider/record,
	csd_blu:wrap_updating_providers(<provider entityID="{$provider/@entityID}" />)
    )

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_provider_facility

Description



health_worker_update_provider_facility

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
() (: does nothing:)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_provider_organization

Description



health_worker_update_provider_organization

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
() (: does nothing:)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:health_worker_update_service

Description



health_worker_update_service

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $provs0 := if (exists($careServicesRequest/facility/@entityID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/facility/service/@position)) then $provs0  else ()
let $provs2 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs1,$careServicesRequest/id) else ()
let $old_srvc := $provs2[1]/facilities/facility[upper-case(@entityID) =upper-case($careServicesRequest/facility/@entityID)]/service[position() = $careServicesRequest/facility/service/@position]
return
  if (count($provs2) = 1 and exists($old_srvc)) 
    then
    let $new_srvc := $careServicesRequest/facility/service
    let $provs3 := 
    <provider entityID="{$provs1[1]/@entityID}">
      <facilities>
	<facility entityID="{$careServicesRequest/facility/@entityID}">
	  <service position="{$careServicesRequest/facility/service/@position}" />
	</facility>
      </facilities>
    </provider>
    return
      (
	csd_blu:bump_timestamp($provs2[1]),
	delete node $old_srvc/freeBusyURI,
	if (exists($new_srvc/freeBusyURI)) then insert node $new_srvc/freeBusyURI into $old_srvc else (),
	delete node $old_srvc/organization,
	if (exists($new_srvc/organization)) then insert node $new_srvc/organization into $old_srvc else (),
	delete node $old_srvc/language,
	if (exists($new_srvc/language)) then insert node $new_srvc/language into $old_srvc else (),
	csd_blu:wrap_updating_providers($provs3)
     )
  else 	csd_blu:wrap_updating_providers(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:facility_create_address

Description



facility_create_address

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $fac0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$careServicesRequest/id) else ()
let $fac1 := if (count($fac0) = 1) then $fac0 else ()
let $fac2 := if (exists($careServicesRequest/address/@type))  then $fac1 else ()
return  
  if ( count($fac2) = 1 )
    then
    let $facility:= $fac2[1]
    return
      let $fac3:=  
      <facility entityID="{$facility/@entityID}">
        <address type="{$careServicesRequest/address/@type}"/>
      </facility>
       return (
	   insert node
	   $careServicesRequest/address
	   into $facility
	   ,
	csd_blu:wrap_updating_facilities($fac3)
	)
  else  csd_blu:wrap_updating_facilities(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_create_contact_point

Description



organization_create_contact_point

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $orgs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id) else ()
let $orgs1 := if (count($orgs0) = 1) then $orgs0 else ()
let $orgs2 := if (exists($careServicesRequest/contactPoint))  then $orgs1 else ()
return  
  if ( count($orgs2) = 1 )
    then
    let $organization:= $orgs2[1]
    let $position := count($organization/contactPoint) +1
    let $cp := 
      <contactPoint>
	{(
	  if (exists($careServicesRequest/contactPoint/codedType)) then  $careServicesRequest/contactPoint/codedType else (),
	  if (exists($careServicesRequest/contactPoint/equipment)) then  $careServicesRequest/contactPoint/equipment else (),
	  if (exists($careServicesRequest/contactPoint/purpose)) then  $careServicesRequest/contactPoint/purpose else (),
	  if (exists($careServicesRequest/contactPoint/certificate)) then  $careServicesRequest/contactPoint/certificate else ()
	 )}
      </contactPoint>
    let $orgs3:=  
    <organization entityID="{$organization/@entityID}">
	<contactPoint position="{$position}"/>
    </organization>
    return 
      (insert node $cp into $organization ,    
      csd_blu:wrap_updating_organizations($orgs3)
      )
  else  csd_blu:wrap_updating_organizations(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_create_credential

Description



organization_create_credential

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $orgs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id) else ()
let $orgs1 := if (count($orgs0) = 1) then $orgs0 else ()
let $orgs2 := if (exists($careServicesRequest/credential/codedType/@code) and exists($careServicesRequest/credential/codedType/@codingScheme) ) then $orgs1  else ()
let $cred_request := $careServicesRequest/credential
let $code:= $cred_request/codedType/@code
let $codingScheme:= $cred_request/codedType/@codingScheme
let $creds0 := $orgs2/credential/codedType[@code = $code and @codingScheme = $codingScheme]
return  
  if ( count($orgs2) = 1 and count($creds0) = 0)  (:DO NOT ALLOW SAME CRED TWICE :)
    then
    let $organization:= $orgs2[1]
    let $cred_rec :=
    <credential>
      <codedType code="{$code}" codingScheme="{$codingScheme}"/>
    </credential>
    let $cred_new :=
    <credential>
      <codedType code="{$code}" codingScheme="{$codingScheme}"/>
      {(
	if (exists($cred_request/number)) then $cred_request/number else (),
	if (exists($cred_request/issuingAuthority)) then $cred_request/issuingAuthority else (),
	if (exists($cred_request/credentialIssueDate)) then $cred_request/credentialIssueDate else (),
        if (exists($cred_request/credentialRenewalDate)) then $cred_request/credentialRenewalDate else ()
      )}
    </credential>
    let $orgs3:=  
    <organization entityID="{$organization/@entityID}">{$cred_rec}</organization>
    return 
	(
	insert node $cred_new into $organization,
	csd_blu:wrap_updating_organizations($orgs3)
	)

  else  csd_blu:wrap_updating_organizations(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr:stored-function:organization_create_otherid

Description



organization_create_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $orgs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id) else ()
let $orgs1 := if (count($orgs0) = 1) then $orgs0 else ()
let $orgs2 := if (exists($careServicesRequest/otherID/@code))  then $orgs1 else ()
return  
  if ( count($orgs2) = 1 )
    then
    let $organization:= $orgs2[1]
    let $position := count($organization/otherID) +1
    let $id := 
      if (exists($careServicesRequest/otherID/@assigningAuthorityName)) then
      <otherID code="{$careServicesRequest/otherID/@code}" assigningAuthorityName="{$careServicesRequest/otherID/@assigningAuthorityName}">{string($careServicesRequest/otherID)}</otherID>
    else 
      <otherID code="{$careServicesRequest/otherID/@code}">{string($careServicesRequest/otherID)}</otherID>
    let $orgs3:=  
    <organization entityID="{$organization/@entityID}">
      <otherID position="{$position}"/>
    </organization>
    return 
      (insert node $id into $organization ,    
      csd_blu:wrap_updating_organizations($orgs3)
      )
  else  csd_blu:wrap_updating_organizations(())
      
Content-Type: application/json
URN: urn:openhie.org:openinfoman-rapidpro:get_json_for_import

Description



 
    Get JSON representation of CSD for import to RapidPro via API
  

Definition

Source:
import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";

declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;



let $careServicesSubRequest :=  
  <csd:careServicesRequest>
    <csd:function  urn="urn:ihe:iti:csd:2014:stored-function:provider-search" >
      <csd:requestParams/>
    </csd:function>
  </csd:careServicesRequest> 

let $providers := csr_proc:process_CSR_stored_results($csd_webconf:db, /. , $careServicesSubRequest)


let $contacts :=  
  <json type='object'>
    <contacts type="array">
    {
      for $provider in  $providers/csd:providerDirectory/csd:provider
      let $uuid := lower-case(string($provider/@entityID))
      let $payrollnum := $provider/csd:otherID[@code="1"]/text()
      let $payrollisssue := string($provider/csd:otherID[@code="1"]/@issuedate)
      let $name := ($provider/csd:demographic/csd:name/csd:commonName)[1]/text()
      let $tels := $provider/csd:demographic/csd:contactPoint/csd:codedType[@code="BP" and  @codingScheme="urn:ihe:iti:csd:2013:contactPoint"]
      let $tel_1 := $tels[1]/text()
      let $tel_2 := $tels[2]/text()
      let $tel_3 := $tels[3]/text()
      return 
	if (true()) (:  ($uuid and $name)  :)
       then 
         <_  type="object">
	   <name>{$name}</name>
	   <urns type="array">
             { if ($tel_1) then   <_ type='string'>tel:{$tel_1}</_> else ()} 
             { if ($tel_2) then   <_ type='string'>tel:{$tel_2}</_> else ()} 
             { if ($tel_3) then   <_ type='string'>tel:{$tel_3}</_> else ()} 
	   </urns>
	   <fields type="object">
             <globalid>{$uuid}</globalid>
             <payrollnum>{$payrollnum}</payrollnum>
             <payrollissue>{$payrollisssue}</payrollissue>
	   </fields>
         </_>
       else ()
    }
    </contacts>
  </json>


return json:serialize($contacts,map{"format":"direct"})  
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-liberia:mhero-merge

Description



 
    Performs merge for Liberia preserving any mHero/RapidPRO identifiers for existing providers.
  

Definition

Source:
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";

import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";

import module namespace mhero = "https://github.com/openhie/openinfoman-mhero";

declare namespace csd  =  "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;


let $mhero_doc := /.
let $mhero := $careServicesRequest/@resource
let $mhero := $careServicesRequest/documents/mhero/@resource


for $doc  in $careServicesRequest/documents/document
let $name := $doc/@resource
let $src_doc :=
  if (not ($name  = '')) 
  then if (not ($name = $mhero)) then csd_dm:open_document( $name) else ()
  else $doc
return mhero:merge_into($mhero_doc, $src_doc) 

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-fhir:fhir_fac_by_organizational_hierarchy_value_set

Description



    Provider XML representation of organizational-facility hierarchy a FHIR value set resource.  

  

Definition

Source:
import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace functx = 'http://www.functx.com';

declare namespace csd =  "urn:ihe:iti:csd:2013";
declare namespace fhir = "http://hl7.org/fhir";
declare variable $careServicesRequest as item() external;

let $org_id := $careServicesRequest/fhir:_id/text()
let $search_name := string($careServicesRequest/@function)
let $resource := string($careServicesRequest/@resource)

let $function := csr_proc:get_function_definition($search_name)
let $entity :=   string(($function/csd:extension[@urn='urn:openhie.org:openinfoman:adapter:fhir:valueset' ])[1]/@type)


let $t_base_url := 
  if (exists($careServicesRequest/@xml:base))
  then string($careServicesRequest/@xml:base)
  else string($careServicesRequest/@base_url)


let $base_url :=
  concat($t_base_url, "CSD/csr/", $resource, "/careServicesRequest/" , $search_name , "/adapter/fhir/" , $entity , "/valueset" )

let $expand := 
    (exists($careServicesRequest/fhir:_query)
    and matches(functx:trim(($careServicesRequest/fhir:_query)[1]/text()),'expand','i')
    )
      


let $org := (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $org_id])[1]
let $child_orgs := /csd:CSD/csd:organizationDirectory/csd:organization[ ./csd:parent[@entityID = $org_id]]
let $child_facs := /csd:CSD/csd:facilityDirectory/csd:facility[ ./csd:organizations/csd:organization[@entityID = $org_id]]
let $org_name := ($org/csd:primaryName)[1]/text()


return
  if (exists($org) ) 
  then
    <fhir:ValueSet>
      <fhir:text>
	<fhir:status value="generated"/>
	<div xmlns="http://www.w3.org/1999/xhtml">
	  <h2>Value Set {$org_id}</h2>
	  <h3>Valueset {$entity}: {$org/csd:primaryName/text()}</h3>
	  {
	    let $parent := (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $org/csd:parent/@entityID ])[1]
	    return 
	       if (exists($parent))
	       then
	         <span class='vs_parent'>
		   <p>Parent Oraganization (Imports this value set): </p>
		   <a href="{$base_url}?_id={$parent/@entityID}">{string($parent/@entityID)}</a>{$parent/csd:primaryName}
		 </span>
	       else()
	  }
	  {
	    if (count($child_orgs) > 0)
	    then
	      <span class='vs_child'>
	       <p>
  	         Child Organizatons (Imported Value Sets):
	       </p>
	       <ul>
	         {
		   for $child_org in $child_orgs
		   return <li><a href="{$base_url}?_id={$child_org/@entityID}">{string($child_org/@entityID)}</a>{$child_org/csd:primaryName}</li>
		 }
	       </ul>
	      </span>
	    else ()
	    
	  }
	  {
	    if (count($child_facs) > 0)
	    then 
	      <span class='vs_facs'>
	        <p>
	          Facility codes directly defined by this code set:
		</p>
	        <ul>
		  {
		     for $child_fac in $child_facs
		     return <li>Value: {string($child_fac/@entityID)} is {$child_fac/csd:primaryName/text()} </li>
		  }
		</ul>
	      </span>
	    else ()

	  }
	</div>
      </fhir:text>
      <fhir:identifier value="{$base_url}?_id={$org_id}"/>
      <fhir:version value="0"/>
      <fhir:name>Organization: {$org_name}</fhir:name>
      <fhir:status value="active"/>      
      <fhir:date>{string($org/csd:record/@lastModified)}</fhir:date>
      <fhir:define>

        <fhir:system value="{$base_url}?_id={$org_id}"/>
        <fhir:version value="0"/>
	<fhir:caseSensitive value="true"/>

	{
	  for $child_fac in $child_facs
	  let $fac_name := ($child_fac/csd:primaryName[1])/text()
	  let $definition := out:format("%s in %s", $fac_name,$org_name)
	  let $value := string($child_fac/@entityID)
	  where (not (functx:all-whitespace($value)) and not (functx:all-whitespace($fac_name)))
	  return 
	    <fhir:concept>
	      <fhir:code value="{$value}"/>
	      <fhir:display value="{$fac_name}"/>
	      <fhir:definition value="{$definition}"/>
	    </fhir:concept>
	}
      </fhir:define>
      {
	if(not($expand) ) 
	then
  	  <fhir:compose>
            {
	      for $child_org in $child_orgs
	      let $child_id := string($child_org/@entityID)
	      where not (functx:all-whitespace($child_id))
	      return <fhir:import value="{$base_url}?_id={$child_id}"/>
	    }
	  </fhir:compose>    
	 else  ()

        }
    </fhir:ValueSet>
  else $careServicesRequest
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-fhir:fhir_location_read

Description



    Provider XML representation of a faciltiy as a FHIR location resource.  

  

Definition

Source:
import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace fadpt = "https://github.com/openhie/openinfoman/adapter/fhir";
import module namespace functx = 'http://www.functx.com';

declare namespace csd =  "urn:ihe:iti:csd:2013";
declare namespace fhir = "http://hl7.org/fhir";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
 
let $search_name := "urn:ihe:iti:csd:2014:stored-function:facility-search"

let $careServicesSubRequest :=  
  <csd:careServicesRequest>
    <csd:function urn="{$search_name}" resource="{$careServicesRequest/@resource}" base_url="{$careServicesRequest/@base_url}">
      <csd:requestParams>
         {
	  let $id := $careServicesRequest/fhir:_id/text()
	  return if (functx:all-whitespace($id)) then () else <csd:id entityID="{$id}"/>
	 }
         {
	  let $cn := $careServicesRequest/fhir:name/text()
	  return if (functx:all-whitespace($cn)) then () else  <csd:primaryName>{$cn}</csd:primaryName> 
	 }
	 {
	  let $org := string($careServicesRequest/fhir:manaingOrganization/@value)
	  return if (functx:all-whitespace($org)) then () else <csd:organizations><csd:organization>{$org}</csd:organization></csd:organizations> 
	 }

         {
	  let $t_start := $careServicesRequest/page/text()
	  return if (functx:is-a-number($t_start))
	    then
	      let $start := max((xs:int($t_start),1))
	      let $t_count := $careServicesRequest/fhir:_count/text()
	      let $count := if(functx:is-a-number($t_count)) then  max((xs:int($t_count),1)) else 50
	      let $startIndex := ($start - 1)*$count + 1
	      return <csd:start>{$startIndex}</csd:start>
	    else () 
	 }
	 {
	   let $count := $careServicesRequest/fhir:_count/text()
	   return 
	      if(functx:is-a-number($count)) 
	      then  <csd:max>{max((xs:int($count),1))} </csd:max>
	      else ()
	 }
	 {
	  let $since := $careServicesRequest/fhir:_since/text()
	  return if (functx:all-whitespace($since)) then () else <csd:record updated="{$since}"/> 
	 }
      </csd:requestParams>
    </csd:function>
  </csd:careServicesRequest>

 
let $contents := csr_proc:process_CSR_stored_results( /. , $careServicesSubRequest)

   (:note this is a CSD:csd element, not a document :)
return $contents/csd:facilityDirectory/csd:facility




Content-Type: text/xml
URN: urn:openhie.org:openinfoman-fhir:fhir_organization_read

Description



    Provider XML representation of a organization as a FHIR organization resource.  

  

Definition

Source:
import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace fadpt = "https://github.com/openhie/openinfoman/adapter/fhir";
import module namespace functx = 'http://www.functx.com';

declare namespace csd =  "urn:ihe:iti:csd:2013";
declare namespace fhir = "http://hl7.org/fhir";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
 
let $search_name := "urn:ihe:iti:csd:2014:stored-function:organization-search"

let $careServicesSubRequest :=  
  <csd:careServicesRequest>
    <csd:function urn="{$search_name}" resource="{$careServicesRequest/@resource}" base_url="{$careServicesRequest/@base_url}">
      <csd:requestParams>
         {
	  let $id := $careServicesRequest/fhir:_id/text()
	  return if (functx:all-whitespace($id)) then () else <csd:id entityID="{$id}"/>
	 }
         {
	  let $cn := $careServicesRequest/fhir:name/text()
	  return if (functx:all-whitespace($cn)) then () else <csd:primaryName>{$cn}</csd:primaryName> 
	 }
	 {
	  let $org := string($careServicesRequest/fhir:partOf/@value)
	  return if (functx:all-whitespace($org)) then () else  <csd:parent>{$org}</csd:parent> 
	 }

         {
	  let $t_start := $careServicesRequest/page/text()
	  return if (functx:is-a-number($t_start))
	    then
	      let $start := max((xs:int($t_start),1))
	      let $t_count := $careServicesRequest/fhir:_count/text()
	      let $count := if(functx:is-a-number($t_count)) then  max((xs:int($t_count),1)) else 50
	      let $startIndex := ($start - 1)*$count + 1
	      return <csd:start>{$startIndex}</csd:start>
	    else () 
	 }
         {
	   let $count := $careServicesRequest/fhir:_count/text()
	   return 
	      if(functx:is-a-number($count)) 
	      then <csd:max>{max(($count,1))} </csd:max>
	      else ()
	 }
	 {
	  let $since := $careServicesRequest/fhir:_since/text()
	  return if ($since) then <csd:record updated="{$since}"/> else () 
	 }
      </csd:requestParams>
    </csd:function>
  </csd:careServicesRequest>

 
let $contents := csr_proc:process_CSR_stored_results( /. , $careServicesSubRequest)

   (:note this is a CSD:csd element, not a document :)
return $contents/csd:organizationDirectory/csd:organization




Content-Type: text/xml
URN: urn:openhie.org:openinfoman-fhir:fhir_practitioner_read

Description



    Provider XML representation of a provider as a FHIR practitioner resource.  

  

Definition

Source:
import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace fadpt = "https://github.com/openhie/openinfoman/adapter/fhir";
import module namespace functx = 'http://www.functx.com';

declare namespace csd =  "urn:ihe:iti:csd:2013";
declare namespace fhir = "http://hl7.org/fhir";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
 
let $search_name := "urn:ihe:iti:csd:2014:stored-function:provider-search"

let $careServicesSubRequest :=  
  <csd:careServicesRequest>
    <csd:function urn="{$search_name}" resource="{$careServicesRequest/@resource}" base_url="{$careServicesRequest/@base_url}">
      <csd:requestParams>
         {
	  let $id := $careServicesRequest/fhir:_id/text()
	  return if (functx:all-whitespace($id)) then () else <csd:id entityID="{$id}"/>
	 }
         {
	  let $cn := $careServicesRequest/fhir:name/fhir:text/text()
	  return if (functx:all-whitespace($cn)) then () else <csd:commonName>{$cn}</csd:commonName>
	 }
	 {
	  let $org := string($careServicesRequest/fhir:organization/@value)
	  return if (functx:all-whitespace($org)) then () else  <csd:organizations><csd:organization>{$org}</csd:organization></csd:organizations> 
	 }

	 {
	  let $loc := string($careServicesRequest/fhir:location/@value)
	  return if (functx:all-whitespace($loc)) then () else <csd:facilities><csd:facility>{$loc}</csd:facility></csd:facilities> 
	 }

         {
	  let $t_start := $careServicesRequest/page/text()
	  return if (functx:is-a-number($t_start))
	    then
	      let $start := max((xs:int($t_start),1))
	      let $t_count := $careServicesRequest/fhir:_count/text()
	      let $count := if(functx:is-a-number($t_count)) then  max((xs:int($t_count),1)) else 50
	      let $startIndex := ($start - 1)*$count + 1
	      return <csd:start>{xs:string($startIndex)}</csd:start>
	    else () 
	 }
         {
	   let $count := $careServicesRequest/fhir:_count/text()
	   return 
	      if(functx:is-a-number($count)) 
	      then <csd:max>{max(($count,1))} </csd:max>
	      else ()
	 }
	 {
	  let $since := $careServicesRequest/fhir:_since/text()
	  return if (functx:all-whitespace($since)) then () else <csd:record updated="{$since}"/> 
	 }
      </csd:requestParams>
    </csd:function>
  </csd:careServicesRequest>

 
let $contents := csr_proc:process_CSR_stored_results( /. , $careServicesSubRequest)

   (:note this is a CSD:csd element, not a document :)
return $contents/csd:providerDirectory/csd:provider




Content-Type: application/json
URN: urn:openhie.org:openinfoman-rapidpro:select_hfr_facility

Description



 
    Creates selection menu of all the CSD organizations with a specified parent.  Designed as part of heierarchical organization selection menus in RapidPro webhooks.
  

Definition

Source:
import module namespace functx = "http://www.functx.com";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

let $t_top_orgid  :=  $careServicesRequest/query[@name = 'orgid']/text()
let $top_org :=  (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $t_top_orgid])[1]

let $selected_text := $careServicesRequest/query[@name = 'input']/text()

let $selected_index := if ($selected_text castable as xs:integer) then xs:integer($selected_text) else -1

let $selected :=
  if ($selected_index = 0)
  then
    /csd:CSD/csd:organizationDirectory/csd:organization[
      @entityID = /csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $top_org/@entityID]/csd:parent/@entityID
    ]
  else if ($selected_index > 0)
  then
    let $select_orgs := 
      if (exists($top_org))
      then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $top_org/@entityID]
      else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]
    return ($select_orgs)[$selected_index]
  else ()

    
let $orgs := 
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $selected/@entityID]
  else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]

let $output := 
  if ( $selected[./csd:codedType/@code=7])
  then
    <json type='object'>
      <menutext>Facility Selected</menutext>
      <facility>{string($selected/@entityID)}</facility>
      <facilityname>{$selected/csd:primaryName/text()}</facilityname>
      <orgcode>{string($selected/csd:otherID/@code)}</orgcode>
    </json>
  else  if ( local-name($selected ) = 'organization'  or not(exists($selected)))
  then
    <json type='object'>
      <menutext >
 	{ if (exists($selected)) then concat("In ", $selected/csd:primaryName/text(), ". ")  else () }
	{
	  let $parent := (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $selected/csd:parent/@entityID])[1]/csd:primaryName/text()
	  return
	    if ($parent)
	    then concat("O) Up to ", $parent, " ") 
	    else ()
        }
	{ for $ent at $pos in ($orgs)  return concat( $pos, ") ", $ent/csd:primaryName/text())    }
      </menutext>
      <orgid>{if (exists($selected)) then string($selected/@entityID) else ()}</orgid>
      <orgcode>{string($selected/csd:otherID/@code)}</orgcode>
      <facility/>
      <facilityname/>      
    </json>
   else <json type='object'/>

(:return $output :)
return json:serialize($output,map{'format':'direct'})
Content-Type: application/json
URN: urn:openhie.org:openinfoman-rapidpro:select_village

Description



 
    Creates selection menu of all the CSD organizations and faciltiies with a specified parent.  Designed as part of heierarchical facility selection menus in RapidPro webhooks.
  

Definition

Source:
import module namespace functx = "http://www.functx.com";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

let $t_top_orgid  :=  $careServicesRequest/query[@name = 'orgid']/text()
let $top_org :=  (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $t_top_orgid])[1]



let $selected_text := $careServicesRequest/query[@name = 'input']/text()
(:
let $selections := $careServicesRequest/values/item[./pair[@name = 'label' and ./text() = 'facilityselection']]
let $selected_text := 
  if (count($selections) > 0)
  then
    let $max_time := max(for $time in $selections/pair[@name='time'] return xs:dateTime($time))
    return $selections[./pair[@name = 'time'] = $max_time]/pair[@name='text']/text()
   else ()
:)

let $selected_index := if ($selected_text castable as xs:integer) then xs:integer($selected_text) else -1


let $selected :=
  if ($selected_index = 0)
  then
    /csd:CSD/csd:organizationDirectory/csd:organization[
      @entityID = /csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $top_org/@entityID]/csd:parent/@entityID
    ]
  else if ($selected_index > 0)
  then
    let $select_orgs := 
      if (exists($top_org))
      then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $top_org/@entityID]
      else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]
	
    let $select_facs := 
      if (exists($top_org))
      then /csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization[@entityID = $top_org/@entityID]]
      else ()
    return ($select_orgs,$select_facs)[ $selected_index]
  else ()

    
let $orgs := 
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $selected/@entityID]
  else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]
	
let $facs := 
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization[@entityID = $selected/@entityID]]
  else ()



let $output := 
  if ( local-name($selected ) = 'facility')
  then
    <json type='object'>
      <menutext>You already selected a facility.  You shouldn't see this message</menutext>
      <facility>{string($selected/@entityID)}</facility>
      <facilityname>{$selected/csd:primaryName/text()}</facilityname>
    </json>
  else  if ( local-name($selected ) = 'organization'  or not(exists($selected)))
  then
    <json type='object'>
      <menutext >
 	{ if (exists($selected)) then concat("In ", $selected/csd:primaryName/text(), ". ")  else () }
	{
	  let $parent := (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $selected/csd:parent/@entityID])[1]/csd:primaryName/text()
	  return
	    if ($parent)
	    then concat("O) Up to ", $parent, " ") 
	    else ()
        }
	{ for $ent at $pos in ($orgs,$facs)  return concat( $pos, ") ", $ent/csd:primaryName/text())    }
      </menutext>
      <orgid>{if (exists($selected)) then string($selected/@entityID) else ()}</orgid>
      <facility/>
      <facilityname/>      
    </json>
   else <json type='object'/>

(:return $output :)
return json:serialize($output,map{'format':'direct'})
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-tz:hfr_facilities_to_csd

Description



 
    Updates the CSD document by an import from Health Facility Registry export of the Organizational hierarchy
  

Definition

Source:
import module namespace dxf2csd = "http://dhis2.org/csd/dxf/2.0";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace functx = "http://www.functx.com";

declare namespace csd = "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;

let $doc_name := string($careServicesRequest/@resource)
let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
let $org_dir := $doc/csd:CSD/csd:organizationDirectory

let $oid := $careServicesRequest/oid
let $csv_src := $careServicesRequest/csv  
let $csv :=    csv:parse($csv_src, map{ 'header': true()})/csv/record



let $namespace_uuid := "7ee93e32-78da-4913-82f8-49eb0a618cfc"

let $generate_UUID_v3 := function($name) {
  concat('urn:uuid:' , dxf2csd:generate_UUID_v3($name,$namespace_uuid))
}

let $zone_csd :=
for $zone_record in distinct-values($csv/Zone)
 let $now := current-dateTime()
 let $zone_urn := $generate_UUID_v3(concat('zone:',$zone_record))
  return
   <csd:organization entityID="{$zone_urn}">
     <csd:codedType code="1" codingScheme="{$oid}"/>
     <csd:primaryName>{$zone_record}</csd:primaryName>
     <csd:record
       created="{$now}"
       updated="{$now}"
       sourceDirectory="http://hfrportal.ehealth.go.tz"/>
   </csd:organization>

let $region_csd :=
for $region_record in distinct-values($csv/Region)
 let $now := current-dateTime()
 let $region_urn := $generate_UUID_v3(concat('region:',$region_record))
 let $parent_urns :=
 for $record in $csv  
  let $zone := $record/Zone
  let $region := $record/Region
  return if($region_record=$region)
   then $generate_UUID_v3(concat('zone:',$zone))
   else ()
 return
   <csd:organization entityID="{$region_urn}">
     <csd:codedType code="2" codingScheme="{$oid}"/>
     <csd:primaryName>{$region_record}</csd:primaryName>
     <csd:record
       created="{$now}"
       updated="{$now}"
       sourceDirectory="http://hfrportal.ehealth.go.tz"/>
     <csd:parent entityID="{$parent_urns[last()]}"/>
   </csd:organization>

let $district_csd :=
for $district_record in distinct-values($csv/District)
 let $now := current-dateTime()
 let $district_urn := $generate_UUID_v3(concat('district:',$district_record))
 let $parent_urns :=
 for $record in $csv
  let $region := $record/Region
  let $district := $record/District
  return if($district_record=$district)
   then $generate_UUID_v3(concat('region:',$region))
   else ()
 return
   <csd:organization entityID="{$district_urn}">
     <csd:codedType code="3" codingScheme="{$oid}"/>
     <csd:primaryName>{$district_record}</csd:primaryName>
     <csd:record
       created="{$now}"
       updated="{$now}"
       sourceDirectory="http://hfrportal.ehealth.go.tz"/>
     <csd:parent entityID="{$parent_urns[last()]}"/>
   </csd:organization>

let $council_csd :=
for $council_record in distinct-values($csv/Council)
 let $now := current-dateTime()
 let $council_urn := $generate_UUID_v3(concat('council:',$council_record))
 let $parent_urns :=
 for $record in $csv
  let $district := $record/District
  let $council := $record/Council
  return if($council_record=$council)
   then $generate_UUID_v3(concat('district:',$district))
   else ()
 return
   <csd:organization entityID="{$council_urn}">
     <csd:codedType code="4" codingScheme="{$oid}"/>
     <csd:primaryName>{$council_record}</csd:primaryName>
     <csd:record
       created="{$now}"
       updated="{$now}"
       sourceDirectory="http://hfrportal.ehealth.go.tz"/>
     <csd:parent entityID="{$parent_urns[last()]}"/>
   </csd:organization>

let $ward_csd :=
for $ward_record in distinct-values($csv/Ward)
 let $now := current-dateTime()
 let $ward_urn := $generate_UUID_v3(concat('ward:',$ward_record))
 let $parent_urns :=
 for $record in $csv
  let $council := $record/Council
  let $ward := $record/Ward
  return if($ward_record=$ward)
   then $generate_UUID_v3(concat('council:',$council))
   else ()
 return if (not (contains($ward_record,"Not set"))) then
   <csd:organization entityID="{$ward_urn}">
     <csd:codedType code="5" codingScheme="{$oid}"/>
     <csd:primaryName>{$ward_record}</csd:primaryName>
     <csd:record
       created="{$now}"
       updated="{$now}"
       sourceDirectory="http://hfrportal.ehealth.go.tz"/>
     <csd:parent entityID="{$parent_urns[last()]}"/>
   </csd:organization>
   else ()

let $village_csd :=
for $village_record in distinct-values($csv/VillageStreet)
 let $now := current-dateTime()
 let $village_urn := $generate_UUID_v3(concat('village:',$village_record))
 let $parent_urns :=
 for $record in $csv
  let $ward := if ((contains($record/Ward,"Not set"))) then $record/Council else($record/Ward)
  let $village := $record/VillageStreet
  return if($village_record=$village)
   then $generate_UUID_v3(concat('ward:',$ward))
   else ()
 return if (not (contains($village_record,"Not set"))) then
   <csd:organization entityID="{$village_urn}">
     <csd:codedType code="6" codingScheme="{$oid}"/>
     <csd:primaryName>{$village_record}</csd:primaryName>
     <csd:record
       created="{$now}"
       updated="{$now}"
       sourceDirectory="http://hfrportal.ehealth.go.tz"/>
     <csd:parent entityID="{$parent_urns[last()]}"/>
   </csd:organization>
   else ()

let $facility_csd :=
for $record in $csv
 let $facNum := $record/FacilityNumber
 let $facName  := $record/FacilityName
 let $now := current-dateTime()
 let $facility_urn := $generate_UUID_v3(concat('facility:',$facNum))
 let $parent := if ((contains($record/VillageStreet,"Not set"))) then 
                     (if ((contains($record/Ward,"Not set"))) then $record/Council else $record/Ward) 
                     else($record/VillageStreet)
 let $parent_string := if ((contains($record/VillageStreet,"Not set"))) then
                     (if ((contains($record/Ward,"Not set"))) then "council:" else "ward:")
                     else("village:")
 let $parent_urn := $generate_UUID_v3(concat($parent_string,$parent))
 return if (not (contains($facName,"Not set"))) then
   <csd:organization entityID="{$facility_urn}">
     <csd:otherID assigningAuthorityName='health_facility_registry' code="{$facNum}"/>
     <csd:codedType code="7" codingScheme="{$oid}"/>
     <csd:primaryName>{$facName/text()}</csd:primaryName>
     <csd:record
       created="{$now}"
       updated="{$now}"
       sourceDirectory="http://hfrportal.ehealth.go.tz"/>
     <csd:parent entityID="{$parent_urn}"/>
   </csd:organization>
   else ()

let $csd :=
  <csd:CSD>
    <csd:organizationDirectory>
      {($zone_csd,$region_csd,$district_csd,$council_csd,$ward_csd,$village_csd,$facility_csd)}
    </csd:organizationDirectory>
    <csd:serviceDirectory/>
    <csd:facilityDirectory/>
    <csd:providerDirectory/>
  </csd:CSD>

return  csd_dm:add($csd_webconf:db,$csd,$doc_name)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-tz:rm_org_hierarchy_to_csd

Description



 
    Updates the CSD document by an import from Resource Map's export of the Organizational hierarchy
  

Definition

Source:
import module namespace dxf2csd = "http://dhis2.org/csd/dxf/2.0";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace functx = "http://www.functx.com";

declare namespace csd = "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;


let $doc_name := string($careServicesRequest/@resource)
let $doc := csd_dm:open_document($doc_name)


let $oid := $careServicesRequest/oid
let $csv_src := $careServicesRequest/csv  
let $csv :=    csv:parse($csv_src, map{ 'header': true()})/csv/record



let $namespace_uuid := "7ee93e32-78da-4913-82f8-49eb0a618cfc"

let $generate_UUID_v3 := function($name) {
  concat('urn:uuid:' , dxf2csd:generate_UUID_v3($name,$namespace_uuid))
}



let $csd_orgs := 
  for $record in $csv
   let $village := $record/VillMtaa
   let $ward  := $record/Ward
   let $council  := $record/Council
   let $district  := $record/District
   let $region  := $record/Region
   let $zone  := $record/Zone 
   let $country  := $record/Country
   let $name  := $record/Name
   let $id  := $record/NodeID
   let $urn := $generate_UUID_v3(concat('organization:',$id))
   let $level := 
      if (not(functx:all-whitespace($village)))
      then  '6'
      else if (not(functx:all-whitespace($ward)))
      then  '5'
      else if (not(functx:all-whitespace($council)))
      then  '4'
      else if (not(functx:all-whitespace($district)))
      then  '3'
      else if (not(functx:all-whitespace($region)))
      then  '2'
      else if (not(functx:all-whitespace($zone)))
      then  '1'
      else if (not(functx:all-whitespace($country)))
      then  '0'
      else ()
   let $pid := 
      if ( not(functx:all-whitespace($village)) )
      then  $csv[./Country = $country and ./Zone = $zone and ./Region = $region and ./District = $district and ./Council = $council and ./Ward = $ward and functx:all-whitespace(./VillMtaa)]/NodeID/text()
      else if (not(functx:all-whitespace($ward)))
      then  $csv[./Country = $country and ./Zone = $zone and ./Region = $region and ./District = $district and ./Council = $council and functx:all-whitespace(./VillMtaa) and functx:all-whitespace(./Ward)]/NodeID/text()
      else if (not(functx:all-whitespace($council)))
      then  $csv[./Country = $country and ./Zone = $zone and ./Region = $region and ./District = $district and functx:all-whitespace(./Council) and functx:all-whitespace(./VillMtaa) and functx:all-whitespace(./Ward) ]/NodeID/text()
      else if (not(functx:all-whitespace($district)))
      then  $csv[./Country = $country and ./Zone = $zone and ./Region = $region and functx:all-whitespace(./District) and functx:all-whitespace(./Council) and functx:all-whitespace(./VillMtaa) and functx:all-whitespace(./Ward) ]/NodeID/text()
      else if (not(functx:all-whitespace($region)))
      then  $csv[./Country = $country and ./Zone = $zone and functx:all-whitespace(./Region) and functx:all-whitespace(./District) and functx:all-whitespace(./Council) and functx:all-whitespace(./VillMtaa) and functx:all-whitespace(./Ward)]/NodeID/text()
      else if (not(functx:all-whitespace($zone)))
      then  $csv[./Country = $country  and functx:all-whitespace(./Zone) and functx:all-whitespace(./Region) and functx:all-whitespace(./District) and functx:all-whitespace(./Council) and functx:all-whitespace(./VillMtaa) and functx:all-whitespace(./Ward)]/NodeID/text()
      else ()
   let $parent := 
     if ($pid)
     then
       let $parent_urn := $generate_UUID_v3(concat('organization:',$pid))
       return <csd:parent entityID="{$parent_urn}"/>
     else ()
   return 
     if (($name) and ($level)  and ($urn) )
     then 
       <csd:organization entityID="{$urn}">
	 <csd:otherID assigningAuthorityName='resource_map_tanzania' code="{$id}"/>
	 <csd:codedType code="{$level}" codingScheme="{$oid}"/>
	 <csd:primaryName>{$name/text()}</csd:primaryName>
	 {$parent}
       </csd:organization>
     else ($record)  (:no name or id or type :)



let $csd :=
  <csd:CSD>
    <csd:organizationDirectory>
      {$csd_orgs}
    </csd:organizationDirectory>
    <csd:serviceDirectory/>
    <csd:facilityDirectory/>  
    <csd:providerDirectory/>
  </csd:CSD>

return  csd_dm:add($csd,$doc_name)


Content-Type: text/xml
URN: urn:openhie.org:openinfoman-namibia:stored-function:staff_list

Description



    Create a staff list for Namibia by facility
  

Definition

Source:
declare namespace csd = 'urn:ihe:iti:csd:2013';
declare variable $careServicesRequest as item() external;

<html>
 <body>
  <ul>
   <li>You have {count(/csd:CSD/csd:providerDirectory/*)} providers.</li>
   <li>You have {count(/csd:CSD/csd:facilityDirectory/*)} facilities.</li>
   <li>You have {count(/csd:CSD/csd:organizationDirectory/*)} organizations.</li>
   <li>You have {count(/csd:CSD/csd:serviceDirectory/*)} services.</li>
  </ul>
  <table>
  {(: Looping through the Facility directory :)
    for $facility in /csd:CSD/csd:facilityDirectory/*
      let $facilityName:=$facility/csd:primaryName
      order by $facilityName
      return
	  <span>
	  <h2>Facility List</h2>
      <tr>
        <td> {string($facility/csd:record/@sourceDirectory)}</td>
        <td>{ $facilityName }</td> 
        <td>{ string($facility/@urn)}</td>	 
      </tr>
	  </span>
	  <span>
	  <h2>Empoloyee's List</h2>
	  <h3>{$facilityName}</h3>
	     <table> 
		 {
           for $provider in /csd:CSD/csd:providerDirectory/*
             let $EmpoloyeeName:= $provider/demogrpahic/csd:name[1]/csd:forename
             let $pfacility:=$provider/csd:facilities/facility/@entityID
			 let $gender_code:= $provider/demogrpahic/csd:gender
			 let $DOB:= $provider/demogrpahic/csd:dateOfBirth
			 let $email:= string($provider/demogrpahic/csd:contactPoint/@EMAIL)
             where $facility/@urn = $pfacility
             order by $EmpoloyeeName
			 return
			 <tr>
			  <td>{$EmpoloyeeName}</td>
			  <td>{$gender_code}</td>
			  <td>{$DOB}</td>
			  <td>{$email}</td>
			 </tr>
			 }
		   </table>
	  </span>
  
  }
  </table>
 </body>
</html>
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-whomds:stored-function:mds_completeness_healthworker

Description



Health Worker WHO MDS completeness report

Definition

Source:
declare   namespace   csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;
let $doc := /.


let $xpaths := map{
    "Posting/Facility": "csd:facilities/csd:facility",
    "ID Number": "csd:otherID/@code",
    "ID Date of Issue":"csd:otherID/@issueDate/text()",
    "ID Date of Expiration":"csd:otherID/@expirationDate/text()",
    "Place of Issue": "csd:otherID/@assigningAuthorityName/text()",
    "First name": "csd:demographic/csd:name/csd:forename/text()",
    "Last name": "csd:demographic/csd:name/csd:surname/text()",
    "Middle name":"csd:demographic/csd:name/csd:otherNames[@type='middle']/text()",
    "Maiden name": "csd:demographic/csd:name/csd:otherNames[@type='maiden']/text()",
    "Other name 1" : "csd:demographic/csd:name/csd:otherNames[@type='other_1']/text()",
    "Other name 2" :"csd:demographic/csd:name/csd:otherNames[@type='other_2']/text()",
    "Other name 3" : "csd:demographic/csd:name/csd:otherNames[@type='other_3']/text()",
    "Place of birth country":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:country/text()",
    "Place of birth town": "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:town/text()",
    "Father’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:fatherName/text()",
    "Mother’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:motherName/text()",
    "Photograph" :    "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds'  and @type='photograph']/csd:image/text()",
    "Date of birth" :  "csd:demographic/csd:dateOfBirth/text()",
    "Sex at birth " : "csd:demographic/csd:gender/text()",
    "Citizenship at birth" : "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:birth/text()" , 
    "Citizenship at present country of residence":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:residence/text()",
    "Ability in written languages":"csd:language[@code]/@written-ability",
    "Ability in spoken languages": "csd:language[@code]/@spoken-ability",
    "Address Country":"csd:demographic/csd:address/csd:addressLine[@component='country']/text()",
    "Address City": "csd:demographic/csd:address/csd:addressLine[@component='city']/text()" ,
    "Street Address": "csd:demographic/csd:address/csd:addressLine[@component='streetAddress']/text()",
    "Address Postal Code" :"csd:demographic/csd:address/csd:addressLine[@component='postalCode']/text()" ,
    "Telephone number" : "csd:demographic/csd:contactPoint/csd:codedType[@code='BP'  and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Email address" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMAIL' and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Emergency contact name" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMERGENCY'  and @codingScheme= 'urn:who.int:hrh:mds']/text()",
    "Professional License and Certification Document Type" : "csd:credential/csd:codedType/@code",
    "Professional License and Certification Document Category" : "csd:credential/csd:codedType/@category",
    "Professional License and Certification Issuing Institution": "csd:credential/csd:issuingAuthority/text()",
    "Professional License and Certification Date of Issue" : "csd:credential/csd:credentialIssueDate/text()",
    "Professional License and Certification Date of Expiration" : "csd:credential/csd:credentialRenewalDate/text()" ,
    "Professional License and Certification Scan/Photograph" :  "csd:credential/csd:extension[@urn ='urn:who.int:hrh:mds' and @type='photograph']/csd:image/text()" ,
    "Employment status" : "csd:record/@status" ,
    "Occupational category" : "csd:codedType/@code" ,
    "Employment title" : "csd:codedType[@code]/text()",
    "Complaints" : "csd:credential/csd:extension[@urn = 'urn:who.int:hrh:mds' and @type='complaints']/@value",
    "Data submission  institution ": "csd:record/@sourceDirectory",
    "Data submission date" : "csd:record/@updated" 
}



let $total := count($doc/csd:CSD/csd:providerDirectory/csd:provider)

let $stats := 
  map:for-each($xpaths, 
    function($label,$xpath) {
      let $matches := 
        for $provider in $doc/csd:CSD/csd:providerDirectory/csd:provider
        let $bindings := map{"provider":$provider}
	let $expr := " declare namespace csd = 'urn:ihe:iti:csd:2013'; declare variable $provider external; $provider/" || $xpath
	let $result := xquery:eval($expr,$bindings) 
	where exists($result)
	return 	$provider
      let $count:=count($matches)
      return <tr count="{$count}" xpath="{$xpath}"><td>{$label}</td><td>{$count}</td><td>{if ($total > 0) then floor($count div $total * 100) else "N/A"} %</td></tr>
    })


return 
  <table >
  <tr><th style='width:33%'>Data Field</th><th style='width:33%'>Number of Records<br/>Total of {$total}</th><th style='width:33%'>Percentage</th></tr>
   { 
     for $stat in $stats
     order by number($stat/@count) descending
     return $stat
   }
  </table>
Content-Type: text/csv
URN: urn:openhie.org:openinfoman-whomds:stored-function:mds_completeness_healthworker_csv

Description



Health Worker WHO MDS completeness report as CSV

Definition

Source:
declare   namespace   csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;
let $doc := /.


let $xpaths := map{
    "Posting/Facility": "csd:facilities/csd:facility",
    "ID Number": "csd:otherID/@code",
    "ID Date of Issue":"csd:otherID/@issueDate/text()",
    "ID Date of Expiration":"csd:otherID/@expirationDate/text()",
    "Place of Issue": "csd:otherID/@assigningAuthorityName/text()",
    "First name": "csd:demographic/csd:name/csd:forename/text()",
    "Last name": "csd:demographic/csd:name/csd:surname/text()",
    "Middle name":"csd:demographic/csd:name/csd:otherNames[@type='middle']/text()",
    "Maiden name": "csd:demographic/csd:name/csd:otherNames[@type='maiden']/text()",
    "Other name 1" : "csd:demographic/csd:name/csd:otherNames[@type='other_1']/text()",
    "Other name 2" :"csd:demographic/csd:name/csd:otherNames[@type='other_2']/text()",
    "Other name 3" : "csd:demographic/csd:name/csd:otherNames[@type='other_3']/text()",
    "Place of birth country":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:country/text()",
    "Place of birth town": "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:town/text()",
    "Father’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:fatherName/text()",
    "Mother’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:motherName/text()",
    "Photograph" :    "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds'  and @type='photograph']/csd:image/text()",
    "Date of birth" :  "csd:demographic/csd:dateOfBirth/text()",
    "Sex at birth " : "csd:demographic/csd:gender/text()",
    "Citizenship at birth" : "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:birth/text()" , 
    "Citizenship at present country of residence":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:residence/text()",
    "Ability in written languages":"csd:language[@code]/@written-ability",
    "Ability in spoken languages": "csd:language[@code]/@spoken-ability",
    "Address Country":"csd:demographic/csd:address/csd:addressLine[@component='country']/text()",
    "Address City": "csd:demographic/csd:address/csd:addressLine[@component='city']/text()" ,
    "Street Address": "csd:demographic/csd:address/csd:addressLine[@component='streetAddress']/text()",
    "Address Postal Code" :"csd:demographic/csd:address/csd:addressLine[@component='postalCode']/text()" ,
    "Telephone number" : "csd:demographic/csd:contactPoint/csd:codedType[@code='BP'  and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Email address" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMAIL' and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Emergency contact name" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMERGENCY'  and @codingScheme= 'urn:who.int:hrh:mds']/text()",
    "Professional License and Certification Document Type" : "csd:credential/csd:codedType/@code",
    "Professional License and Certification Document Category" : "csd:credential/csd:codedType/@category",
    "Professional License and Certification Issuing Institution": "csd:credential/csd:issuingAuthority/text()",
    "Professional License and Certification Date of Issue" : "csd:credential/csd:credentialIssueDate/text()",
    "Professional License and Certification Date of Expiration" : "csd:credential/csd:credentialRenewalDate/text()" ,
    "Professional License and Certification Scan/Photograph" :  "csd:credential/csd:extension[@urn ='urn:who.int:hrh:mds' and @type='photograph']/csd:image/text()" ,
    "Employment status" : "csd:record/@status" ,
    "Occupational category" : "csd:codedType/@code" ,
    "Employment title" : "csd:codedType[@code]/text()",
    "Complaints" : "csd:credential/csd:extension[@urn = 'urn:who.int:hrh:mds' and @type='complaints']/@value",
    "Data submission  institution ": "csd:record/@sourceDirectory",
    "Data submission date" : "csd:record/@updated" 
}



let $total := count($doc/csd:CSD/csd:providerDirectory/csd:provider)

let $stats := 
  map:for-each($xpaths, 
    function($label,$xpath) {
      let $matches := 
        for $provider in $doc/csd:CSD/csd:providerDirectory/csd:provider
        let $bindings := map{"provider":$provider}
	let $expr := " declare namespace csd = 'urn:ihe:iti:csd:2013'; declare variable $provider external; $provider/" || $xpath
	let $result := xquery:eval($expr,$bindings) 
	where exists($result)
	return 	$provider
      let $count:=count($matches)
      return <record><label>{$label}</label><count>{$count}</count><percent>{if ($total > 0) then floor($count div $total * 100) else "N/A"} %</percent></record>
    })


let $csv:=
  <csv >
  <record><label>Data Field</label><count>Number of Records Total of {$total}</count><percent>Percentage</percent></record>
   { 
     for $stat in $stats
     order by number($stat/count/text()) descending
     return $stat
   }
  </csv>

return csv:serialize($csv,map{ 'header': 'no', 'separator': 'tab'  })
Content-Type: text/html
URN: urn:openhie.org:openinfoman-r:stored-function:duplicate_record_field_metrics

Description



    Gets metrics on specified data fields to determine applicability of these fields for deduplication of records.  Output is text representation of result.
  

Definition

Source:
import module namespace rscript = "https://github.com/openhie/openinfoman/adapter/r";

declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;


(: 
   The query will be executed against the root element of the CSD document.    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 


rscript:html_result(/.,$careServicesRequest)
Content-Type: text/plain
URN: urn:openhie.org:openinfoman-ldif:provider_search

Description



    Gets LDIF (for LDAP) representaiton of provider search results
  

Definition

Source:

(: import the library module for ldif :)
import module namespace ldif = "https://github.com/openhie/openinfoman/adapter/ldif";

(: declare the careServicesRequest vairable as external :)
declare variable $careServicesRequest as item() external;

(: get the ldif data file for entities matching the request :)
ldif:get(/.,$careServicesRequest)

Content-Type: text/xml
URN:

Description



    Peforms a search request on a provider's common name according to the OpenSearch 1.1 Specification:
      http://www.opensearch.org/Specifications/OpenSearch/1.1
    Returns search results in opensearch feed for a provider by common name including link to free busy information on Zimbra for scheduling information.
  

Definition

Source:
import module namespace osf = "https://github.com/openhie/openinfoman/adapter/opensearch";
import module namespace functx = 'http://www.functx.com';

declare namespace csd =  "urn:ihe:iti:csd:2013";
declare namespace rss = "http://backend.userland.com/rss2";
declare namespace atom = "http://www.w3.org/2005/Atom";
declare namespace html = "http://www.w3.org/1999/xhtml";
declare namespace os  = "http://a9.com/-/spec/opensearch/1.1/";


declare variable $careServicesRequest as item() external;



(: 
   The query will be executed against the root element of the CSD document.    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 


(:Get the search terms passed in the request :)
let $search_terms := xs:string($careServicesRequest/os:searchTerms/text())
(:Find the matching providers -- to be customized for your search:)
let $filter:= function($common_name) {
  functx:contains-case-insensitive($common_name,  $search_terms)  
}
let $matched_providers :=  
  if ($search_terms) then
    for $provider in /csd:CSD/csd:providerDirectory/csd:provider
    let $common_names := $provider/csd:demographic/csd:name/csd:commonName
    where  count(filter($common_names,$filter)) > 0
    return $provider  
  else ()

let $html_func := function($provider,$doc_name,$search_name) {
  if (local-name-from-QName(node-name($provider)) = 'provider' and namespace-uri-from-QName(node-name($provider)) = "urn:ihe:iti:csd:2013") then
    let $demo:= $provider/csd:demographic[1]
    let $oid := string($provider/@oid)
    let $adapter_link := concat($careServicesRequest/@base_url,"CSD/adapter/zimbra/" , $search_name, "/" , $doc_name,"/scheduling")
    return 
      <html:li>
	<html:a href="{osf:get_entity_link($provider,$search_name)}">
	  {$demo/csd:name[1]/csd:surname/text()}, {$demo/csd:name[1]/csd:forename/text()}
	</html:a>
	<html:a href="{$adapter_link}?oid={$oid}">Scheduling with Free Busy</html:a>
	<html:div class='description_html'>{osf:get_provider_desc_html($provider,$doc_name)}</html:div>
      </html:li>
   else 
   ()
}



let $processors := map{
  'html' := $html_func
}



(:Produce the feed in the neccesary format :)
return osf:create_feed_from_entities($matched_providers,$careServicesRequest,$processors)



Content-Type: text/xml
URN: urn:openhie.org:openinfoman-rwanda:stored-function:rwanda_lookup_epid

Description



rwanda_lookup_epid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 


let $id_number := ($careServicesRequest/id_number , $careServicesRequest/csd:id_number)[1]
let $authority := ($careServicesRequest/authority , $careServicesRequest/csd:authority)[1]
let $id_type := ($careServicesRequest/id_type, $careServicesRequest/csd:id_type)[1]

let $provider := 
  if (exists($id_number) and exists($id_type) and exists($authority))
  then 
     let $provs :=   /csd:CSD/csd:providerDirectory/csd:provider[./csd:otherID[./@assigningAuthorityName = $authority  and  ./@code = $id_type  and ./text() = $id_number ]]
     return $provs[1]
  else ()

return $provider
Content-Type: text/xml
URN: urn:moh.gov.rw:extract_orgunits_rwanda:v2.19

Description



    
    Extracts Organisation Unit hierarchy and Facility/Site list from DATIM (DHIS2) as CSD Organization and Facility entities.   
    Also creates SVS for relevant terminologies (e.g. facility/site type)

    Imports: DHIS2 metadata export of Organsation Units, Organisation Unit Group,  Organisation Unit Group Set, Organization Unit Level from DHIS2 2.19
    
  

Definition

Source:
declare namespace csd = "urn:ihe:iti:csd:2013"; 

declare namespace svs = "urn:ihe:iti:svs:2008";
declare namespace dxf = "http://dhis2.org/schema/dxf/2.0";
declare namespace adx = "http://www.datim.org/adx:2015";

import module namespace datim = "http://www.datim.org";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace svs_lsvs = "https://github.com/openhie/openinfoman/svs_lsvs";
import module namespace uuid = "https://github.com/openhie/openinfoman-datim/uuid";
import module namespace functx = "http://www.functx.com";

declare variable $careServicesRequest as item() external; 


let $dxf := $careServicesRequest/file
let $datim_oid := $careServicesRequest/oid/text()
let $codelist_prefix := $careServicesRequest/codelist_prefix/text()

let $orgUnits := $dxf/dxf:metaData/dxf:organisationUnits/dxf:organisationUnit
let $orgGroups := $dxf/dxf:metaData/dxf:organisationUnitGroups/dxf:organisationUnitGroup

let $site_codes := ('FACILITY','COUNTRY','OUSCOUNTRIES','COMMUNITIY')   (:Org Unit Groups that can report data and so should have a CSD facilities :)

let $doc_name := string($careServicesRequest/@resource)
let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
let $org_dir := $doc/csd:CSD/csd:organizationDirectory
let $fac_dir := $doc/csd:CSD/csd:facilityDirectory





let $now := current-dateTime()



let $entities:= 
  for $orgUnit in $orgUnits
  let $level := xs:integer($orgUnit/@level)
  let $id := $orgUnit/@id
  let $code := $orgUnit/@code
  let $uuid := string($orgUnit/@uuid)
  let $displayName:=string($orgUnit/@name)
  let $pid:=string($orgUnit/dxf:parent/@id)
  let $puuid := $orgUnits[@id=$pid]/@uuid
  let $lm := datim:fixup_date($orgUnit/@lastUpdated)
  let $created := datim:fixup_date($orgUnit/@created)
  let $groups := $orgGroups[./dxf:organisationUnits/dxf:organisationUnit[@id = $id]]
  let $group_codes := $groups/@code
  let $facEntityID := concat("urn:uuid:",uuid:generate(concat('facility:',$id),$datim:namespace_uuid))
  let $orgEntityID := concat("urn:uuid:",uuid:generate(concat('organization:',$id),$datim:namespace_uuid))
  let $parentEntityID := concat("urn:uuid:",uuid:generate(concat('organization:',$pid),$datim:namespace_uuid))

  let $fac_entity :=
    if ($group_codes = $site_codes)
    then
      <csd:facility entityID="{$facEntityID}">
        <csd:otherID assigningAuthorityName="http://www.datim.org/orgUnit" code="id">{string($id)}</csd:otherID>
        <csd:otherID assigningAuthorityName="http://www.datim.org/orgUnit" code="code">{string($code)}</csd:otherID>
	{
	  if (not(functx:all-whitespace($uuid)))
	  then <csd:otherID assigningAuthorityName="http://www.datim.org/orgUnit" code="uuid">{string($uuid)}</csd:otherID>
	  else ()
	}
	<csd:codedType codingScheme="urn:www.datim.org" code="site"/>
	  {
	    for $group_code in $group_codes
	    return <csd:codedType codingScheme="urn:www.datim.org:org-unit-group" code="{$group_code}" />
	  }
	<csd:primaryName>{$displayName}</csd:primaryName>
	{datim:get_geocode($doc,$orgUnit)}
	{ 
	  if (not(functx:all-whitespace($puuid))) 
	  then 
            <csd:organizations>
	      <csd:organization entityID="{$parentEntityID}"/>
	    </csd:organizations>
	  else () 
	}
	<csd:record created="{$created}" updated="{$lm}" status="Active" sourceDirectory="http://www.datim.org"/>
      </csd:facility>
    else ()
  let $org_entity :=
    <csd:organization entityID="{$orgEntityID}">
      <csd:otherID assigningAuthorityName="http://www.datim.org/orgUnit" code="id">{string($id)}</csd:otherID>
      <csd:otherID assigningAuthorityName="http://www.datim.org/orgUnit" code="code">{string($code)}</csd:otherID>
      {
	if (not(functx:all-whitespace($uuid)))
	then <csd:otherID assigningAuthorityName="http://www.datim.org/orgUnit" code="uuid">{string($uuid)}</csd:otherID>
	else ()
      }
      <csd:codedType code="{$level}" codingScheme="urn:www.datim.org:org-unit-level"/>
      {
	for $group_code in $group_codes
	return <csd:codedType codingScheme="urn:www.datim.org:org-unit-group" code="{$group_code}" />
      }
      <csd:primaryName>{$displayName}</csd:primaryName>
      {datim:get_geocode($doc,$orgUnit) (:Should put in a CP to point geo codes for orgs as service delivery area :)}
      {
	if (not(functx:all-whitespace($puuid))) 
	then 
          <csd:organizations>
	    <csd:organization entityID="{$parentEntityID}"/>
	  </csd:organizations>
	else () 
      }
      <csd:record created="{$created}" updated="{$lm}" status="Active" sourceDirectory="http://www.datim.org"/>
    </csd:organization>

  return ($org_entity,$fac_entity)

	

	
let $level_oid := concat($datim_oid,'.2')
let $levels := $dxf/dxf:metaData/dxf:organisationUnitLevels/dxf:organisationUnitLevel
let $level_version := max(for $date in $levels/@lastUpdated return xs:dateTime(datim:fixup_date($date)))
let $svs_levels :=
  <svs:ValueSet  xmlns:svs="urn:ihe:iti:svs:2008" id="{$level_oid}" version="{$level_version}" displayName="Organisation Unit Levels for DATIM">
    <svs:ConceptList xml:lang="en-US" >
      {
	for $level in $levels
	return <svs:Concept code="{$level/@level}" displayName="{$level/@name}" codeSystem="urn:www.datim.org:org-unit-level" />
      }
    </svs:ConceptList>
  </svs:ValueSet>

let $group_oid := concat($datim_oid,'.3')
let $group_version := max(for $date in $orgGroups/@lastUpdated return xs:dateTime(datim:fixup_date($date)))
let $svs_groups :=
  <svs:ValueSet  xmlns:svs="urn:ihe:iti:svs:2008" id="{$group_oid}" version="{$group_version}" displayName="Organisation Unit Groups for DATIM">
    <svs:ConceptList xml:lang="en-US" >
      {
	for $group in $orgGroups
	return <svs:Concept code="{$group/@code}" displayName="{$group/@name}" codeSystem="urn:www.datim.org:org-unit-group" />
      }
    </svs:ConceptList>
  </svs:ValueSet>


let $svs_docs := ($svs_levels,$svs_groups)


return (
  for $entity in $entities
  let $id := $entity/@entityID
  return 
    if (local-name($entity) = 'facility')
    then 
      let $existing_fac := $fac_dir/csd:facility[@entityID = $id]
      return
        if (not(exists($existing_fac)))
        then (insert node $entity into $fac_dir)
        else (replace node $existing_fac with $entity)
    else
      let $existing_org := $org_dir/csd:organization[@entityID = $id]
      return
        if (not(exists($existing_org)))
        then (insert node $entity into $org_dir)
        else (replace node $existing_org with $entity)
  ,
  for $svs_doc in $svs_docs return svs_lsvs:insert($csd_webconf:db,$svs_doc) 

)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-opensearch:provider_common_name

Description



    Peforms a search request on a provider's common name according to the OpenSearch 1.1 Specification:
      http://www.opensearch.org/Specifications/OpenSearch/1.1
    Returns search results in opensearch feed for a provider by common name
  

Definition

Source:
import module namespace osf = "https://github.com/openhie/openinfoman/adapter/opensearch";
import module namespace functx = 'http://www.functx.com';

declare namespace csd =  "urn:ihe:iti:csd:2013";
declare namespace rss = "http://backend.userland.com/rss2";
declare namespace atom = "http://www.w3.org/2005/Atom";
declare namespace html = "http://www.w3.org/1999/xhtml";
declare namespace os  = "http://a9.com/-/spec/opensearch/1.1/";

declare variable $careServicesRequest as item() external;



(: 
   The query will be executed against the root element of the CSD document.    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 


(:Get the search terms passed in the request :)
let $search_terms := xs:string($careServicesRequest/os:searchTerms/text())
(:Find the matching providers -- to be customized for your search:)
let $filter:= function($common_name) {
  functx:contains-case-insensitive($common_name,  $search_terms)  
}
let $matched_providers :=  
  if ($search_terms) then
    for $provider in /csd:CSD/csd:providerDirectory/csd:provider
    let $common_names := $provider/csd:demographic/csd:name/csd:commonName
    where  count(filter($common_names,$filter)) > 0
    return $provider  
  else ()



(:Produce the feed in the neccesary format :)
return osf:create_feed_from_entities($matched_providers,$careServicesRequest)



Content-Type: text/xml
URN: urn:openhie.org:openinfoman-opensearch:provider_credenital

Description



    Peforms a search request on a provider's credential number according to the OpenSearch 1.1 Specification:
      http://www.opensearch.org/Specifications/OpenSearch/1.1
    Returns search results in opensearch feed 
  

Definition

Source:
import module namespace osf = "https://github.com/openhie/openinfoman/adapter/opensearch";
import module namespace functx = 'http://www.functx.com';

declare namespace csd = "urn:ihe:iti:csd:2013";
declare namespace rss = "http://backend.userland.com/rss2";
declare namespace atom = "http://www.w3.org/2005/Atom";
declare namespace html = "http://www.w3.org/1999/xhtml";
declare namespace os  = "http://a9.com/-/spec/opensearch/1.1/";
declare variable $careServicesRequest as item() external;


(: 
   The query will be executed against the root element of the CSD document.    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

(:Get the search terms passed in the request :)
let $search_terms := xs:string($careServicesRequest/os:searchTerms/text())
(:Find the matching providers -- to be customized for your search:)
let $filter:= function($credential) {
  functx:contains-case-insensitive($credential,  $search_terms)  
}
let $matched_providers :=  
  if ($search_terms) then
    for $provider in /csd:CSD/csd:providerDirectory/csd:provider
    let $credentials := $provider/csd:credential/csd:number
    where  count(filter($credentials,$filter)) > 0
    return $provider  
  else ()
  


let $html_func :=  function($provider ,$doc_name,$search_name) 
{
  let $demo:= $provider/csd:demographic[1]
  return 
  <html:li>
    <html:a href="{osf:get_entity_link($provider,$search_name)}">
      {$demo/csd:name[1]/csd:surname/text()}, {$demo/csd:name[1]/csd:forename/text()}
    </html:a>
    <html:div class='description_html'>
      {osf:get_provider_desc_html($provider,$doc_name)}
      <html:h2>Credentials</html:h2>
      <html:ul>
	  {
	    for $cred in $provider/csd:credential
	    return      
	      <html:li>
	        {$cred/csd:number} assigned by {$cred/csd:issuingAuthority}
	      </html:li>

	  }
      </html:ul>
    </html:div>
  </html:li> 
}


let $processors := map{
  'html' : $html_func
}


(:Produce the feed in the neccesary format :)
return osf:create_feed_from_entities($matched_providers,$careServicesRequest,$processors)



Content-Type: text/xml
URN: urn:openhie.org:openinfoman-anon:wiki-star-bible

Description



 
    Anonymizes data using biblical names for person names and star names for places (sourced from wikipedia)
  

Definition

Source:
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_lsc = "https://github.com/openhie/openinfoman/csd_lsc";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace anonymize = "https://github.com/openhie/openinfoman-anon";
import module namespace functx = "http://www.functx.com";

declare namespace csd  =  "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;

let $dest_doc := /.
let $dest := $careServicesRequest/@resource

let $values_doc := "anonymous/bible.xml"
let $fac_values_doc := "anonymous/star.xml"


let $values_src_0 := db:open($csd_webconf:db,$values_doc)
let $values_src_1 := 
 if (count($values_src_0//value[1]) > 0)  
 then $values_src_0
 else 
   let $number-for-a := string-to-codepoints('A')
   let $number-for-z := string-to-codepoints('Z')

   let $values_src := 
     <values>
       {
	 for $letter in ($number-for-a to $number-for-z)
	 let $url := concat('http://en.wikipedia.org/wiki/List_of_biblical_names_starting_with_', codepoints-to-string($letter))
	 let $resp := http:send-request(<http:request method='get' href="{$url}"/>)
 	   for $li in $resp/html/body//div[@id="mw-content-text"]/ul[1]/li
	   let $text := string-join(($li/a[1]/text(),$li/text()))
	   let $name := tokenize($text,'\W+')[1]
	   return <value>{functx:trim($name)}</value>
       }
     </values>
    return $values_src
let $values := $values_src_1//value/text()
  


let $fac_values_src_0 := db:open($csd_webconf:db,  $fac_values_doc)
let $fac_values_src_1 := 
 if (count($fac_values_src_0//value[1]) > 0)  
 then $fac_values_src_0
 else 
   let $fac_url := 'http://en.wikipedia.org/wiki/List_of_proper_names_of_stars_in_alphabetical_order'
   let $resp := http:send-request(<http:request method='get' href="{$fac_url}"/>)
  
   return
     <values>
       {
	 for $td in $resp//table[@class="wikitable"]//td[1]
	 let $text := 
	   functx:trim(string-join(($td/a[1]/text(),$td/text())))
	 return if ($text) then <value>{$text}</value> else ()
       }
     </values>


let $fac_values := $fac_values_src_1//value/text()
 

return 
(
  if (count($values_src_0//value[1]) = 0)  
  then 
     if (db:exists($csd_webconf:db, $values_doc))
     then db:replace($csd_webconf:db, $values_src_1, $values_doc)
     else db:add($csd_webconf:db, $values_src_1, $values_doc)
  else ()
  ,
  if (count($fac_values_src_0//value[1]) = 0)  
  then 
     if (db:exists($csd_webconf:db, $fac_values_doc))
     then db:replace($csd_webconf:db, $fac_values_src_1, $fac_values_doc)
     else db:add($csd_webconf:db, $fac_values_src_1, $fac_values_doc)
  else ()
  ,
  for $doc  in $careServicesRequest/documents/document
    let $name := $doc/@resource
    let $src_doc :=
      if (not ($name = $dest)) then csd_dm:open_document( $name) 
      else ()
    let $anon_doc := anonymize:document($src_doc,$values,$fac_values,$fac_values)
    return   (csd_lsc:refresh_doc($dest_doc, $anon_doc))

)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-ilr:validate_provider_facility_service

Description



    Validates a healthcare worker's entity ID.   If optional facility and service information is provided, validates that the healthcare worker is registered to perform the service at the indicated facility
  

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory/>
  <facilityDirectory/>
  <providerDirectory>
    {
      let $facility_entityID := $careServicesRequest/facility[1]/@entityID
      let $service_entityID := $careServicesRequest/facility[1]/service[1]/@entityID
	  
      (: if no provider id was provided, then this is invalid. :)
      let $provs0 := if (exists($careServicesRequest/id/@entityID))
	then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id)
      else ()   

      let $provs1 := if (exists($facility_entityID) and count($provs0) = 1)
	then 
	   if (count ($provs0[1]/facilities/facility[@entityID = $facility_entityID]) > 0) then $provs0 else ()
	else $provs0

      let $provs2 := if (exists($service_entityID) and count($provs1) = 1)
	then 
	   if (count ($provs1[1]/facilities/facility[upper-case(@entityID) = upper-case($facility_entityID)]/service[upper-case(@entityID) = upper-case($service_entityID)]) > 0) then $provs1 else ()
	else $provs1

      return if (count($provs2) = 1) then
	<provider entityID='{$provs2[1]/@entityID}'/>
      else 
	 ()
    }     
  </providerDirectory>
</CSD>
Content-Type: text/csv
URN: urn:openhie.org:openinfoman-rapidpro:get_csv_for_import

Description



 
    Creates selection menu of all the CSD organizations and faciltiies with a specified parent.  Designed as part of heierarchical facility selection menus in RapidPro webhooks.
  

Definition

Source:
import module namespace oi_csv =  "https://github.com/openhie/openinfoman/adapter/csv";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

oi_csv:get_serialized(/,$careServicesRequest)
Content-Type: application/json
URN: urn:openhie.org:openinfoman-rapidpro:get_json_for_import

Description



 
    Get JSON representation of CSD for import to RapidPro via API
  

Definition

Source:
import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";

declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;



let $careServicesSubRequest :=  
  <csd:careServicesRequest>
    <csd:function  urn="urn:ihe:iti:csd:2014:stored-function:provider-search" >
      <csd:requestParams/>
    </csd:function>
  </csd:careServicesRequest> 

let $providers := csr_proc:process_CSR_stored_results( /. , $careServicesSubRequest)


let $contacts :=  
  <json type='object'>
    <contacts type="array">
    {
      for $provider in  $providers/csd:providerDirectory/csd:provider
      let $uuid := lower-case(string($provider/@entityID))
      let $name := ($provider/csd:demographic/csd:name/csd:commonName)[1]/text()
      let $tels := $provider/csd:demographic/csd:contactPoint/csd:codedType[@code="BP" and  @codingScheme="urn:ihe:iti:csd:2013:contactPoint"]
      let $tel_1 := $tels[1]/text()
      let $tel_2 := $tels[2]/text()
      let $tel_3 := $tels[3]/text()
      return 
	if (true()) (:  ($uuid and $name)  :)
       then 
         <_  type="object">
	   <name>{$name}</name>
	   <urns type="array">
             { if ($tel_1) then   <_ type='string'>tel:{$tel_1}</_> else ()} 
             { if ($tel_2) then   <_ type='string'>tel:{$tel_2}</_> else ()} 
             { if ($tel_3) then   <_ type='string'>tel:{$tel_3}</_> else ()} 
	   </urns>
	   <fields type="object">
             <globalid>{$uuid}</globalid>
	   </fields>
         </_>
       else ()
    }
    </contacts>
  </json>


return json:serialize($contacts,map{"format":"direct"})  
Content-Type: text/html
URN: urn:openhie.org:openinfoman-rapidpro:phone_stats

Description



 
    Statistics on phone numbers
  

Definition

Source:
import module namespace functx = "http://www.functx.com";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;


let $country_code := '+231'
let $cellcom_code := '77'

let $get_clean_phones := function($provider) {
  let $all_phones := $provider/csd:demographic/csd:contactPoint/csd:codedType[@code = "BP" and @codingScheme="urn:ihe:iti:csd:2013:contactPoint"]
  let $clean_phones :=
    for $phone in $all_phones
    let $raw_phones := tokenize($phone/text(),'[/\s]+')
    let $normalized_phones := 
      for $raw_phone in $raw_phones
      let $clean_phone := replace($raw_phone,'[^\d\+]/', '')
      return 
	if (string-length($clean_phone) = 0)
	then ()
        else 
	  if (starts-with($clean_phone,'0'))
	  then concat($country_code, substring($clean_phone,2))
	  else $clean_phone
    return $normalized_phones
  return $clean_phones
}

let $clean_providers := 
  for $provider in /csd:CSD/csd:providerDirectory/csd:provider
  let $clean_phones := $get_clean_phones($provider)
  where count($clean_phones) > 0
  return $provider

let $cellcom_providers := 
  for $provider in $clean_providers 
  let $clean_phones := $get_clean_phones($provider)
  let $cellcom_phones := 
    for $clean_phone in $clean_phones
    return 
      if (starts-with($clean_phone,concat($country_code,$cellcom_code))) 
      then $clean_phone
      else ()
  where (count($cellcom_phones) > 0)
  return $provider

let $multi_providers :=
  for $provider in $clean_providers
  let $clean_phones := $get_clean_phones($provider)
  where (count($clean_phones) > 1)
  return $provider

return 
  <div>
    <ul>
      <li>Total number of health workers: {count(/csd:CSD/csd:providerDirectory/csd:provider)}</li>
      <li>Total number of health workers with phone: {count($clean_providers)}</li>
      <li>Total number of health workers with cellcom phone: {count($cellcom_providers)}</li>
      <li>Total number of health workers with multiple phones: {count($multi_providers)}</li>      
    </ul>
  </div>


Content-Type: application/json
URN: urn:openhie.org:openinfoman-rapidpro:select_facility

Description



 
    Creates selection menu of all the CSD organizations and faciltiies with a specified parent.  Designed as part of heierarchical facility selection menus in RapidPro webhooks.
  

Definition

Source:
import module namespace functx = "http://www.functx.com";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

let $t_top_orgid  :=  $careServicesRequest/query[@name = 'orgid']/text()
let $top_org :=  (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $t_top_orgid])[1]



let $selected_text := $careServicesRequest/query[@name = 'input']/text()
(:
let $selections := $careServicesRequest/values/item[./pair[@name = 'label' and ./text() = 'facilityselection']]
let $selected_text := 
  if (count($selections) > 0)
  then
    let $max_time := max(for $time in $selections/pair[@name='time'] return xs:dateTime($time))
    return $selections[./pair[@name = 'time'] = $max_time]/pair[@name='text']/text()
   else ()
:)

let $selected_index := if ($selected_text castable as xs:integer) then xs:integer($selected_text) else -1


let $selected :=
  if ($selected_index = 0)
  then
    /csd:CSD/csd:organizationDirectory/csd:organization[
      @entityID = /csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $top_org/@entityID]/csd:parent/@entityID
    ]
  else if ($selected_index > 0)
  then
    let $select_orgs := 
      if (exists($top_org))
      then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $top_org/@entityID]
      else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]
	
    let $select_facs := 
      if (exists($top_org))
      then /csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization[@entityID = $top_org/@entityID]]
      else ()
    return ($select_orgs,$select_facs)[ $selected_index]
  else ()

    
let $orgs := 
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $selected/@entityID]
  else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]
	
let $facs := 
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization[@entityID = $selected/@entityID]]
  else ()



let $output := 
  if ( local-name($selected ) = 'facility')
  then
    <json type='object'>
      <menutext>You already selected a facility.  You shouldn't see this message</menutext>
      <facility>{string($selected/@entityID)}</facility>
      <facilityname>{$selected/csd:primaryName/text()}</facilityname>
    </json>
  else  if ( local-name($selected ) = 'organization'  or not(exists($selected)))
  then
    <json type='object'>
      <menutext >
 	{ if (exists($selected)) then concat("In ", $selected/csd:primaryName/text(), ". ")  else () }
	{
	  let $parent := (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $selected/csd:parent/@entityID])[1]/csd:primaryName/text()
	  return
	    if ($parent)
	    then concat("O) Up to ", $parent, " ") 
	    else ()
        }
	{ for $ent at $pos in ($orgs,$facs)  return concat( $pos, ") ", $ent/csd:primaryName/text())    }
      </menutext>
      <orgid>{if (exists($selected)) then string($selected/@entityID) else ()}</orgid>
      <facility/>
      <facilityname/>      
    </json>
   else <json type='object'/>

(:return $output :)
return json:serialize($output,map{'format':'direct'})
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:indices_demographic_birth

Description



nigeria_health_worker_indices_demogrpahic_birth

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $provs0 := 
  if (exists($careServicesRequest/id/@entityID)) then 
    csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
  else (/CSD/providerDirectory/*)
let $provs1:=     
  for $provider in  $provs0
  return
  <provider entityID="{$provider/@entityID}">
    <demographic>
     {
       if (exists(($provider/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='birth'])[1])) then
	 <extension urn="urn:who.int:hrh:mds" type='birth'/>
       else ()
     }
    </demographic>
  </provider>
    
return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:indices_demographic_citizenship

Description



nigeria_health_worker_indices_demogrpahic_citizenship

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $provs0 := 
  if (exists($careServicesRequest/id/@entityID)) then 
    csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
  else (/CSD/providerDirectory/*)
let $provs1:=     
  for $provider in  $provs0
  return
  <provider entityID="{$provider/@entityID}">
    <demographic>
     {
       if (exists(($provider/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='citizenship'])[1])) then
	 <extension urn="urn:who.int:hrh:mds" type='citizenship'/>
       else ()
     }
    </demographic>
  </provider>
    
return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:indices_demographic_photo

Description



nigeria_health_worker_indices_demographic_photo

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
  let $provs0 := 
    if (exists($careServicesRequest/id/@entityID)) then 
      csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) 
    else (/CSD/providerDirectory/*)
  let $provs1:=     
      for $provider in  $provs0
      return
      <provider entityID="{$provider/@entityID}">
	<demographic>
	  {
	    for $name at $pos  in  $provider/demographic/extension[@type='photograph' and @urn='urn:who.int:hrh:mds']
	    return <extension type='photograph' urn='urn:who.int:hrh:mds'  position="{$pos}"/> 
	  }
	</demographic>
    </provider>
      
    return csd_bl:wrap_providers($provs1)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:read_demographic_birth

Description



nigeria_health_worker_read_demographic_birth

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/* ,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    <provider entityID="{$provs1[1]/@entityID}">
      <demographic>
	{($provs1[1]/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='birth'])[1]}
      </demographic>
    </provider>
  else ()        
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:read_demographic_citizenship

Description



nigeria_health_worker_read_demographic_citizenship

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/* ,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    <provider entityID="{$provs1[1]/@entityID}">
      <demographic>
	{($provs1[1]/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='citizenship'])[1]}
      </demographic>
    </provider>
  else ()        
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:read_demographic_photo

Description



nigeria_health_worker_read_demographic_photo

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";

declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $exts := $careServicesRequest/demographic/extension[@type='photograph' and @urn='urn:who.int:hrh:mds']
let $provs0 := if (count($exts) = 1 and exists($exts[1]/@position)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    return 
    <provider entityID="{$provider/@entityID}">
      <demographic>
	{
	  for $ext in ($provider/demographic/extension[@type='photograph' and @urn='urn:who.int:hrh:mds'])[position() = $exts[1]/@position]
	  return      <extension type='photograph' urn='urn:who.int:hrh:mds'  position="{$exts[1]/@position}">{$ext/*}</extension>
	}
      </demographic>
      {$provider/record}
    </provider>
  else ()    
    
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:read_otherid

Description



nigeria_health_worker_read_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 

let $provs0 := if (exists($careServicesRequest/otherID/@position)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $provs2 := 
  if (count($provs1) = 1) 
    then 
    let $provider :=  $provs1[1] 
    return 
    <provider entityID="{$provider/@entityID}">
      {(
	if (exists($careServicesRequest/otherID/@position))
	  then 
	  for $id in $provider/otherID[position() = $careServicesRequest/otherID/@position]
	  return       
	  <otherID 
	  position="{$careServicesRequest/otherID/@position}"
	  code="{$id/@code}"
	  expirationDate="{$id/@expirationDate}"
	  issueDate="{$id/@issueDate}"
	  assigningAuthorityName="{$id/@assigningAuthorityName}">{string($id)}</otherID>
	else
	  ()
        ,      
	$provider/record
	)}
    </provider>
  else ()    
    
return csd_bl:wrap_providers($provs2)
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:opensearch_name

Description



    Peforms a search request on a provider's common name according to the OpenSearch 1.1 Specification:
      http://www.opensearch.org/Specifications/OpenSearch/1.1
    Returns search results in opensearch feed for a provider by common name
  

Definition

Source:
import module namespace osf = "https://github.com/openhie/openinfoman/adapter/opensearch";
import module namespace functx = 'http://www.functx.com';

declare namespace csd =  "urn:ihe:iti:csd:2013";
declare namespace rss = "http://backend.userland.com/rss2";
declare namespace atom = "http://www.w3.org/2005/Atom";
declare namespace html = "http://www.w3.org/1999/xhtml";
declare namespace os  = "http://a9.com/-/spec/opensearch/1.1/";
declare variable $careServicesRequest as item() external;


(: 
   The query will be executed against the root element of the CSD document.    
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 


(:Get the search terms passed in the request :)
let $search_terms := xs:string($careServicesRequest/os:searchTerms/text())
(:Find the matching providers -- to be customized for your search:)
let $matched_providers :=  
  for $provider in /csd:CSD/csd:providerDirectory/csd:provider
  let $surname := $provider/csd:demographic/csd:name/csd:surname
  where  exists($search_terms) and exists($surname) and functx:contains-case-insensitive($surname,  $search_terms)  
  return $provider  



let $html_wrap_func :=  function($meta,$content) {
  <html:html xml:lang="en" lang="en">
    <html:head profile="http://a9.com/-/spec/opensearch/1.1/" >    

      <html:link href="/static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
      <html:link href="/static/bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>
      
      <html:script src="https://code.jquery.com/jquery.js"/>
      <script src="/static/bootstrap/js/bootstrap.min.js"/>

      <html:script src="https://code.jquery.com/jquery.js"/>
      <html:script src="/static/bootstrap/js/bootstrap.min.js"/>
      {$meta}
    </html:head>
    <html:body>  
      <html:div class="navbar navbar-inverse navbar-static-top">
	<html:div class="container">
          <html:div class="navbar-header">
	    <html:img class='pull-left' height='38px' src='/static/FMOH_Nigeria_logo.png'/>
            <html:button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <html:span class="icon-bar"></html:span>
              <html:span class="icon-bar"></html:span>
              <html:span class="icon-bar"></html:span>
            </html:button>
            <html:a class="navbar-brand" href="/CSD">Nigeria Health Workforce Registry</html:a>
          </html:div>
	</html:div>
      </html:div>
      <html:div class="container">
	<html:p align="justify" class='bold'>
	The Nigeria Health Workforce Registry (NHWR) is an information system developed and managed by the Department of Planning, Research and Statistics,
	in the Federal Ministry of Health. The Nigeria Health Workforce Registry represents the Government of Nigeria's health workforce, aggregated from the three
	tiers of the country's health system - Local, State and Federal levels.
	</html:p>
	<html:p>
	The Nigeria Health Workforce Registry implements the Care Services Directory 
	(<html:a href="ftp://ftp.ihe.net/DocumentPublication/CurrentPublished/ITInfrastructure/IHE_ITI_Suppl_CSD.pdf">CSD</html:a>)
	profile from Integrating the Health Enterprise <html:a href="http://ihe.net">(IHE)</html:a> as recommened by OpenHIE.
	</html:p>
	

	<html:p>
	  <html:b>The Nigeria Health Workforce Registry is a free, Open Source software solution.</html:b>
	</html:p>
      </html:div>
      <html:div class='wrapper_search'>
	<html:div class="container">
	  {$content}
	</html:div>
      </html:div>


      <html:div id='site_footer' class='container'>
        © 2014 Department of Planning, Research and statistics, Federal Ministry of Health. 
      </html:div>
    </html:body>
  </html:html>

}



let $processors := map{
  'html_wrap' : $html_wrap_func
}

(:Produce the feed in the neccesary format :)
return osf:create_feed_from_entities($matched_providers,$careServicesRequest,$processors)



Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:create_demographic_birth

Description



nigeria_health_worker_create_demographic_birth

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $birth :=  ($careServicesRequest/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='birth'])[1]
let $existingBirth :=  ($provs[1]/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='birth'])[1]
let $demo := $provs[1]/demographic
let $insert := 
  if (not(exists($demo))) then <demographic>{$birth}</demographic> else $birth
    let $return := 
    <provider entityID="{$provs[1]/@entityID}">
      <demographic><extension type="birth" urn="urn:who.int:hrh:mds"/></demographic>
    </provider>
let $insertTo :=
  if (not(exists($demo))) then $provs[1] else $provs[1]/demographic

return  
  if ( count($provs) = 1 and not(exists($existingBirth)))
  then
     (
      insert node $insert into $insertTo,
      csd_blu:bump_timestamp($provs[1]),
      csd_blu:wrap_updating_providers($return)
      )
  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:create_demographic_citizenship

Description



nigeria_health_worker_create_demographic_citizenship

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $citizenship :=  ($careServicesRequest/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='citizenship'])[1]
let $existingCitizenship :=  ($provs[1]/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='citizenship'])[1]
let $demo := $provs[1]/demographic
let $insert := 
  if (not(exists($demo))) then <demographic>{$citizenship}</demographic> else $citizenship
    let $return := 
    <provider entityID="{$provs[1]/@entityID}">
      <demographic><extension type="citizenship" urn="urn:who.int:hrh:mds"/></demographic>
    </provider>
let $insertTo :=
  if (not(exists($demo))) then $provs[1] else $provs[1]/demographic

return  
  if ( count($provs) = 1 and not(exists($existingCitizenship)))
  then
     (
      insert node $insert into $insertTo,
      csd_blu:bump_timestamp($provs[1]),
      csd_blu:wrap_updating_providers($return)
      )
  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:create_demographic_photo

Description



nigeria_health_worker_create_demogrpahic_photo

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";

declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $ext := $careServicesRequest/demographic/extension[@type='photograph' and urn ='urn:who.int:hrh:mds']
let $provs := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
return  
  if ( exists($ext) and count($provs) = 1 )
    then
    let $provider:= $provs[1]
    let $position := count($provider/demographic/extension[@type='photograph' and @urn='urn:who.int:hrh:mds']) +1
    let $return:=  
    <provider entityID="{$provider/@entityID}">
      <demographic>
	<extension type='photograph' urn='urn:who.int:hrh:mds' position="{$position}"/>
      </demographic>
    </provider>
    return 
      (
	if (exists($provider/demographic))
	  then insert node $ext into $provider/demographic 
	else
	  insert node <demographic>{$ext}</demographic> into $provider
	  ,   csd_blu:wrap_updating_providers($return)
	)
  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:create_other_id

Description



nigeria_health_worker_create_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provider := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id)[1] else ()
let $new_id := $careServicesRequest/otherID
return  
  if ( exists($provider) and not($new_id/@code = ''))     
    then
    let $position := count($provider/otherID) +1
    let $return:=  
      <provider entityID="{$provider/@entityID}">
	<otherID position="{$position}"/>
      </provider>
    return 
      (
	insert node $new_id into $provider ,    
	csd_blu:wrap_updating_providers($return)
      )
  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:create_provider_credenital

Description



nigeria_health_worker_create_provider_credential

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provider := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id)[1] else ()
let $cred_request := $careServicesRequest/credential
let $code:= $cred_request/codedType/@code
let $codingScheme:= $cred_request/codedType/@codingScheme
let $creds := $provider/credential[@code = $code and @codingScheme = $codingScheme]
return  
  if ( exists($provider) and count($creds) = 0 and exists($code) and exists($codingScheme))  (:DO NOT ALLOW SAME CRED TWICE :)
    then
    let $return:=  
      <provider entityID="{$provider/@entityID}">
	<credential>
	  <codedType code="{$code}" codingScheme="{$codingScheme}"/>
	</credential>
      </provider>
    let $cred_new :=
      <credential>
	<codedType code="{$code}" codingScheme="{$codingScheme}"/>
	{(
	  if (exists($cred_request/number)) then $cred_request/number else (),
	  if (exists($cred_request/issuingAuthority)) then $cred_request/issuingAuthority else (),
	  if (exists($cred_request/credentialIssueDate)) then $cred_request/credentialIssueDate else (),
	  if (exists($cred_request/credentialRenewalDate)) then $cred_request/credentialRenewalDate else (),
	  if (exists($cred_request/extension[@urn='urn:who.int:hrh:mds' and @type='photograph']/image)) then $cred_request/extension[@urn='urn:who.int:hrh:mds' and @type='photograph'] else ()
	 )}
      </credential>
    return 
	(
	insert node $cred_new into $provider,
	csd_blu:wrap_updating_providers($return)
	)

  else  csd_blu:wrap_updating_providers(())
      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:delete_demographic_birth

Description



nigeria_health_worker_delete_demogrpahic_birth

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $providers := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
return
  if ( count($providers) = 1 )
    then
    let $birth := ($providers[1]/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='birth'])
    return if (exists($birth)) then (delete node $birth) else ()
  else  ()

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:delete_demogrpahic_citizenship

Description



nigeria_health_worker_delete_demogrpahic_citizenship

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $providers := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
return
  if ( count($providers) = 1 )
    then
    let $citizenship := ($providers[1]/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='citizenship'])
    return if (exists($citizenship)) then (delete node $citizenship) else ()
  else  ()

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:delete_demographic_photo

Description



nigeria_health_worker_delete_demogrpahic_photo

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";

declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:) 
let $pos := $careServicesRequest/demographic/extension[@type='photograph' and @urn='urn:who.int:hrh:mds']/@position
return
  if (exists($pos)) 
    then 
    let $providers := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
    return
      if ( count($providers) = 1 )
	then
	let  $ext :=  ($providers[1]/demographic/extension[@type='photograph' and @urn='urn:who.int:hrh:mds'])[position() = $pos]
	return if (exists($ext)) then (delete node $ext) else ()
      else  ()
    else ()      
Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:update_demographic_birth

Description



nigeria_health_worker_update_demogrpahic_birth

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $updBirth :=  ($careServicesRequest/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='birth'])[1]
let $existBirth := ($provs[1]/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='birth'])[1]

return  
  if ( count($provs) = 1 and exists( $existBirth ) and exists($updBirth)) then
   (
     if (exists($updBirth/country))
       then 	    
       if (exists($existBirth/country))
	 then  replace value of node $existBirth/country with $updBirth/country
       else insert node  $updBirth/country into $existBirth
     else (),
     if (exists($updBirth/town))
       then 	    
       if (exists($existBirth/town))
	 then  replace value of node $existBirth/town with $updBirth/town
       else insert node  $updBirth/town into $existBirth
     else (),
     if (exists($updBirth/motherName))
       then 	    
       if (exists($existBirth/motherName))
	 then  replace value of node $existBirth/motherName with $updBirth/motherName
       else insert node  $updBirth/motherName into $existBirth
     else (),
     if (exists($updBirth/fatherName))
       then 	    
       if (exists($existBirth/fatherName))
	 then  replace value of node $existBirth/fatherName with $updBirth/fatherName
       else insert node  $updBirth/fatherName into $existBirth
     else (),	    
     csd_blu:bump_timestamp($provs[1]),
     let $return := 
     <provider entityID="{$provs[1]/@entityID}">
       <demographic><extension type="birth" urn="urn:who.int:hrh:mds"/></demographic>
     </provider>
     return csd_blu:wrap_updating_providers($return)
    )
  else 	csd_blu:wrap_updating_providers(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:update_demogrpahic_citizenship

Description



nigeria_health_worker_update_demogrpahic_citizenship

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $updCitizen :=  ($careServicesRequest/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='citizenship'])[1]
let $existCitizen := ($provs[1]/demographic/extension[@urn='urn:who.int:hrh:mds' and @type='citizenship'])[1]

return  
  if ( count($provs) = 1 and exists( $existCitizen ) and exists($updCitizen)) then
   (
     if (exists($updCitizen/residence))
       then 	    
       if (exists($existCitizen/residence))
	 then  replace value of node $existCitizen/residence with $updCitizen/residence
       else insert node  $updCitizen/residence into $existCitizen
     else (),
     if (exists($updCitizen/current))
       then 	    
       if (exists($existCitizen/current))
	 then  replace value of node $existCitizen/current with $updCitizen/current
       else insert node  $updCitizen/current into $existCitizen
     else (),
     if (exists($updCitizen/birth))
       then 	    
       if (exists($existCitizen/birth))
	 then  replace value of node $existCitizen/birth with $updCitizen/birth
       else insert node  $updCitizen/birth into $existCitizen
     else (),
     csd_blu:bump_timestamp($provs[1]),
     let $return := 
     <provider entityID="{$provs[1]/@entityID}">
       <demographic><extension type='citizenship' urn="urn:who.int:hrh:mds"/></demographic>
     </provider>
     return csd_blu:wrap_updating_providers($return)
    )
  else 	csd_blu:wrap_updating_providers(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:update_demographic_photo

Description



nigeria_health_worker_update_demogrpahic_phto

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";

declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $new_ext := $careServicesRequest/demographic/extension[@type='photograph' and @urn='urn:who.int:hrh:mds']
let $provs0 := if (exists($new_ext/@position)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $ext := ($provs1[1]/demographic/extension[@type='photograph' and @urn='urn:who.int:hrh:mds'])[position() = $new_ext/@position]
return
  if (count($provs1) = 1 and exists($ext)) 
    then
    let $provs2 := 
    <provider entityID="{$provs1[1]/@entityID}">
      <demographic>
	<extension type='photograph' urn='urn:who.int:hrh:mds' position="{$new_ext/@position}"/>
      </demographic>
    </provider>
    return
      (
	csd_blu:bump_timestamp($provs1[1]),
	replace  node $ext with $new_ext,
	csd_blu:wrap_updating_providers($provs2)
     )
  else 	csd_blu:wrap_updating_providers(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:update_otherid

Description



nigeria_health_worker_update_otherid

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   
let $provs0 := if (exists($careServicesRequest/otherID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $id := $provs1[1]/otherID[position() = $careServicesRequest/otherID/@position]
return
  if (count($provs1) = 1 and exists($id)) 
    then
    let $provs2 := 
    <provider entityID="{$provs1[1]/@entityID}">
      <otherID position="{$careServicesRequest/otherID/@position}"/>
    </provider>
    return
      (
	csd_blu:bump_timestamp($provs1[1]),
	if ($careServicesRequest/otherID/@code) 
	  then 	    
	    if (exists($id/@code))
	      then  (replace value of node $id/@code with $careServicesRequest/otherID/@code)
	      else (insert node  $careServicesRequest/otherID/@code into $id)
	  else (),
	if (exists($careServicesRequest/otherID/@assigningAuthorityName) )
	  then 
	    if (exists($id/@assigningAuthorityName))
	      then replace value of node $id/@assigningAuthorityName with $careServicesRequest/otherID/@assigningAuthorityName
	      else insert node $careServicesRequest/otherID/@assigningAuthorityName into $id		
	  else (),
	if (exists($careServicesRequest/otherID/@issueDate) )
	  then 
	    if (exists($id/@issueDate))
	      then replace value of node $id/@issueDate with $careServicesRequest/otherID/@issueDate
	      else insert node $careServicesRequest/otherID/@issueDate into $id		
	  else (),
	if (exists($careServicesRequest/otherID/@expirationDate) )
	  then 
	    if (exists($id/@expirationDate))
	      then replace value of node $id/@expirationDate with $careServicesRequest/otherID/@expirationDate
	      else insert node $careServicesRequest/otherID/@expirationDate into $id		
	  else (),
	if (not(string($careServicesRequest/otherID) = '')) 
	  then (replace value of node $id with string($careServicesRequest/otherID))
	  else (),
	csd_blu:wrap_updating_providers($provs2)
     )
  else 	csd_blu:wrap_updating_providers(())

Content-Type: text/xml
URN: urn:openhie.org:openinfoman-hwr-nigeria:stored-function:update_provider_credenital

Description



nigeria_health_worker_update_provider_credential

Definition

Source:
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";

import module namespace csd_blu = "https://github.com/openhie/openinfoman/csd_blu";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(: 
   The query will be executed against the root element of the CSD document.
   
   The dynamic context of this query has $careServicesRequest set to contain any of the search 
   and limit paramaters as sent by the Service Finder
:)   

let $provs0 := if (exists($careServicesRequest/id/@entityID)) then	csd_bl:filter_by_primary_id(/CSD/providerDirectory/*,$careServicesRequest/id) else ()
let $provs1 := if (count($provs0) = 1) then $provs0 else ()
let $provs2 := if (exists($careServicesRequest/credential/codedType/@code) and exists($careServicesRequest/credential/codedType/@codingScheme) ) then $provs1  else ()
let $cred_new := $careServicesRequest/credential
let $code:= $cred_new/codedType/@code
let $codingScheme:= $cred_new/codedType/@codingScheme
let $creds0 := $provs2/credential/codedType[@code = $code and @codingScheme = $codingScheme]
return  
  if ( count($provs2) = 1 and count($creds0) = 1)  (:Update only:)
    then
    let $cred_old := $creds0[1]/..
    let $provider:= $provs2[1]
    let $provs3 := 
      <provider entityID="{$provider/@entityID}">
	<credential>
	  <codedType code="{$code}" codingScheme="{$codingScheme}"/>
	</credential>
      </provider>


    return
      
      (
	csd_blu:bump_timestamp($provider),
	if (exists($cred_new/issuingAuthority)) then
	  (if (exists($cred_old/issuingAuthority)) then (delete node $cred_old/issuingAuthority) else (),
	  insert node $cred_new/issuingAuthority into $cred_old)
	else (),
	if (exists($cred_new/number)) then
	  (if (exists($cred_old/number)) then (delete node $cred_old/number) else (),
	  insert node $cred_new/number into $cred_old)
	else (),
	if (exists($cred_new/credentialIssueDate)) then
	  (if (exists($cred_old/credentialIssueDate)) then (delete node $cred_old/credentialIssueDate) else (),
	  insert node $cred_new/credentialIssueDate into $cred_old)
	else (),
	if (exists($cred_new/credentialRenewalDate)) then
	  (if (exists($cred_old/credentialRenewalDate)) then (delete node $cred_old/credentialRenewalDate) else (),
	  insert node $cred_new/credentialRenewalDate into $cred_old)
	else (),
	if (exists($cred_new/extension[@urn='urn:who.int:hrh:mds' and @type='photograph']/image)) then
	  (if (exists($cred_old/extension[@urn='urn:who.int:hrh:mds' and @type='photograph'])) then (delete node $cred_old/extension[@urn='urn:who.int:hrh:mds' and @type='photograph']) else (),
	  insert node $cred_new/extension[@urn='urn:who.int:hrh:mds' and @type='photograph'] into $cred_old	   )
	else (),

	csd_blu:wrap_updating_providers($provs3)
       )
  else 	csd_blu:wrap_updating_providers(())