Přeskočit obsah
For the complete DHIS2 documentation index, see llms.txt.

Tracker (deprecated APIs)

Caution

Tracker has been re-implemented in DHIS2 2.36. The new endpoints are documented at Tracker.

Endpoints

  • GET/POST/PUT/DELETE /api/trackedEntityInstance
  • GET/POST/PUT/DELETE /api/enrollments
  • GET/POST/PUT/DELETE /api/events
  • GET/POST/PUT/DELETE /api/relationships

will be removed in version 42!

  • If you plan to use the tracker endpoints use the new endpoints described in Tracker
  • If you are still using the deprecated tracker endpoints in production, please migrate over to the new endpoints. Migrating to new tracker endpoints should help you get started. Reach out on the community of practice if you need further assistance.

Migrating to new tracker endpoints

The following sections highlight the important differences between the deprecated endpoints.

  • GET/POST/PUT/DELETE /api/trackedEntityInstance
  • GET/POST/PUT/DELETE /api/enrollments
  • GET/POST/PUT/DELETE /api/events
  • GET/POST/PUT/DELETE /api/relationships

and the newly introduced endpoints

  • POST /api/tracker
  • GET /api/tracker/trackedEntities
  • GET /api/tracker/enrollments
  • GET /api/tracker/events
  • GET /api/tracker/relationships

Property names

API property names have changed so they are consistent across all the endpoints. The following table lists the old and new property names.

Objekt trasování Dříve Nyní
Atribut created
lastUpdated
createdAt
updatedAt
DataValue created
lastUpdated
createByUserInfo
lastUpdatedByUserInfo
createdAt
updatedAt
createdBy
updatedBy
Zápis created
createdAtClient
lastUpdated
lastUpdatedAtClient
trackedEntityInstance
enrollmentDate
incidentDate
completedDate
createByUserInfo
lastUpdatedByUserInfo
createdAt
createdAtClient
updatedAt
updatedAtClient
trackedEntity
enrolledAt
occurredAt
completedAt
createdBy
updatedBy
Událost trackedEntityInstance
eventDate
dueDate
created
createdAtClient
lastUpdated
lastUpdatedAtClient
completedDate
createByUserInfo
lastUpdatedByUserInfo
assignedUser*
trackedEntity
occurredAt
scheduledAt
createdAt
createdAtClient
updatedAt
updatedAtClient
completedAt
createdBy
updatedBy
assignedUser*
Poznámka storedDate
lastUpdatedBy
storedAt
createdBy
ProgramOwner ownerOrgUnit
trackedEntityInstance
orgUnit
trackedEntity
RelationshipItem trackedEntityInstance.trackedEntityInstance
enrollment.enrollment
event.event
trackedEntity
enrollment
event
Vztah created
lastUpdated
createdAt
updatedAt
TrackedEntity trackedEntityInstance
created
createdAtClient
lastUpdated
lastUpdatedAtClient
createByUserInfo
lastUpdatedByUserInfo
trackedEntity
createdAt
createdAtClient
updatedAt
updatedAtClient
createdBy
updatedBy

Note

Property assignedUser was a string before and is now an object of the following shape (type User):

{
   "assignedUser": {
     "uid": "ABCDEF12345",
     "username": "username",
     "firstName": "John",
     "surname": "Doe"
   }
}

Semicolon as separator for identifiers (UID)

Fields or query parameter accepting multiple values like UIDs are now consistently separated by comma instead of semicolon. This is to ensure UIDs are consistently separated by comma across all DHIS2 endpoints.

The following fields are affected

  • event.attributeCategoryOptions (as well as an event returned as part of a relationship from/to)

Tracker import changelog (POST)

The previous tracker import endpoints

  • POST/PUT/DELETE /api/trackedEntityInstance
  • POST/PUT/DELETE /api/enrollments
  • POST/PUT/DELETE /api/events
  • POST/PUT/DELETE /api/relationships

are replaced by the new endpoint

  • POST /api/tracker

Tracker Import describes how to use this new endpoint.

Tracker export changelog (GET)

In addition to the changed names shown in Property names some request parameters have been changed as well.

The following tables list the differences in old and new request parameters for GET endpoints.

Request parameter changes for GET /api/tracker/trackedEntities

Dříve Nyní
assignedUser assignedUsers
Values are now separated by comma instead of semicolon.
attachment Removed
attribute Removed - use filter instead
eventStartDate
eventEndDate
eventOccurredAfter
eventOccurredBefore
includeAllAttributes Removed
lastUpdatedStartDate
lastUpdatedEndDate
lastUpdatedDuration
updatedAfter
updatedBefore
updatedWithin
ouMode orgUnitMode
ou orgUnits
Values are now separated by comma instead of semicolon.
programEnrollmentStartDate
programEnrollmentEndDate
enrollmentEnrolledAfter
enrollmentEnrolledBefore
programIncidentStartDate
programIncidentEndDate
enrollmentOccurredAfter
enrollmentOccurredBefore
programStartDate
programEndDate
Odebráno – zastaralé, viz
  • enrollmentEnrolledAfter
  • enrollmentEnrolledBefore
query Removed - use filter instead
skipMeta Removed
skipPaging paging
Is the inverse so paging=false replaces skipPaging=true.
trackedEntityInstance trackedEntities
Values are now separated by comma instead of semicolon.

Request parameter changes for GET /api/tracker/enrollments

Dříve Nyní
enrollment enrollments
Values are now separated by comma instead of semicolon.
lastUpdated
lastUpdatedDuration
updatedAfter
updatedWithin
ouMode orgUnitMode
ou orgUnits
Values are now separated by comma instead of semicolon.
programStartDate
programEndDate
enrolledAfter
enrolledBefore
skipPaging paging
Is the inverse so paging=false replaces skipPaging=true.
trackedEntityInstance trackedEntity

Request parameter changes for GET /api/tracker/events

Dříve Nyní
assignedUser assignedUsers
Values are now separated by comma instead of semicolon.
attachment Removed
attributeCc attributeCategoryCombo
attributeCos attributeCategoryOptions
Values are now separated by comma instead of semicolon.
dueDateStart
dueDateEnd
scheduledAfter
scheduledBefore
event events
Values are now separated by comma instead of semicolon.
lastUpdatedStartDate
lastUpdatedEndDate
lastUpdatedDuration
updatedAfter
updatedBefore
updatedWithin
lastUpdated Odebráno - zastaralé, viz:
  • 01cupdatedAfter
  • updatedBefore
ouMode orgUnitMode
skipEventId Removed
skipMeta Removed
skipPaging paging
Is the inverse so paging=false replaces skipPaging=true.
startDate
endDate
occurredAfter
occurredBefore
startDate
endDate
occurredAfter
occurredBefore
trackedEntityInstance trackedEntity

Request parameter changes for GET /api/tracker/relationships

Dříve Nyní
skipPaging paging
Is the inverse so paging=false replaces skipPaging=true.
tei trackedEntity

Web API Trasovače

Tracker Web API consists of 3 endpoints that have full CRUD (create, read, update, delete) support. The 3 endpoints are /api/trackedEntityInstances, /api/enrollments and /api/events and they are responsible for tracked entity instance, enrollment and event items.

Správa instance trasované entity

Tracked entity instances have full CRUD support in the API. Together with the API for enrollment most operations needed for working with tracked entity instances and programs are supported.

/api/33/trackedEntityInstances

Vytváření nové instance trasované entity

For creating a new person in the system, you will be working with the trackedEntityInstances resource. A template payload can be seen below:

{
  "trackedEntity": "tracked-entity-id",
  "orgUnit": "org-unit-id",
  "geometry": "<Geo JSON>",
  "attributes": [{
    "attribute": "attribute-id",
    "value": "attribute-value"
  }]
}

The field "geometry" accepts a GeoJson object, where the type of the GeoJson have to match the featureType of the TrackedEntityType definition. An example GeoJson object looks like this:

{
  "type": "Point",
  "coordinates": [1, 1]
}

The "coordinates" field was introduced in 2.29, and accepts a coordinate or a polygon as a value.

For getting the IDs for relationship and attributes you can have a look at the respective resources relationshipTypes, trackedEntityAttributes. To create a tracked entity instance you must use the HTTP POST method. You can post the payload the following URL:

/api/trackedEntityInstances

For example, let us create a new instance of a person tracked entity and specify its first name and last name attributes:

{
  "trackedEntity": "nEenWmSyUEp",
  "orgUnit": "DiszpKrYNg8",
  "attributes": [
    {
      "attribute": "w75KJ2mc4zz",
      "value": "Joe"
    },
    {
      "attribute": "zDhUuAYrxNC",
      "value": "Smith"
    }
  ]
}

Chcete-li to odeslat na server, můžete použít příkaz cURL takto:

curl -d @tei.json "https://play.dhis2.org/demo/api/trackedEntityInstances" -X POST
  -H "Content-Type: application/json" -u admin:district

To create multiple instances in one request you can wrap the payload in an outer array like this and POST to the same resource as above:

{
  "trackedEntityInstances": [
    {
      "trackedEntity": "nEenWmSyUEp",
      "orgUnit": "DiszpKrYNg8",
      "attributes": [
        {
          "attribute": "w75KJ2mc4zz",
          "value": "Joe"
        },
        {
          "attribute": "zDhUuAYrxNC",
          "value": "Smith"
        }
      ]
    },
    {
      "trackedEntity": "nEenWmSyUEp",
      "orgUnit": "DiszpKrYNg8",
      "attributes": [
        {
          "attribute": "w75KJ2mc4zz",
          "value": "Jennifer"
        },
        {
          "attribute": "zDhUuAYrxNC",
          "value": "Johnson"
        }
      ]
    }
  ]
}

The system does not allow the creation of a tracked entity instance (as well as enrollment and event) with a UID that was already used in the system. That means that UIDs cannot be reused.

Aktualizace instance trasované entity

For updating a tracked entity instance, the payload is equal to the previous section. The difference is that you must use the HTTP PUT method for the request when sending the payload. You will also need to append the person identifier to the trackedEntityInstances resource in the URL like this, where <tracked-entity-instance-identifier> should be replaced by the identifier of the tracked entity instance:

/api/trackedEntityInstances/<tracked-entity-instance-id>

The payload has to contain all, even non-modified, attributes and relationships. Attributes or relationships that were present before and are not present in the current payload any more will be removed from the system. This means that if attributes/relationships are empty in the current payload, all existing attributes/relationships will be deleted from the system. From 2.31, it is possible to ignore empty attributes/relationships in the current payload. A request parameter of ignoreEmptyCollection set to true can be used in case you do not wish to send in any attributes/relationships and also do not want them to be deleted from the system.

It is not allowed to update an already deleted tracked entity instance. Also, it is not allowed to mark a tracked entity instance as deleted via an update request. The same rules apply to enrollments and events.

Odstranění instance trasované entity

In order to delete a tracked entity instance, make a request to the URL identifying the tracked entity instance with the DELETE method. The URL is equal to the one above used for update.

Vytvářejte a zapisujte instance trasovaných entit

It is also possible to both create (and update) a tracked entity instance and at the same time enroll into a program.

{
  "trackedEntity": "tracked-entity-id",
  "orgUnit": "org-unit-id",
  "attributes": [{
    "attribute": "attribute-id",
    "value": "attribute-value"
  }],
  "enrollments": [{
    "orgUnit": "org-unit-id",
    "program": "program-id",
    "enrollmentDate": "2013-09-17",
    "incidentDate": "2013-09-17"
   }, {
    "orgUnit": "org-unit-id",
    "program": "program-id",
    "enrollmentDate": "2013-09-17",
    "incidentDate": "2013-09-17"
   }]
}

You would send this to the server as you would normally when creating or updating a new tracked entity instance.

curl -X POST -d @tei.json -H "Content-Type: application/json"
  -u user:pass "http://server/api/33/trackedEntityInstances"

Kompletní příklad datového obsahu včetně: instance trasované entity, registrace a události

It is also possible to create (and update) a tracked entity instance, at the same time enroll into a program and create an event.

{
  "trackedEntityType": "nEenWmSyUEp",
  "orgUnit": "DiszpKrYNg8",
  "attributes": [
    {
      "attribute": "w75KJ2mc4zz",
      "value": "Joe"
    },
    {
      "attribute": "zDhUuAYrxNC",
      "value": "Rufus"
    },
    {
      "attribute": "cejWyOfXge6",
      "value": "Male"
    }
  ],
  "enrollments": [
    {
      "orgUnit": "DiszpKrYNg8",
      "program": "ur1Edk5Oe2n",
      "enrollmentDate": "2017-09-15",
      "incidentDate": "2017-09-15",
      "events": [
        {
          "program": "ur1Edk5Oe2n",
          "orgUnit": "DiszpKrYNg8",
          "eventDate": "2017-10-17",
          "status": "COMPLETED",
          "storedBy": "admin",
          "programStage": "EPEcjy3FWmI",
          "coordinate": {
            "latitude": "59.8",
            "longitude": "10.9"
          },
          "dataValues": [
            {
              "dataElement": "qrur9Dvnyt5",
              "value": "22"
            },
            {
              "dataElement": "oZg33kd9taw",
              "value": "Male"
            }
          ]
        },
        {
          "program": "ur1Edk5Oe2n",
          "orgUnit": "DiszpKrYNg8",
          "eventDate": "2017-10-17",
          "status": "COMPLETED",
          "storedBy": "admin",
          "programStage": "EPEcjy3FWmI",
          "coordinate": {
            "latitude": "59.8",
            "longitude": "10.9"
          },
          "dataValues": [
            {
              "dataElement": "qrur9Dvnyt5",
              "value": "26"
            },
            {
              "dataElement": "oZg33kd9taw",
              "value": "Female"
            }
          ]
        }
      ]
    }
  ]
}

You would send this to the server as you would normally when creating or updating a new tracked entity instance.

curl -X POST -d @tei.json -H "Content-Type: application/json"
  -u user:pass "http://server/api/33/trackedEntityInstances"

Vygenerované atributy instance trasované entity

Tracked entity instance attributes that are using automatic generation of unique values have three endpoints that are used by apps. The endpoints are all used for generating and reserving values.

In 2.29 we introduced TextPattern for defining and generating these patterns. All existing patterns will be converted to a valid TextPattern when upgrading to 2.29.

Note

As of 2.29, all these endpoints will require you to include any variables reported by the requiredValues endpoint listed as required. Existing patterns, consisting of only #, will be upgraded to the new TextPattern syntax RANDOM(<old-pattern>). The RANDOM segment of the TextPattern is not a required variable, so this endpoint will work as before for patterns defined before 2.29.

Nalezení požadovaných hodnot

A TextPattern can contain variables that change based on different factors. Some of these factors will be unknown to the server, so the values for these variables have to be supplied when generating and reserving values.

This endpoint will return a map of required and optional values, that the server will inject into the TextPattern when generating new values. Required variables have to be supplied for the generation, but optional variables should only be supplied if you know what you are doing.

GET /api/33/trackedEntityAttributes/Gs1ICEQTPlG/requiredValues
{
  "REQUIRED": [
    "ORG_UNIT_CODE"
  ],
  "OPTIONAL": [
    "RANDOM"
  ]
}
Generovat koncový bod hodnoty

Online web apps and other clients that want to generate a value that will be used right away can use the simple generate endpoint. This endpoint will generate a value that is guaranteed to be unique at the time of generation. The value is also guaranteed not to be reserved. As of 2.29, this endpoint will also reserve the value generated for 3 days.

If your TextPattern includes required values, you can pass them as parameters like the example below:

The expiration time can also be overridden at the time of generation, by adding the ?expiration=<number-of-days> to the request.

GET /api/33/trackedEntityAttributes/Gs1ICEQTPlG/generate?ORG_UNIT_CODE=OSLO
{
  "ownerObject": "TRACKEDENTITYATTRIBUTE",
  "ownerUid": "Gs1ICEQTPlG",
  "key": "RANDOM(X)-OSL",
  "value": "C-OSL",
  "created": "2018-03-02T12:01:36.680",
  "expiryDate": "2018-03-05T12:01:36.678"
}
Generovat a rezervovat koncový bod hodnoty

The generate and reserve endpoint is used by offline clients that need to be able to register tracked entities with unique ids. They will reserve a number of unique ids that this device will then use when registering new tracked entity instances. The endpoint is called to retrieve a number of tracked entity instance reserved values. An optional parameter numberToReserve specifies how many ids to generate (default is 1).

If your TextPattern includes required values, you can pass them as parameters like the example below:

Similar to the /generate endpoint, this endpoint can also specify the expiration time in the same way. By adding the ?expiration=<number-of-days> you can override the default 60 days.

GET /api/33/trackedEntityAttributes/Gs1ICEQTPlG/generateAndReserve?numberToReserve=3&ORG_UNIT_CODE=OSLO
[
  {
    "ownerObject": "TRACKEDENTITYATTRIBUTE",
    "ownerUid": "Gs1ICEQTPlG",
    "key": "RANDOM(X)-OSL",
    "value": "B-OSL",
    "created": "2018-03-02T13:22:35.175",
    "expiryDate": "2018-05-01T13:22:35.174"
  },
  {
    "ownerObject": "TRACKEDENTITYATTRIBUTE",
    "ownerUid": "Gs1ICEQTPlG",
    "key": "RANDOM(X)-OSL",
    "value": "Q-OSL",
    "created": "2018-03-02T13:22:35.175",
    "expiryDate": "2018-05-01T13:22:35.174"
  },
  {
    "ownerObject": "TRACKEDENTITYATTRIBUTE",
    "ownerUid": "Gs1ICEQTPlG",
    "key": "RANDOM(X)-OSL",
    "value": "S-OSL",
    "created": "2018-03-02T13:22:35.175",
    "expiryDate": "2018-05-01T13:22:35.174"
  }
]
Rezervované hodnoty

Reserved values are currently not accessible through the api, however, they are returned by the generate and generateAndReserve endpoints. The following table explains the properties of the reserved value object:

Tabulka: Rezervované hodnoty

Vlastnictví Popis
ownerObject Typ metadat odkazovaný při generování a rezervaci hodnoty. V současné době je podporován pouze TRACKEDENTITYATTRIBUTE.
ownerUid Uid objektu metadat odkazovaného při generování a rezervaci hodnoty.
key Částečně generovaná hodnota, kde generované segmenty ještě nejsou přidány.
value Plně vyřešená hodnota vyhrazena. Toto je hodnota, kterou odesíláte na server při ukládání dat.
created Časové razítko, kdy byla rezervace provedena
expiryDate Časové razítko, kdy rezervace již nebude rezervována

Expired reservations are removed daily. If a pattern changes, values that were already reserved will be accepted when storing data, even if they don't match the new pattern, as long as the reservation has not expired.

Atributy obrázku

Working with image attributes is a lot like working with file data values. The value of an attribute with the image value type is the id of the associated file resource. A GET request to the /api/trackedEntityInstances/<entityId>/<attributeId>/image endpoint will return the actual image. The optional height and width parameters can be used to specify the dimensions of the image.

curl "http://server/api/33/trackedEntityInstances/ZRyCnJ1qUXS/zDhUuAYrxNC/image?height=200&width=200"
  > image.jpg

The API also supports a dimension parameter. It can take three possible values (please note capital letters): SMALL (254x254), MEDIUM (512x512), LARGE (1024x1024) or ORIGINAL. Image type attributes will be stored in pre-generated sizes and will be furnished upon request based on the value of the dimension parameter.

curl "http://server/api/33/trackedEntityInstances/ZRyCnJ1qUXS/zDhUuAYrxNC/image?dimension=MEDIUM"

File attributes

Working with file attributes is a lot like working with image data values. The value of an attribute with the file value type is the id of the associated file resource. A GET request to the /api/trackedEntityInstances/<entityId>/<attributeId>/file endpoint will return the actual file content.

curl "http://server/api/trackedEntityInstances/ZRyCnJ1qUXS/zDhUuAYrxNC/file

Dotaz na instanci trasované entity

To query for tracked entity instances you can interact with the /api/trackedEntityInstances resource.

/api/33/trackedEntityInstances
Požádat o syntaxi

Tabulka: Parametry dotazu instancí trasovaných entit

Parametr dotazu Popis
filtr Atributy, které se mají použít jako filtr pro dotaz. Parametr lze opakovat libovolněkrát. Filtry lze použít na rozměr ve formátu <attribute-id>:<operator>:<filter>[:<operator>:<filter>]. Hodnoty filtru nerozlišují velká a malá písmena a lze je spolu s operátorem opakovat libovolněkrát. Operátory mohou být EQ | GT | GE | LT | LE | NE | LIKE | V.
ou Identifikátory organizační jednotky oddělené „;“.
ouMode Režim výběru organizačních jednotek lze SELECTED | CHILDREN | DESCENDANTS | ACCESSIBLE | CAPTURE | ALL. Výchozí hodnota je SELECTED, což se týká pouze vybraných vybraných organizačních jednotek. Vysvětlení viz tabulka níže.
program Identifikátor programu. Omezuje instance na přihlášení do daného programu.
programStatus Stav instance pro daný program. Může být AKTIVNÍ | DOKONČENO | ZRUŠENO.
followUp Sledovat stav instance pro daný program. Může to být true | false nebo omitted.
programStartDate Datum zahájení zápisu v daném programu pro instanci trasované entity.
programEndDate Datum ukončení zápisu v daném programu pro instanci trasované entity.
trackedEntity Identifikátor trasované entity. Omezuje instance na daný typ trasované instance.
strana Číslo stránky. Výchozí stránka je 1.
pageSize Velikost stránky. Výchozí velikost je 50 řádků na stránku.
totalPages Označuje, zda se má do odpovědi stránkování zahrnout celkový počet stránek (znamená delší dobu odezvy).
skipPaging Označuje, zda má být stránkování ignorováno a mají být vráceny všechny řádky.
lastUpdatedStartDate Filter for teis which were updated after this date. Cannot be used together with lastUpdatedDuration.
lastUpdatedEndDate Filter for teis which were updated up until this date. Cannot be used together with lastUpdatedDuration.
lastUpdatedDuration Include only items which are updated within the given duration. The format is , where the supported time units are “d” (days), “h” (hours), “m” (minutes) and “s” (seconds). Cannot be used together with lastUpdatedStartDate and/or lastUpdatedEndDate.
assignedUserMode Restricts result to tei with events assigned based on the assigned user selection mode, can be CURRENT | PROVIDED | NONE | ANY. See table below "Assigned user modes" for explanations.
assignedUser Filter the result down to a limited set of teis with events that are assigned to the given user IDs by using assignedUser=id1;id2.This parameter will be considered only if assignedUserMode is either PROVIDED or null. The API will error out, if for example, assignedUserMode=CURRENT and assignedUser=someId
trackedEntityInstance Filter the result down to a limited set of teis using explicit uids of the tracked entity instances by using trackedEntityInstance=id1;id2. This parameter will at the very least create the outer boundary of the results, forming the list of all teis using the uids provided. If other parameters/filters from this table are used, they will further limit the results from the explicit outer boundary.
includeDeleted Označuje, zda zahrnout měkké odstraněné TEI nebo ne. Ve výchozím nastavení je fase.
potentialDuplicate Filter the result based on the fact that a TEI is a Potential Duplicate. true: return TEIs flagged as Potential Duplicates. false: return TEIs NOT flagged as Potential Duplicates. If omitted, we don't check whether a TEI is a Potential Duplicate or not.

The available organisation unit selection modes are explained in the following table.

Tabulka: Režimy výběru organizační jednotky

Režim Popis
SELECTED Organizační jednotky definované v požadavku.
CHILDREN Vybrané organizační jednotky a bezprostřední podřazené, tedy organizační jednotky na níže uvedené úrovni.
DESCENDANTS Vybrané organizační jednotky a všechny podřazené, tedy všechny organizační jednotky v podhierarchii.
ACCESSIBLE technically, returns everything in the user's tracker search organisation units. In practice, if a user lacks search organisation units, the system defaults to the data capture scope. As the capture scope is mandatory, we ensure that a user always has at least one universe.
CAPTURE The data capture organisation units associated with the current user and all descendants, encompassing all organisation units in the sub-hierarchy.
VŠE The term "ALL" logically refers to the entire organisation unit available in the system for super users. However, for non-superusers, "ALL" is equivalent to "ACCESSIBLE" organisation units.

The available assigned user modes are explained in the following table.

Tabulka: Přiřazené uživatelské režimy

Režim Popis
CURRENT Zahrnuje události přiřazené aktuálně přihlášenému uživateli.
PROVIDED Includes events assigned to the user provided in the request.
NONE Includes unassigned events only.
ANY Includes all assigned events, doesn't matter who are they assigned to as long as they assigned to someone.

V dotazu se nerozlišují velká a malá písmena. Pro parametry dotazu platí následující pravidla.

  • Alespoň jedna organizační jednotka musí být specifikována pomocí ou parameter (one or many), or ouMode=ALL must be specified.

  • Může být pouze jeden z parametrů program a trackedEntity specifikováno (nula nebo jedna).

  • If programStatus is specified then program must also be specifikováno.

  • Je-li zadáno followUp, musí být zadáno také program.

  • Pokud je zadáno programStartDate nebo programEndDate, pak musí být také specifikován program.

  • Položky filtru lze zadat pouze jednou.

A query for all instances associated with a specific organisation unit can look like this:

/api/33/trackedEntityInstances.json?ou=DiszpKrYNg8

To query for instances using one attribute with a filter and one attribute without a filter, with one organisation unit using the descendant organisation unit query mode:

/api/33/trackedEntityInstances.json?filter=zHXD5Ve1Efw:EQ:A
  &filter=AMpUYgxuCaE&ou=DiszpKrYNg8;yMCshbaVExv

A query for instances where one attribute is included in the response and one attribute is used as a filter:

/api/33/trackedEntityInstances.json?filter=zHXD5Ve1Efw:EQ:A
  &filter=AMpUYgxuCaE:LIKE:Road&ou=DiszpKrYNg8

A query where multiple operand and filters are specified for a filter item:

api/33/trackedEntityInstances.json?ou=DiszpKrYNg8&program=ur1Edk5Oe2n
  &filter=lw1SqmMlnfh:GT:150:LT:190

To query on an attribute using multiple values in an IN filter:

api/33/trackedEntityInstances.json?ou=DiszpKrYNg8
  &filter=dv3nChNSIxy:IN:Scott;Jimmy;Santiago

To constrain the response to instances which are part of a specific program you can include a program query parameter:

api/33/trackedEntityInstances.json?filter=zHXD5Ve1Efw:EQ:A&ou=O6uvpzGd5pu
  &ouMode=DESCENDANTS&program=ur1Edk5Oe2n

Chcete-li zadat data zápisu programu jako součást dotazu:

api/33/trackedEntityInstances.json?filter=zHXD5Ve1Efw:EQ:A&ou=O6uvpzGd5pu
  &program=ur1Edk5Oe2n&programStartDate=2013-01-01&programEndDate=2013-09-01

To constrain the response to instances of a specific tracked entity you can include a tracked entity query parameter:

api/33/trackedEntityInstances.json?filter=zHXD5Ve1Efw:EQ:A&ou=O6uvpzGd5pu
  &ouMode=DESCENDANTS&trackedEntity=cyl5vuJ5ETQ

By default the instances are returned in pages of size 50, to change this you can use the page and pageSize query parameters:

api/33/trackedEntityInstances.json?filter=zHXD5Ve1Efw:EQ:A&ou=O6uvpzGd5pu
  &ouMode=DESCENDANTS&page=2&pageSize=3

K filtrování můžete použít řadu operátorů:

Tabulka: Operátory filtrů

Operátor Popis
EQ Rovno
GT Větší než
GE Větší než nebo rovno
LT Menší než
LE Menší nebo rovno
NE Nerovná se
LIKE Shoda volného textu (obsahuje)
SW Začíná s
EW Končí s
IN Rovná se jedné z více hodnot oddělených ";"
Formát odpovědi

Tento zdroj podporuje zdroj JSON, JSONP, XLS a CSV reprezentace.

  • json (application/json)

  • jsonp (application/javascript)

  • xml (application/xml)

The response in JSON/XML is in object format and can look like the following. Please note that field filtering is supported, so if you want a full view, you might want to add fields=* to the query:

{
  "trackedEntityInstances": [
    {
      "lastUpdated": "2014-03-28 12:27:52.399",
      "trackedEntity": "cyl5vuJ5ETQ",
      "created": "2014-03-26 15:40:19.997",
      "orgUnit": "ueuQlqb8ccl",
      "trackedEntityInstance": "tphfdyIiVL6",
      "relationships": [],
      "attributes": [
        {
          "displayName": "Address",
          "attribute": "AMpUYgxuCaE",
          "type": "string",
          "value": "2033 Akasia St"
        },
        {
          "displayName": "TB number",
          "attribute": "ruQQnf6rswq",
          "type": "string",
          "value": "1Z 989 408 56 9356 521 9"
        },
        {
          "displayName": "Weight in kg",
          "attribute": "OvY4VVhSDeJ",
          "type": "number",
          "value": "68.1"
        },
        {
          "displayName": "Email",
          "attribute": "NDXw0cluzSw",
          "type": "string",
          "value": "LiyaEfrem@armyspy.com"
        },
        {
          "displayName": "Gender",
          "attribute": "cejWyOfXge6",
          "type": "optionSet",
          "value": "Female"
        },
        {
          "displayName": "Phone number",
          "attribute": "P2cwLGskgxn",
          "type": "phoneNumber",
          "value": "085 813 9447"
        },
        {
          "displayName": "First name",
          "attribute": "dv3nChNSIxy",
          "type": "string",
          "value": "Liya"
        },
        {
          "displayName": "Last name",
          "attribute": "hwlRTFIFSUq",
          "type": "string",
          "value": "Efrem"
        },
        {
          "code": "Height in cm",
          "displayName": "Height in cm",
          "attribute": "lw1SqmMlnfh",
          "type": "number",
          "value": "164"
        },
        {
          "code": "City",
          "displayName": "City",
          "attribute": "VUvgVao8Y5z",
          "type": "string",
          "value": "Kranskop"
        },
        {
          "code": "State",
          "displayName": "State",
          "attribute": "GUOBQt5K2WI",
          "type": "number",
          "value": "KwaZulu-Natal"
        },
        {
          "code": "Zip code",
          "displayName": "Zip code",
          "attribute": "n9nUvfpTsxQ",
          "type": "number",
          "value": "3282"
        },
        {
          "code": "National identifier",
          "displayName": "National identifier",
          "attribute": "AuPLng5hLbE",
          "type": "string",
          "value": "465700042"
        },
        {
          "code": "Blood type",
          "displayName": "Blood type",
          "attribute": "H9IlTX2X6SL",
          "type": "string",
          "value": "B-"
        },
        {
          "code": "Latitude",
          "displayName": "Latitude",
          "attribute": "Qo571yj6Zcn",
          "type": "string",
          "value": "-30.659626"
        },
        {
          "code": "Longitude",
          "displayName": "Longitude",
          "attribute": "RG7uGl4w5Jq",
          "type": "string",
          "value": "26.916172"
        }
      ]
    }
  ]
}

Databázový dotaz na mřížku instance trasované entity

To query for tracked entity instances you can interact with the /api/trackedEntityInstances/grid resource. There are two types of queries: One where a query query parameter and optionally attribute parameters are defined, and one where attribute and filter parameters are defined. This endpoint uses a more compact "grid" format, and is an alternative to the query in the previous section.

/api/33/trackedEntityInstances/query
Požádat o syntaxi

Tabulka: Parametry dotazu instancí trasovaných entit

Parametr dotazu Popis
query Řetězec dotazu. Parametr dotazu na atributy lze použít k definování atributů, které se mají zahrnout do odpovědi. Pokud nejsou definovány žádné atributy, ale program, použijí se atributy z programu. Pokud není definován žádný program, použijí se všechny atributy. Existují dva formáty. První je řetězec dotazu plánu. Druhý je ve formátu <operator> : <query> . Operátory mohou být EQ | JAKO. EQ znamená přesné shody slov, LIKE znamená částečné shody slov. Dotaz bude rozdělen na mezeru, kde každé slovo bude tvořit logický dotaz AND.
attribute Atributy, které mají být zahrnuty do odpovědi. Lze také použít jako filtr pro dotaz. Parametr lze opakovat libovolněkrát. Filtry lze použít na rozměr ve formátu <attribute-id>:<operator>:<filter>[:<operator>:<filter>]. Hodnoty filtru nerozlišují velká a malá písmena a lze je spolu s operátorem opakovat libovolněkrát. Operátory mohou být EQ | GT | GE | LT | LE | NE | LIKE | V. Filtry lze vynechat, aby bylo možné atribut jednoduše zahrnout do odpovědi bez jakýchkoli omezení.
filtr Atributy, které se mají použít jako filtr pro dotaz. Parametr lze opakovat libovolněkrát. Filtry lze použít na rozměr ve formátu <attribute-id>:<operator>:<filter>[:<operator>:<filter>]. Hodnoty filtru nerozlišují velká a malá písmena a lze je spolu s operátorem opakovat libovolněkrát. Operátory mohou být EQ | GT | GE | LT | LE | NE | LIKE | V.
ou Identifikátory organizační jednotky oddělené „;“.
ouMode Režim výběru organizačních jednotek může být SELECTED | CHILDREN | DESCENDANTS | ACCESSIBLE | ALL. Výchozí hodnota je SELECTED, což se týká pouze vybraných organizačních jednotek. Vysvětlení viz tabulka níže.
program Identifikátor programu. Omezuje instance na přihlášení do daného programu.
programStatus Stav instance pro daný program. Může být AKTIVNÍ | DOKONČENO | ZRUŠENO.
followUp Sledovat stav instance pro daný program. Může to být true | false nebo omitted.
programStartDate Datum zahájení zápisu v daném programu pro instanci trasované entity.
programEndDate Datum ukončení zápisu v daném programu pro instanci trasované entity.
trackedEntity Identifikátor trasované entity. Omezuje instance na daný typ trasované instance.
eventStatus Status of any event associated with the given program and the tracked entity instance. Can be ACTIVE | COMPLETED | VISITED | SCHEDULE | OVERDUE | SKIPPED.
eventStartDate Datum zahájení akce spojené s daným programem a stav akce.
eventEndDate Datum ukončení události spojené s daným programem a stavem události.
programStage ProgramStage, pro kterou by se měly použít filtry související s událostmi. Pokud nebudou poskytnuty, budou zváženy všechny fáze.
skipMeta Označuje, zda by měla být zahrnuta metadata pro odpověď.
strana Číslo stránky. Výchozí stránka je 1.
pageSize Velikost stránky. Výchozí velikost je 50 řádků na stránku.
totalPages Označuje, zda se má do odpovědi stránkování zahrnout celkový počet stránek (znamená delší dobu odezvy).
skipPaging Označuje, zda má být stránkování ignorováno a mají být vráceny všechny řádky.
assignedUserMode Omezuje výsledek na tei s událostmi přiřazenými na základě přiřazeného režimu výběru uživatele, může být CURRENT | PROVIDED | NONE | ANY.
assignedUser Filter the result down to a limited set of teis with events that are assigned to the given user IDs by using assignedUser=id1;id2.This parameter will be considered only if assignedUserMode is either PROVIDED or null. The API will error out, if for example, assignedUserMode=CURRENT and assignedUser=someId
trackedEntityInstance Filter the result down to a limited set of teis using explicit uids of the tracked entity instances by using trackedEntityInstance=id1;id2. This parameter will at the very least create the outer boundary of the results, forming the list of all teis using the uids provided. If other parameters/filters from this table are used, they will further limit the results from the explicit outer boundary.
potentialDuplicate Filter the result based on the fact that a TEI is a Potential Duplicate. true: return TEIs flagged as Potential Duplicates. false: return TEIs NOT flagged as Potential Duplicates. If omitted, we don't check whether a TEI is a Potential Duplicate or not.

The available organisation unit selection modes are explained in the following table.

Tabulka: Režimy výběru organizační jednotky

Režim Popis
SELECTED Organizační jednotky definované v požadavku.
CHILDREN Bezprostřední podřazené, tedy pouze první úroveň níže, organizačních jednotek definovaných v požadavku.
DESCENDANTS Všechny podřazení, tedy pouze na nižších úrovních, např. včetně podřazených do druhé úrovně organizačních jednotek definovaných v požadavku.
ACCESSIBLE Všichni podřazení organizačních jednotek zobrazení dat přidružení k aktuálnímu uživateli. Pokud první není definován, vrátí se zpět k organizačním jednotkám sběru dat přidruženým k aktuálnímu uživateli.
CAPTURE Data zachycují organizační jednotky spojené s aktuálním uživatelem a všemi potomky, tj. všemi organizačními jednotkami v podhierarchii.
VŠE All organisation units in the system. Requires ALL authority.

Note that you can specify "attribute" with filters or directly using the "filter" params for constraining the instances to return.

Pro vrácení atributů platí určitá pravidla.

  • If "query" is specified without any attributes or program, then all attributes that are marked as "Display in List without Program" is included in the response.

  • Pokud je zadán program, budou všechny atributy spojené s programem be included in the response.

  • If tracked entity type is specified, then all tracked entity type attributes will be included in the response.

You can specify queries with words separated by space - in that situation the system will query for each word independently and return records where each word is contained in any attribute. A query item can be specified once as an attribute and once as a filter if needed. The query is case insensitive. The following rules apply to the query parameters.

  • Alespoň jedna organizační jednotka musí být specifikována pomocí ou parameter (one or many), or ouMode=ALL must be specified.

  • Může být pouze jeden z parametrů program a trackedEntity specifikováno (nula nebo jedna).

  • If programStatus is specified then program must also be specifikováno.

  • Je-li zadáno followUp, musí být zadáno také program.

  • Pokud je zadáno programStartDate nebo programEndDate, pak musí být také specifikován program.

  • If eventStatus is specified then eventStartDate and eventEndDate must also be specified.

  • Spolu s filtry nelze zadat dotaz.

  • Položky atributů lze zadat pouze jednou.

  • Položky filtru lze zadat pouze jednou.

A query for all instances associated with a specific organisation unit can look like this:

/api/33/trackedEntityInstances/query.json?ou=DiszpKrYNg8

A query on all attributes for a specific value and organisation unit, using an exact word match:

/api/33/trackedEntityInstances/query.json?query=scott&ou=DiszpKrYNg8

A query on all attributes for a specific value, using a partial word match:

/api/33/trackedEntityInstances/query.json?query=LIKE:scott&ou=DiszpKrYNg8

You can query on multiple words separated by the URL character for space which is %20, will use a logical AND query for each word:

/api/33/trackedEntityInstances/query.json?query=isabel%20may&ou=DiszpKrYNg8

Dotaz, kde jsou specifikovány atributy, které mají být zahrnuty v odpovědi:

/api/33/trackedEntityInstances/query.json?query=isabel
  &attribute=dv3nChNSIxy&attribute=AMpUYgxuCaE&ou=DiszpKrYNg8

To query for instances using one attribute with a filter and one attribute without a filter, with one organisation unit using the descendants organisation unit query mode:

/api/33/trackedEntityInstances/query.json?attribute=zHXD5Ve1Efw:EQ:A
  &attribute=AMpUYgxuCaE&ou=DiszpKrYNg8;yMCshbaVExv

A query for instances where one attribute is included in the response and one attribute is used as a filter:

/api/33/trackedEntityInstances/query.json?attribute=zHXD5Ve1Efw:EQ:A
  &filter=AMpUYgxuCaE:LIKE:Road&ou=DiszpKrYNg8

A query where multiple operand and filters are specified for a filter item:

/api/33/trackedEntityInstances/query.json?ou=DiszpKrYNg8&program=ur1Edk5Oe2n
  &filter=lw1SqmMlnfh:GT:150:LT:190

To query on an attribute using multiple values in an IN filter:

/api/33/trackedEntityInstances/query.json?ou=DiszpKrYNg8
  &attribute=dv3nChNSIxy:IN:Scott;Jimmy;Santiago

To constrain the response to instances which are part of a specific program you can include a program query parameter:

/api/33/trackedEntityInstances/query.json?filter=zHXD5Ve1Efw:EQ:A
  &ou=O6uvpzGd5pu&ouMode=DESCENDANTS&program=ur1Edk5Oe2n

Chcete-li zadat data zápisu programu jako součást dotazu:

/api/33/trackedEntityInstances/query.json?filter=zHXD5Ve1Efw:EQ:A
  &ou=O6uvpzGd5pu&program=ur1Edk5Oe2n&programStartDate=2013-01-01
  &programEndDate=2013-09-01

To constrain the response to instances of a specific tracked entity you can include a tracked entity query parameter:

/api/33/trackedEntityInstances/query.json?attribute=zHXD5Ve1Efw:EQ:A
  &ou=O6uvpzGd5pu&ouMode=DESCENDANTS&trackedEntity=cyl5vuJ5ETQ

By default the instances are returned in pages of size 50, to change this you can use the page and pageSize query parameters:

/api/33/trackedEntityInstances/query.json?attribute=zHXD5Ve1Efw:EQ:A
  &ou=O6uvpzGd5pu&ouMode=DESCENDANTS&page=2&pageSize=3

To query for instances which have events of a given status within a given time span:

/api/33/trackedEntityInstances/query.json?ou=O6uvpzGd5pu
  &program=ur1Edk5Oe2n&eventStatus=COMPLETED
  &eventStartDate=2014-01-01&eventEndDate=2014-09-01

K filtrování můžete použít řadu operátorů:

Tabulka: Operátory filtrů

Operátor Popis
EQ Rovno
GT Větší než
GE Větší než nebo rovno
LT Menší než
LE Menší nebo rovno
NE Nerovná se
LIKE Shoda volného textu (obsahuje)
SW Začíná s
EW Končí s
IN Rovná se jedné z více hodnot oddělených ";"
Formát odpovědi

Tento zdroj podporuje zdroj JSON, JSONP, XLS a CSV reprezentace.

  • json (application/json)

  • jsonp (application/javascript)

  • xml (application/xml)

  • csv (application/csv)

  • xls (application/vnd.ms-excel)

The response in JSON comes is in a tabular format and can look like the following. The headers section describes the content of each column. The instance, created, last updated, org unit and tracked entity columns are always present. The following columns correspond to attributes specified in the query. The rows section contains one row per instance.

{
  "headers": [{
    "name": "instance",
    "column": "Instance",
    "type": "java.lang.String"
  }, {
    "name": "created",
    "column": "Created",
    "type": "java.lang.String"
  }, {
    "name": "lastupdated",
    "column": "Last updated",
    "type": "java.lang.String"
  }, {
    "name": "ou",
    "column": "Org unit",
    "type": "java.lang.String"
  }, {
    "name": "te",
    "column": "Tracked entity",
    "type": "java.lang.String"
  }, {
    "name": "zHXD5Ve1Efw",
    "column": "Date of birth type",
    "type": "java.lang.String"
  }, {
    "name": "AMpUYgxuCaE",
    "column": "Address",
    "type": "java.lang.String"
  }],
  "metaData": {
    "names": {
      "cyl5vuJ5ETQ": "Person"
    }
  },
  "width": 7,
  "height": 7,
  "rows": [
    ["yNCtJ6vhRJu", "2013-09-08 21:40:28.0", "2014-01-09 19:39:32.19", "DiszpKrYNg8", "cyl5vuJ5ETQ", "A", "21 Kenyatta Road"],
    ["fSofnQR6lAU", "2013-09-08 21:40:28.0", "2014-01-09 19:40:19.62", "DiszpKrYNg8", "cyl5vuJ5ETQ", "A", "56 Upper Road"],
    ["X5wZwS5lgm2", "2013-09-08 21:40:28.0", "2014-01-09 19:40:31.11", "DiszpKrYNg8", "cyl5vuJ5ETQ", "A", "56 Main Road"],
    ["pCbogmlIXga", "2013-09-08 21:40:28.0", "2014-01-09 19:40:45.02", "DiszpKrYNg8", "cyl5vuJ5ETQ", "A", "12 Lower Main Road"],
    ["WnUXrY4XBMM", "2013-09-08 21:40:28.0", "2014-01-09 19:41:06.97", "DiszpKrYNg8", "cyl5vuJ5ETQ", "A", "13 Main Road"],
    ["xLNXbDs9uDF", "2013-09-08 21:40:28.0", "2014-01-09 19:42:25.66", "DiszpKrYNg8", "cyl5vuJ5ETQ", "A", "14 Mombasa Road"],
    ["foc5zag6gbE", "2013-09-08 21:40:28.0", "2014-01-09 19:42:36.93", "DiszpKrYNg8", "cyl5vuJ5ETQ", "A", "15 Upper Hill"]
  ]
}

Filtry instance trasované entity

To create, read, update and delete tracked entity instance filters you can interact with the /api/trackedEntityInstanceFilters resource. Tracked entity instance filters are shareable and follows the same pattern of sharing as any other metadata object. When using the /api/sharing the type parameter will be trackedEntityInstanceFilter.

/api/33/trackedEntityInstanceFilters
Vytvořte a aktualizujte definici filtru instance trasované entity

For creating and updating a tracked entity instance filter in the system, you will be working with the trackedEntityInstanceFilters resource. The tracked entity instance filter definitions are used in the Tracker Capture app to display relevant predefined "Working lists" in the tracker user interface.

Tabulka: Datový obsah

Hodnoty datového obsahu Popis Příklad
název Název filtru. Požadované.
popis Popis filtru.
sortOrder Pořadí řazení filtru. Používá se v aplikaci Tracker Capture k uspořádání filtrů na ovládacím panelu programu.
styl Objekt obsahující styl css. ( "color": "blue", "icon": "fa fa-calendar"}
program Objekt obsahující id programu. Požadované. { "id" : "uy2gU8kTjF"}
entityQueryCriteria An object representing various possible filtering values. See Entity Query Criteria definition table below.
eventFilters A list of eventFilters. See Event filters definition table below. [{"programStage": "eaDH9089uMp", "eventStatus": "OVERDUE", "eventCreatedPeriod": {"periodFrom": -15, "periodTo": 15}}]

Tabulka: Definice kritérií dotazu entity

attributeValueFilters Seznam FilterValueFilters. To se používá ke specifikaci filtrů pro hodnoty atributů při výpisu instancí sledovaných entit "attributeValueFilters"=[{ "attribute": "abcAttributeUid", "le": "20", "ge": "10", "lt": "20", "gt": "10", "in": ["India", "Norway"], "like": "abc", "sw": "abc", "ew": "abc", "dateFilter": { "startDate": "2014-05-01", "endDate": "2019-03-20", "startBuffer": -5, "endBuffer": 5, "period": "LAST_WEEK", "type": "RELATIVE" } }]
enrollmentStatus The TEIs enrollment status. Can be none(any enrollmentstatus) or ACTIVE|COMPLETED|CANCELLED
followup Když je tento parametr pravdivý, filtr vrátí pouze TEI, které mají registraci s následným sledováním stavu.
organisationUnit Chcete-li zadat uid organizační jednotky "organisationUnit": "a3kGcGDCuk7"
ouMode Chcete-li určit režim výběru OU. Možné hodnoty jsou VYBRANÉ| PŘÍSTUPNÉ DĚTI|POTOMCI|ZAJIŠTĚNÍ VŠECH "ouMode": "SELECTED"
assignedUserMode Chcete-li určit režim výběru přiřazeného uživatele pro události. Možné hodnoty jsou CURRENT| PROVIDED| NONE | ANY. Podívejte se do tabulky níže, abyste pochopili, co jednotlivé hodnoty znamenají. Je-li hodnota PROVIDED (nebo null), budou v datovém obsahu zohledněni neprázdní přiřazení uživatelé. "assignedUserMode": "PROVIDED"
assignedUsers Chcete-li zadat seznam přiřazených uživatelů pro události. K použití spolu s výše uvedeným režimem PROVIDEDassignedUserMode. "assignedUsers": ["a3kGcGDCuk7", "a3kGcGDCuk8"]
displayColumnOrder Chcete-li určit výstupní pořadí sloupců "displayOrderColumns": ["enrollmentDate", "program"]
řazení To specify ordering/sorting of fields and its directions in comma separated values. A single item in order is of the form "orderDimension:direction". Note: Supported orderDimensions are trackedEntity, created, createdAt, createdAtClient, updatedAt, updatedAtClient, enrolledAt, inactive and the tracked entity attributes "order"="a3kGcGDCuk6:desc"
eventStatus Jakýkoli platný EventStatus "eventStatus": "COMPLETED"
programStage Chcete-li zadat uid programuStage, podle kterého se má filtrovat. TEI budou filtrovány na základě přítomnosti zapsaných ve specifikované fázi programu. "programStage"="a3kGcGDCuk6"
trackedEntityType Chcete-li určit TEI filtru trackedEntityType na. "trackedEntityType"="a3kGcGDCuk6"
trackedEntityInstances Chcete-li zadat seznam trackedEntityInstance, který se má použít při dotazování na TEI. "trackedEntityInstances"=["a3kGcGDCuk6","b4jGcGDCuk7"]
enrollmentIncidentDate DateFilterPeriod filtrování data objektu na základě data incidentu registrace. "enrollmentIncidentDate": { "startDate": "2014-05-01", "endDate": "2019-03-20", "startBuffer": -5, "endBuffer": 5, "period": "LAST_WEEK", "type": "RELATIVE" }
eventDate DateFilterPeriod filtrování data objektu na základě data události. "eventDate": { "startBuffer": -5, "endBuffer": 5, "type": "RELATIVE" }
enrollmentCreatedDate DateFilterPeriod filtrování data objektu na základě data vytvoření registrace. "enrollmentCreatedDate": { "period": "LAST_WEEK", "type": "RELATIVE" }
lastUpdatedDate DateFilterPeriod filtrování data objektu na základě data poslední aktualizace. "lastUpdatedDate": { "startDate": "2014-05-01", "endDate": "2019-03-20", "type": "ABSOLUTE" }

Tabulka: Definice filtrů událostí

programStage Ve které fázi programu TEI potřebuje událost, aby byla vrácena. "eaDH9089uMp"
eventStatus The events status. Can be none(any event status) or ACTIVE|COMPLETED|SCHEDULE|OVERDUE ACTIVE
eventCreatedPeriod Period object containing a period in which the event must be created. See Period definition below. { "periodFrom": -15, "periodTo": 15}
assignedUserMode Chcete-li určit režim výběru přiřazeného uživatele pro události. Možné hodnoty jsou CURRENT (události přiřazené aktuálnímu uživateli)| PROVIDED (události přiřazené uživatelům v seznamu „assignedUsers“) | ŽÁDNÉ (události přiřazené nikomu) | JAKÉKOLI (události přiřazené komukoli). Je-li POSKYTNUTO (nebo null), budou zohledněni neprázdní přiřazení uživatelé v užitečné zátěži. "assignedUserMode": "PROVIDED"
assignedUsers Chcete-li zadat seznam přiřazených uživatelů pro události. K použití spolu s výše uvedeným režimem PROVIDEDassignedUserMode. "assignedUsers": ["a3kGcGDCuk7", "a3kGcGDCuk8"]

Tabulka: Definice objektu DateFilterPeriod

typ Určete, zda je typ období typu ABSOLUTE | RELATIVNÍ "type" : "RELATIVE"
period Určete, zda se má použít období definované relativním systémem. Použitelné pouze tehdy, když je "typ" RELATIVNÍ. (podporovaná relativní období viz Relativní období) "period" : "THIS_WEEK"
startDate Absolutní datum zahájení. Použitelné pouze tehdy, když je "typ" ABSOLUTNÍ "startDate":"2014-05-01"
endDate Absolutní datum ukončení. Použitelné pouze tehdy, když je "typ" ABSOLUTE "startDate":"2014-05-01"
startBuffer Relativní vlastní datum zahájení. Použitelné pouze tehdy, když je "typ" RELATIVNÍ "startBuffer":-10
endBuffer Relativní vlastní datum ukončení. Použitelné pouze tehdy, když je "typ" RELATIVNÍ "startDate":+10

Tabulka: Definice období

periodFrom Počet dní od aktuálního dne. Může být kladné nebo záporné celé číslo. -15
periodTo Počet dní od aktuálního dne. Musí být větší než období od. Může být kladné nebo záporné celé číslo. 15
Dotaz na filtry instance trasované entity

Chcete-li se dotazovat na filtry instancí sledovaných entit v systému, můžete komunikovat se zdrojem /api/trackedEntityInstanceFilters.

Tabulka: Instance sledované entity filtruje parametry dotazu

Parametr dotazu Popis
program Identifikátor programu. Omezí filtry na daný program.

Správa zápisů

Zápisy mají v rozhraní API plnou podporu CRUD. Společně s API pro trasované instance entit většina operací potřebných pro práci s trasovanými instancemi entit a programy jsou podporovány.

/api/33/enrollments

Registrace instance trasované entity do programu

For enrolling persons into a program, you will need to first get the identifier of the person from the trackedEntityInstances resource. Then, you will need to get the program identifier from the programs resource. A template payload can be seen below:

{
  "trackedEntityInstance": "ZRyCnJ1qUXS",
  "orgUnit": "ImspTQPwCqd",
  "program": "S8uo8AlvYMz",
  "enrollmentDate": "2013-09-17",
  "incidentDate": "2013-09-17"
}

Tento datový obsah by měl být použit v požadavku POST na zápis identifikovaný následující adresou URL:

/api/33/enrollments

The different status of an enrollment are:

  • ACTIVE: It is used meanwhile when the tracked entity participates on the program.
  • COMPLETED: It is used when the tracked entity finished its participation on the program.
  • CANCELLED: "Deactivated" in the web UI. It is used when the tracked entity cancelled its participation on the program.

For cancelling or completing an enrollment, you can make a PUT request to the enrollments resource, including the identifier and the action you want to perform. For cancelling an enrollment for a tracked entity instance:

/api/33/enrollments/<enrollment-id>/cancelled

For completing an enrollment for a tracked entity instance you can make a PUT request to the following URL:

/api/33/enrollments/<enrollment-id>/completed

For deleting an enrollment, you can make a DELETE request to the following URL:

/api/33/enrollments/<enrollment-id>

Databázový dotaz na zápis instance

Chcete-li se zeptat na zápisy, můžete komunikovat se zdrojem /api/enrollments.

/api/33/enrollments
Požádat o syntaxi

Tabulka: Parametry dotazu zápisu

Parametr dotazu Popis
ou Identifikátory organizační jednotky oddělené „;“.
ouMode The mode of selecting organisation units, can be SELECTED | CHILDREN | DESCENDANTS | ACCESSIBLE | CAPTURE | ALL. Default is SELECTED, which refers to the selected organisation units only. See table below for explanations.
program Identifikátor programu. Omezuje instance na přihlášení do daného programu.
programStatus Stav instance pro daný program. Může být AKTIVNÍ | DOKONČENO | ZRUŠENO.
followUp Sledovat stav instance pro daný program. Může to být true | false nebo omitted.
programStartDate Datum zahájení zápisu v daném programu pro instanci trasované entity.
programEndDate Datum ukončení zápisu v daném programu pro instanci trasované entity.
lastUpdatedDuration Zahrňte pouze položky, které jsou aktualizovány během daného trvání. Formát je , kde podporované časové jednotky jsou „d“ (dny), „h“ (hodiny), „m“ (minuty) a „s“ (sekundy).
trackedEntity Identifikátor trasované entity. Omezuje instance na daný typ trasované instance.
trackedEntityInstance Identifikátor instance trasované entity. Nemělo by se používat společně s trackedEntity.
strana Číslo stránky. Výchozí stránka je 1.
pageSize Velikost stránky. Výchozí velikost je 50 řádků na stránku.
totalPages Označuje, zda se má do odpovědi stránkování zahrnout celkový počet stránek (znamená delší dobu odezvy).
skipPaging Označuje, zda má být stránkování ignorováno a mají být vráceny všechny řádky.
includeDeleted Označuje, zda se mají zahrnout měkké smazané zápisy nebo ne. Ve výchozím nastavení je nepravda.

The available organisation unit selection modes are explained in the following table.

Tabulka: Režimy výběru organizační jednotky

Režim Popis
SELECTED Organizační jednotky definované v požadavku (výchozí).
CHILDREN Bezprostřední podřazené, tedy pouze první úroveň níže, organizačních jednotek definovaných v požadavku.
DESCENDANTS Všechny podřazení, tedy pouze na nižších úrovních, např. včetně podřazených do druhé úrovně organizačních jednotek definovaných v požadavku.
ACCESSIBLE Všichni podřazení organizačních jednotek zobrazení dat přidružení k aktuálnímu uživateli. Pokud první není definován, vrátí se zpět k organizačním jednotkám sběru dat přidruženým k aktuálnímu uživateli.
VŠE All organisation units in the system. Requires ALL authority.

V dotazu se nerozlišují velká a malá písmena. Pro parametry dotazu platí následující pravidla.

  • Alespoň jedna organizační jednotka musí být specifikována pomocí ou parameter (one or many), or ouMode=ALL must be specified.

  • Může být pouze jeden z parametrů program a trackedEntity specifikováno (nula nebo jedna).

  • If programStatus is specified then program must also be specifikováno.

  • Je-li zadáno followUp, musí být zadáno také program.

  • Pokud je zadáno programStartDate nebo programEndDate, pak musí být také specifikován program.

A query for all enrollments associated with a specific organisation unit can look like this:

/api/33/enrollments.json?ou=DiszpKrYNg8

To constrain the response to enrollments which are part of a specific program you can include a program query parameter:

/api/33/enrollments.json?ou=O6uvpzGd5pu&ouMode=DESCENDANTS&program=ur1Edk5Oe2n

Chcete-li zadat data zápisu programu jako součást dotazu:

/api/33/enrollments.json?&ou=O6uvpzGd5pu&program=ur1Edk5Oe2n
  &programStartDate=2013-01-01&programEndDate=2013-09-01

To constrain the response to enrollments of a specific tracked entity you can include a tracked entity query parameter:

/api/33/enrollments.json?ou=O6uvpzGd5pu&ouMode=DESCENDANTS&trackedEntity=cyl5vuJ5ETQ

To constrain the response to enrollments of a specific tracked entity instance you can include a tracked entity instance query parameter, in this case we have restricted it to available enrollments viewable for current user:

/api/33/enrollments.json?ouMode=ACCESSIBLE&trackedEntityInstance=tphfdyIiVL6

By default the enrollments are returned in pages of size 50, to change this you can use the page and pageSize query parameters:

/api/33/enrollments.json?ou=O6uvpzGd5pu&ouMode=DESCENDANTS&page=2&pageSize=3
Formát odpovědi

Tento zdroj podporuje zdroj JSON, JSONP, XLS a CSV reprezentace.

  • json (application/json)

  • jsonp (application/javascript)

  • xml (application/xml)

The response in JSON/XML is in object format and can look like the following. Please note that field filtering is supported, so if you want a full view, you might want to add fields=* to the query:

{
  "enrollments": [
    {
      "lastUpdated": "2014-03-28T05:27:48.512+0000",
      "trackedEntity": "cyl5vuJ5ETQ",
      "created": "2014-03-28T05:27:48.500+0000",
      "orgUnit": "DiszpKrYNg8",
      "program": "ur1Edk5Oe2n",
      "enrollment": "HLFOK0XThjr",
      "trackedEntityInstance": "qv0j4JBXQX0",
      "followup": false,
      "enrollmentDate": "2013-05-23T05:27:48.490+0000",
      "incidentDate": "2013-05-10T05:27:48.490+0000",
      "status": "ACTIVE"
    }
  ]
}

Události

Tato část je o odesílání a čtení událostí.

/api/33/events

Různé stavy události jsou:

  • AKTIVNÍ: Pokud má událost stav AKTIVNÍ, je možné upravit podrobnosti události. DOKONČENÉ události lze znovu přepnout na AKTIVNÍ a naopak.
  • DOKONČENO: Událost změní stav na DOKONČENO pouze tehdy, když uživatel klikne na tlačítko dokončení. Pokud má událost stav DOKONČENO, není možné upravit podrobnosti události. AKTIVNÍ události lze znovu změnit na DOKONČENÉ a naopak.
  • SKIPPED: Naplánované události, které se již nemusí konat. V Tracker Capture je na to tlačítko.
  • SCHEDULE: If an event has no event date (but it has an due date) then the event status is saved as SCHEDULE.
  • OVERDUE: If the due date of a scheduled event (no event date) has expired, it can be interpreted as OVERDUE.
  • VISITED: (Removed since 2.38. VISITED migrate to ACTIVE). In Tracker Capture its possible to reach VISITED by adding a new event with an event date, and then leave before adding any data to the event - but it is not known to the tracker product team that anyone uses the status for anything. The VISITED status is not visible in the UI, and in all means treated in the same way as an ACTIVE event.

Odesílání událostí

DHIS2 supports three kinds of events: single events with no registration (also referred to as anonymous events), single event with registration and multiple events with registration. Registration implies that the data is linked to a tracked entity instance which is identified using some sort of identifier.

To send events to DHIS2 you must interact with the events resource. The approach to sending events is similar to sending aggregate data values. You will need a program which can be looked up using the programs resource, an orgUnit which can be looked up using the organisationUnits resource, and a list of valid data element identifiers which can be looked up using the dataElements resource. For events with registration, a tracked entity instance identifier is required, read about how to get this in the section about the trackedEntityInstances resource. For sending events to programs with multiple stages, you will need to also include the programStage identifier, the identifiers for programStages can be found in the programStages resource.

A simple single event with no registration example payload in XML format where we send events from the "Inpatient morbidity and mortality" program for the "Ngelehun CHC" facility in the demo database can be seen below:

<?xml version="1.0" encoding="utf-8"?>
<event program="eBAyeGv0exc" orgUnit="DiszpKrYNg8"
  eventDate="2013-05-17" status="COMPLETED" storedBy="admin">
  <coordinate latitude="59.8" longitude="10.9" />
  <dataValues>
    <dataValue dataElement="qrur9Dvnyt5" value="22" />
    <dataValue dataElement="oZg33kd9taw" value="Male" />
    <dataValue dataElement="msodh3rEMJa" value="2013-05-18" />
  </dataValues>
</event>

To perform some testing we can save the XML payload as a file called event.xml and send it as a POST request to the events resource in the API using curl with the following command:

curl -d @event.xml "https://play.dhis2.org/demo/api/33/events"
  -H "Content-Type:application/xml" -u admin:district

Stejný datový obsah ve formátu JSON vypadá takto:

{
  "program": "eBAyeGv0exc",
  "orgUnit": "DiszpKrYNg8",
  "eventDate": "2013-05-17",
  "status": "COMPLETED",
  "completedDate": "2013-05-18",
  "storedBy": "admin",
  "coordinate": {
    "latitude": 59.8,
    "longitude": 10.9
  },
  "dataValues": [
    {
      "dataElement": "qrur9Dvnyt5",
      "value": "22"
    },
    {
      "dataElement": "oZg33kd9taw",
      "value": "Male"
    },
    {
      "dataElement": "msodh3rEMJa",
      "value": "2013-05-18"
    }
  ]
}

To send this you can save it to a file called event.json and use curl like this:

curl -d @event.json "localhost/api/33/events" -H "Content-Type:application/json"
  -u admin:district

We also support sending multiple events at the same time. A payload in XML format might look like this:

<?xml version="1.0" encoding="utf-8"?>
<events>
  <event program="eBAyeGv0exc" orgUnit="DiszpKrYNg8"
    eventDate="2013-05-17" status="COMPLETED" storedBy="admin">
    <coordinate latitude="59.8" longitude="10.9" />
    <dataValues>
      <dataValue dataElement="qrur9Dvnyt5" value="22" />
      <dataValue dataElement="oZg33kd9taw" value="Male" />
    </dataValues>
  </event>
  <event program="eBAyeGv0exc" orgUnit="DiszpKrYNg8"
    eventDate="2013-05-17" status="COMPLETED" storedBy="admin">
    <coordinate latitude="59.8" longitude="10.9" />
    <dataValues>
      <dataValue dataElement="qrur9Dvnyt5" value="26" />
      <dataValue dataElement="oZg33kd9taw" value="Female" />
    </dataValues>
  </event>
</events>

You will receive an import summary with the response which can be inspected in order to get information about the outcome of the request, like how many values were imported successfully. The payload in JSON format looks like this:

{
  "events": [
  {
    "program": "eBAyeGv0exc",
    "orgUnit": "DiszpKrYNg8",
    "eventDate": "2013-05-17",
    "status": "COMPLETED",
    "storedBy": "admin",
    "coordinate": {
      "latitude": "59.8",
      "longitude": "10.9"
    },
    "dataValues": [
      {
        "dataElement": "qrur9Dvnyt5",
        "value": "22"
      },
      {
        "dataElement": "oZg33kd9taw",
        "value": "Male"
      }
    ]
  },
  {
    "program": "eBAyeGv0exc",
    "orgUnit": "DiszpKrYNg8",
    "eventDate": "2013-05-17",
    "status": "COMPLETED",
    "storedBy": "admin",
    "coordinate": {
      "latitude": "59.8",
      "longitude": "10.9"
    },
    "dataValues": [
      {
        "dataElement": "qrur9Dvnyt5",
        "value": "26"
      },
      {
        "dataElement": "oZg33kd9taw",
        "value": "Female"
      }
    ]
  } ]
}

GeoJson můžete také použít k uložení jakéhokoli druhu geometrie vaší události. Zde můžete vidět příklad datového obsahu pomocí GeoJson namísto dřívějších vlastností zeměpisné šířky a délky:

{
  "program": "eBAyeGv0exc",
  "orgUnit": "DiszpKrYNg8",
  "eventDate": "2013-05-17",
  "status": "COMPLETED",
  "storedBy": "admin",
  "geometry": {
    "type": "POINT",
    "coordinates": [59.8, 10.9]
  },
  "dataValues": [
    {
      "dataElement": "qrur9Dvnyt5",
      "value": "22"
    },
    {
      "dataElement": "oZg33kd9taw",
      "value": "Male"
    },
    {
      "dataElement": "msodh3rEMJa",
      "value": "2013-05-18"
    }
  ]
}

As part of the import summary you will also get the identifier reference to the event you just sent, together with a href element which points to the server location of this event. The table below describes the meaning of each element.

Tabulka: Formát zdroje událostí

Parametr Typ Požadované Možnosti (nejprve výchozí) Popis
program řetězec true Identifikátor jedné události bez registračního programu
orgUnit řetězec true Identifikátor organizační jednotky, kde se akce konala
eventDate datum true Datum, kdy k události došlo
completedDate datum false Datum, kdy je akce dokončena. Pokud není zadáno, je jako datum dokončení události vybráno aktuální datum
status enum false ACTIVE | COMPLETED | VISITED | SCHEDULE | OVERDUE | SKIPPED Zda je akce dokončena nebo ne
storedBy řetězec false Výchozí nastavení pro aktuálního uživatele Kdo uložil tuto událost (může to být uživatelské jméno, název systému atd.)
souřadnice dvojnásobek false Odkazuje na místo, kde se událost geograficky odehrála (zeměpisná šířka a délka)
dataElement řetězec true Identifikátor datového prvku
value řetězec true Hodnota nebo míra dat pro tuto událost
Shoda OrgUnit

By default the orgUnit parameter will match on the ID, you can also select the orgUnit id matching scheme by using the parameter orgUnitIdScheme=SCHEME, where the options are: ID, UID, UUID, CODE, and NAME. There is also the ATTRIBUTE: scheme, which matches on a unique metadata attribute value.

Aktualizace událostí

To update an existing event, the format of the payload is the same, but the URL you are posting to must add the identifier to the end of the URL string and the request must be PUT.

The payload has to contain all, even non-modified, attributes. Attributes that were present before and are not present in the current payload any more will be removed by the system.

It is not allowed to update an already deleted event. The same applies to tracked entity instance and enrollment.

curl -X PUT -d @updated_event.xml "localhost/api/33/events/ID"
  -H "Content-Type: application/xml" -u admin:district
curl -X PUT -d @updated_event.json "localhost/api/33/events/ID"
  -H "Content-Type: application/json" -u admin:district

Mazání událostí

To delete an existing event, all you need is to send a DELETE request with an identifier reference to the server you are using.

curl -X DELETE "localhost/api/33/events/ID" -u admin:district

Přiřazení uživatele k událostem

K události lze přiřadit uživatele. To lze provést zahrnutím příslušné vlastnosti do datového obsahu při aktualizaci nebo vytváření události.

  "assignedUser": "<id>"

ID odkazuje na if uživatele. K události lze najednou přiřadit pouze jednoho uživatele.

Přiřazení uživatele musí být povoleno ve fázi programu, než mohou být uživatelé přiřazeni k událostem.

Získávání událostí

To get an existing event you can issue a GET request including the identifier like this:

curl "http://localhost/api/33/events/ID" -H "Content-Type: application/xml" -u admin:district

Dotazování a čtení událostí

This section explains how to read out the events that have been stored in the DHIS2 instance. For more advanced uses of the event data, please see the section on event analytics. The output format from the /api/events endpoint will match the format that is used to send events to it (which the analytics event api does not support). Both XML and JSON are supported, either through adding .json/.xml or by setting the appropriate Accept header. The query is paged by default and the default page size is 50 events, field filtering works as it does for metadata, add the fields parameter and include your wanted properties, i.e. ?fields=program,status.

Tabulka: Parametry dotazu na zdroj událostí

Klíč Typ Požadované Popis
program identifikátor true (pokud není poskytnut programStage) Identifikátor programu
programStage identifikátor false Identifikátor fáze programu
programStatus enum false Stav události v programu, může být ACTIVE | COMPLETED | CANCELLED
followUp boolean false Zda je událost zvažována pro pokračování v programu, může být pravda | nepravdivé nebo vynechané.
trackedEntityInstance identifikátor false Identifikátor instance trasované entity
orgUnit identifikátor true Identifikátor organizační jednotky
ouMode enum false Org unit selection mode, can be SELECTED | CHILDREN | DESCENDANTS
startDate datum false Pouze události novější než toto datum
endDate datum false Pouze události starší než toto datum
status enum false Status of event, can be ACTIVE | COMPLETED | VISITED | SCHEDULE | OVERDUE | SKIPPED
lastUpdatedStartDate datum false Filter for events which were updated after this date. Cannot be used together with lastUpdatedDuration.
lastUpdatedEndDate datum false Filter for events which were updated up until this date. Cannot be used together with lastUpdatedDuration.
lastUpdatedDuration řetězec false Include only items which are updated within the given duration. The format is , where the supported time units are “d” (days), “h” (hours), “m” (minutes) and “s” (seconds). Cannot be used together with lastUpdatedStartDate and/or lastUpdatedEndDate.
skipMeta boolean false Vyloučí metadatovou část odpovědi (zlepšuje výkon)
strana celé číslo false Číslo stránky
pageSize celé číslo false Počet položek na každé stránce
totalPages boolean false Označuje, zda se má do odpovědi stránkování zahrnout celkový počet stránek.
skipPaging boolean false Označuje, zda se má přeskočit stránkování v dotazu a vrátit všechny události.
dataElementIdScheme řetězec false Schéma ID datového prvku pro export, platné možnosti jsou UID, CODE a ATTRIBUTE:{ID}
categoryOptionComboIdScheme řetězec false ID schéma Možnost kombinace kategorií pro export, platné možnosti jsou UID, CODE a ATRIBUTE:{ID}
orgUnitIdScheme řetězec false Schéma ID organizační jednotky pro export, platné možnosti jsou UID, CODE a ATTRIBUTE:{ID}
programIdScheme řetězec false Program ID scheme to use for export, valid options are UID, CODE and ATTRIBUTE:{ID}
programStageIdScheme řetězec false Program Stage ID scheme to use for export, valid options are UID, CODE and ATTRIBUTE:{ID}
idScheme řetězec false Umožňuje nastavit id schéma pro datový prvek, kombinaci možností kategorie, orgUnit, program a fázi programu najednou.
řazení řetězec false The order of which to retrieve the events from the API. Usage: order=<property>:asc/desc - Ascending order is default.
Properties: event | program | programStage | enrollment | enrollmentStatus | orgUnit | orgUnitName | trackedEntityInstance | eventDate | followup | status | dueDate | storedBy | created | lastUpdated | completedBy | completedDate
order=orgUnitName:DESC order=lastUpdated:ASC
událost čárkou oddělený řetězec false Filter the result down to a limited set of IDs by using event=id1;id2.
skipEventId boolean false Přeskočí identifikátory událostí v odpovědi
atributCc (**) řetězec false Attribute category combo identifier (must be combined with attributeCos)
attributeCos (**) řetězec false Attribute category option identifiers, separated with ; (must be combined with attributeCc)
async false | true false Označuje, zda má být import proveden asynchronně nebo synchronně.
includeDeleted boolean false Když je true, budou do výsledku dotazu zahrnuty měkké odstraněné události.
assignedUserMode enum false Assigned user selection mode, can be CURRENT | PROVIDED | NONE | ANY.
assignedUser čárkou oddělené řetězce false Filter the result down to a limited set of events that are assigned to the given user IDs by using assignedUser=id1;id2. This parameter will be considered only if assignedUserMode is either PROVIDED or null. The API will error out, if for example, assignedUserMode=CURRENT and assignedUser=someId

Poznámka

Pokud dotaz neobsahuje ani attributeCC, ani attributeCos, vrátí server události pro všechna komba voleb atributů, kde má uživatel přístup ke čtení.

Příklady

Dotaz na všechny události s podřazenými určité organizační jednotky:

/api/29/events.json?orgUnit=YuQRtpLP10I&ouMode=CHILDREN

Dotaz na všechny události se všemi potomky určité organizační jednotky, což znamená všechny organizační jednotky v subhierarchii:

/api/33/events.json?orgUnit=O6uvpzGd5pu&ouMode=DESCENDANTS

Dotaz na všechny události s určitou programovou a organizační jednotkou:

/api/33/events.json?orgUnit=DiszpKrYNg8&program=eBAyeGv0exc

Query for all events with a certain program and organisation unit, sorting by due date ascending:

/api/33/events.json?orgUnit=DiszpKrYNg8&program=eBAyeGv0exc&order=dueDate

Query for the 10 events with the newest event date in a certain program and organisation unit - by paging and ordering by due date descending:

/api/33/events.json?orgUnit=DiszpKrYNg8&program=eBAyeGv0exc
  &order=eventDate:desc&pageSize=10&page=1

Query for all events with a certain program and organisation unit for a specific tracked entity instance:

/api/33/events.json?orgUnit=DiszpKrYNg8
  &program=eBAyeGv0exc&trackedEntityInstance=gfVxE3ALA9m

Query for all events with a certain program and organisation unit older or equal to 2014-02-03:

/api/33/events.json?orgUnit=DiszpKrYNg8&program=eBAyeGv0exc&endDate=2014-02-03

Query for all events with a certain program stage, organisation unit and tracked entity instance in the year 2014:

/api/33/events.json?orgUnit=DiszpKrYNg8&program=eBAyeGv0exc
  &trackedEntityInstance=gfVxE3ALA9m&startDate=2014-01-01&endDate=2014-12-31

Query files associated with event data values. In the specific case of fetching an image file an additional parameter can be provided to fetch the image with different dimensions. If dimension is not provided, the system will return the original image. The parameter will be ignored in case of fetching non-image files e.g pdf. Possible dimension values are small(254 x 254), medium(512 x 512), large(1024 x 1024) or original. Any value other than those mentioned will be discarded and the original image will be returned.

/api/33/events/files?eventUid=hcmcWlYkg9u&dataElementUid=C0W4aFuVm4P&dimension=small

Retrieve events with specified Organisation unit and Program, and use Attribute:Gq0oWTf2DtN as identifier scheme

/api/events?orgUnit=DiszpKrYNg8&program=lxAQ7Zs9VYR&idScheme=Attribute:Gq0oWTf2DtN

Retrieve events with specified Organisation unit and Program, and use UID as identifier scheme for orgUnits, Code as identifier scheme for Program stages, and Attribute:Gq0oWTf2DtN as identifier scheme for the rest of the metadata with assigned attribute.

api/events.json?orgUnit=DiszpKrYNg8&program=lxAQ7Zs9VYR&idScheme=Attribute:Gq0oWTf2DtN
  &orgUnitIdScheme=UID&programStageIdScheme=Code

Dotaz na mřížku událostí

In addition to the above event query end point, there is an event grid query end point where a more compact "grid" format of events are returned. This is possible by interacting with /api/events/query.json|xml|xls|csv endpoint.

/api/33/events/query

Most of the query parameters mentioned in event querying and reading section above are valid here. However, since the grid to be returned comes with specific set of columns that apply to all rows (events), it is mandatory to specify a program stage. It is not possible to mix events from different programs or program stages in the return.

Vracení událostí z jedné fáze programu také otevírá nové funkce - například třídění a vyhledávání událostí na základě hodnot jejich datových prvků. api/events/query to podporuje. Níže je uvedeno několik příkladů

A query to return an event grid containing only selected data elements for a program stage

/api/33/events/query.json?orgUnit=DiszpKrYNg8&programStage=Zj7UnCAulEk
  &dataElement=qrur9Dvnyt5,fWIAEtYVEGk,K6uUAvq500H&order=lastUpdated:desc
  &pageSize=50&page=1&totalPages=true

A query to return an event grid containing all data elements of a program stage

/api/33/events/query.json?orgUnit=DiszpKrYNg8&programStage=Zj7UnCAulEk
  &includeAllDataElements=true

A query to filter events based on data element value

/api/33/events/query.json?orgUnit=DiszpKrYNg8&programStage=Zj7UnCAulEk
  &filter=qrur9Dvnyt5:GT:20:LT:50

In addition to the filtering, the above example also illustrates one thing: the fact that there are no data elements mentioned to be returned in the grid. When this happens, the system defaults back to return only those data elements marked "Display in report" under program stage configuration.

We can also extend the above query to return us a grid sorted (asc|desc) based on data element value

/api/33/events/query.json?orgUnit=DiszpKrYNg8&programStage=Zj7UnCAulEk
  &filter=qrur9Dvnyt5:GT:20:LT:50&order=qrur9Dvnyt5:desc

Filtry událostí

To create, read, update and delete event filters you can interact with the /api/eventFilters resource.

/api/33/eventFilters
Vytvořte a aktualizujte definici filtru událostí

For creating and updating an event filter in the system, you will be working with the eventFilters resource. POST is used to create and PUT method is used to update. The event filter definitions are used in the Tracker Capture app to display relevant predefined "Working lists" in the tracker user interface.

Tabulka: Požadavek na užitečné zatížení

Vlastnost požadavku Popis Příklad
název Název filtru. "name":"Můj pracovní seznam"
popis Popis filtru. "description":"pro výpis všech událostí, které mi byly přiřazeny".
program Uid programu. "program" : "a3kGcGDCuk6"
programStage Uid fáze programu. "programStage" : "a3kGcGDCuk6"
eventQueryCriteria Objekt obsahující parametry pro dotazování, řazení a filtrování událostí. "eventQueryCriteria": { "organisationUnit":"a3kGcGDCuk6", "status": "COMPLETED", "createdDate": { "from": "2014-05-01", "to": "2019-03-20" }, "dataElements": ["a3kGcGDCuk6:EQ:1", "a3kGcGDCuk6"], "filters": ["a3kGcGDCuk6:EQ:1"], "programStatus": "ACTIVE", "ouMode": "SELECTED", "assignedUserMode": "PROVIDED", "assignedUsers" : ["a3kGcGDCuk7", "a3kGcGDCuk8"], "followUp": false, "trackedEntityInstance": "a3kGcGDCuk6", "events": ["a3kGcGDCuk7", "a3kGcGDCuk8"], "fields": "eventDate,dueDate", "order": "dueDate:asc,createdDate:desc" }

Tabulka: Definice kritérií dotazu na událost

followUp Používá se k filtrování událostí na základě příznaku sledování registrace. Možné hodnoty jsou true|false. "followUp": true
organisationUnit Chcete-li zadat uid organizační jednotky "organisationUnit": "a3kGcGDCuk7"
ouMode Chcete-li určit režim výběru OU. Možné hodnoty jsou VYBRANÉ| PŘÍSTUPNÉ DĚTI|POTOMCI|ZAJIŠTĚNÍ VŠECH "ouMode": "SELECTED"
assignedUserMode Chcete-li určit režim výběru přiřazeného uživatele pro události. Možné hodnoty jsou CURRENT| PROVIDED| NONE | ANY. Podívejte se do tabulky níže, abyste pochopili, co jednotlivé hodnoty znamenají. Je-li hodnota PROVIDED (nebo null), budou v datovém obsahu zohledněni neprázdní přiřazení uživatelé. "assignedUserMode": "PROVIDED"
assignedUsers Chcete-li zadat seznam přiřazených uživatelů pro události. K použití spolu s výše uvedeným režimem PROVIDEDassignedUserMode. "assignedUsers": ["a3kGcGDCuk7", "a3kGcGDCuk8"]
displayOrderColumns Chcete-li určit výstupní pořadí sloupců "displayOrderColumns": ["eventDate", "dueDate", "program"]
řazení Specifikovat řazení/třídění polí a jejich směry v hodnotách oddělených čárkami. Jedna položka v objednávce má tvar "dataItem:direction". "order"="a3kGcGDCuk6:desc,eventDate:asc"
dataFilters Chcete-li určit filtry, které se mají použít při vypisování událostí "dataFilters"=[{ "dataItem": "abcDataElementUid", "le": "20", "ge": "10", "lt": "20", "gt": "10", "in": ["India", "Norway"], "like": "abc", "dateFilter": { "startDate": "2014-05-01", "endDate": "2019-03-20", "startBuffer": -5, "endBuffer": 5, "period": "LAST_WEEK", "type": "RELATIVE" } }]
status Jakýkoli platný EventStatus "eventStatus": "COMPLETED"
Události Chcete-li specifikovat seznam událostí "events"=["a3kGcGDCuk6"]
completedDate DateFilterPeriod filtrování data objektu na základě data dokončení. "completedDate": { "startDate": "2014-05-01", "endDate": "2019-03-20", "startBuffer": -5, "endBuffer": 5, "period": "LAST_WEEK", "type": "RELATIVE" }
eventDate DateFilterPeriod filtrování data objektu na základě data události. "eventDate": { "startBuffer": -5, "endBuffer": 5, "type": "RELATIVE" }
dueDate DateFilterPeriod filtrování data objektu na základě data platnosti. "dueDate": { "period": "LAST_WEEK", "type": "RELATIVE" }
lastUpdatedDate DateFilterPeriod filtrování data objektu na základě data poslední aktualizace. "lastUpdatedDate": { "startDate": "2014-05-01", "endDate": "2019-03-20", "type": "ABSOLUTE" }

Tabulka: Definice objektu DateFilterPeriod

typ Určete, zda je typ období typu ABSOLUTE | RELATIVNÍ "type" : "RELATIVE"
period Určete, zda se má použít období definované relativním systémem. Použitelné pouze tehdy, když je "typ" RELATIVNÍ. (podporovaná relativní období viz Relativní období) "period" : "THIS_WEEK"
startDate Absolutní datum zahájení. Použitelné pouze tehdy, když je "typ" ABSOLUTNÍ "startDate":"2014-05-01"
endDate Absolutní datum ukončení. Použitelné pouze tehdy, když je "typ" ABSOLUTE "startDate":"2014-05-01"
startBuffer Relativní vlastní datum zahájení. Použitelné pouze tehdy, když je "typ" RELATIVNÍ "startBuffer":-10
endBuffer Relativní vlastní datum ukončení. Použitelné pouze tehdy, když je "typ" RELATIVNÍ "startDate":+10

The available assigned user selection modes are explained in the following table.

Tabulka: Režimy výběru přiřazených uživatelů (přiřazení události)

Režim Popis
CURRENT Přiřazeno aktuálně přihlášenému uživateli
PROVIDED Přiřazeno uživatelům uvedeným v parametru „assignedUser“.
NONE Nepřiřazeno žádným uživatelům.
ANY Přiděleno všem uživatelům.

Ukázkový datový obsah, který lze použít k vytvoření / aktualizaci eventFilter, je uveden níže.

{
  "program": "ur1Edk5Oe2n",
  "description": "Simple Filter for TB events",
  "name": "TB events",
  "eventQueryCriteria": {
    "organisationUnit":"DiszpKrYNg8",
    "eventStatus": "COMPLETED",
    "eventDate": {
      "startDate": "2014-05-01",
      "endDate": "2019-03-20",
      "startBuffer": -5,
      "endBuffer": 5,
      "period": "LAST_WEEK",
      "type": "RELATIVE"
    },
    "dataFilters": [{
      "dataItem": "abcDataElementUid",
      "le": "20",
      "ge": "10",
      "lt": "20",
      "gt": "10",
      "in": ["India", "Norway"],
      "like": "abc"
    },
    {
      "dataItem": "dateDataElementUid",
      "dateFilter": {
        "startDate": "2014-05-01",
        "endDate": "2019-03-20",
        "type": "ABSOLUTE"
      }
    },
    {
      "dataItem": "anotherDateDataElementUid",
      "dateFilter": {
        "startBuffer": -5,
        "endBuffer": 5,
        "type": "RELATIVE"
      }
    },
    {
      "dataItem": "yetAnotherDateDataElementUid",
      "dateFilter": {
        "period": "LAST_WEEK",
        "type": "RELATIVE"
      }
    }],
    "programStatus": "ACTIVE"
  }
}
Načítání a mazání filtrů událostí

Filtr konkrétních událostí lze načíst pomocí následujícího rozhraní API

GET /api/33/eventFilters/{uid}

Všechny filtry událostí lze načíst pomocí následujícího rozhraní API.

GET /api/33/eventFilters?fields=*

Všechny filtry událostí pro konkrétní program lze načíst pomocí následujícího rozhraní API

GET /api/33/eventFilters?filter=program:eq:IpHINAT79UW

Filtr událostí lze odstranit pomocí následujícího rozhraní API

DELETE /api/33/eventFilters/{uid}

Vztahy

Vztahy jsou vazby mezi dvěma entitami v trasovači. Tyto entity mohou být instance trasovaných entit, zápisy a události.

Existuje několik koncových bodů, které vám umožňují zobrazit, vytvořit, odstranit a aktualizovat vztahy. Nejběžnější je /api/trackedEntityInstances koncový bod, kde můžete zahrnout vztahy v datovém obsahu, abyste je mohli vytvořit, aktualizovat nebo odstranit, pokud je vynecháte - podobně jako při práci se zápisy a událostmi ve stejném koncovém bodě. Všechny koncové body trasovače, /api/trackedEntityInstances, /api/enrollments a /api/events také uvedou jejich vztahy, pokud je to požadováno ve filtru pole.

Standardní koncový bod pro vztahy je však /api/relationships. Tento koncový bod poskytuje všechny normální operace CRUD pro vztahy.

You can view a list of relationships by trackedEntityInstance, enrollment or event:

GET /api/relationships?[tei={teiUID}|enrollment={enrollmentUID}|event={eventUID}]

Tento požadavek vrátí seznam všech vztahů, ke kterým máte přístup, a který obsahuje trasovanou entitu, zápis, nebo událost, kterou jste zadali. Každý vztah je reprezentován následujícím JSON:

{
  "relationshipType": "dDrh5UyCyvQ",
  "relationshipName": "Mother-Child",
  "relationship": "t0HIBrc65Rm",
  "bidirectional": false,
  "from": {
    "trackedEntityInstance": {
      "trackedEntityInstance": "vOxUH373fy5"
    }
  },
  "to": {
    "trackedEntityInstance": {
      "trackedEntityInstance": "pybd813kIWx"
    }
  },
  "created": "2019-04-26T09:30:56.267",
  "lastUpdated": "2019-04-26T09:30:56.267"
}

Můžete také zobrazit zadané vztahy pomocí následujícího koncového bodu:

GET /api/relationships/<id>

Chcete-li vytvořit nebo aktualizovat vztah, můžete použít následující koncové body:

POST /api/relationships
PUT /api/relationships

A použijte následující strukturu datového obsahu:

{
  "relationshipType": "dDrh5UyCyvQ",
  "from": {
    "trackedEntityInstance": {
      "trackedEntityInstance": "vOxUH373fy5"
    }
  },
  "to": {
    "trackedEntityInstance": {
      "trackedEntityInstance": "pybd813kIWx"
    }
  }
}

Chcete-li odstranit vztah, můžete použít tento koncový bod:

  DELETE /api/relationships/<id>

V našem příkladu datového obsahu používáme vztah mezi trackedEntityInstances. Z tohoto důvodu vlastnosti „od“ a „do“ našich užitečných dat zahrnují objekty „trackedEntityInstance“. Pokud váš vztah zahrnuje další entity, můžete použít následující vlastnosti:

{
  "enrollment": {
    "enrollment": "<id>"
  }
}
{
  "event": {
    "event": "<id>"
  }
}

Relationship can be soft deleted. In that case, you can use the includeDeleted request parameter to see the relationship.

GET /api/relationships?tei=pybd813kIWx?includeDeleted=true

Strategie aktualizací

Two update strategies for all 3 tracker endpoints are supported: enrollment and event creation. This is useful when you have generated an identifier on the client side and are not sure if it was created or not on the server.

Tabulka: Dostupné strategie sledování

Parametr Popis
VYTVOŘIT Pouze vytvořit, toto je výchozí chování.
CREATE_AND_UPDATE Zkuste a porovnejte ID, pokud existuje, aktualizujte, pokud ne vytvořte.

Chcete-li změnit parametr, použijte parametr strategie:

POST /api/33/trackedEntityInstances?strategy=CREATE_AND_UPDATE

Hromadné mazání trasovače

Bulk deletion of tracker objects work in a similar fashion to adding and updating tracker objects, the only difference is that the importStrategy is DELETE.

Example: Bulk deletion of tracked entity instances:

{
  "trackedEntityInstances": [
    {
      "trackedEntityInstance": "ID1"
    }, {
      "trackedEntityInstance": "ID2"
    }, {
      "trackedEntityInstance": "ID3"
    }
  ]
}
curl -X POST -d @data.json -H "Content-Type: application/json"
  "http://server/api/33/trackedEntityInstances?strategy=DELETE"

Příklad: Hromadné mazání zápisů:

{
  "enrollments": [
    {
       "enrollment": "ID1"
    }, {
      "enrollment": "ID2"
    }, {
      "enrollment": "ID3"
    }
  ]
}
curl -X POST -d @data.json -H "Content-Type: application/json"
  "http://server/api/33/enrollments?strategy=DELETE"

Příklad: Hromadné mazání událostí:

{
  "events": [
    {
      "event": "ID1"
    }, { 
      "event": "ID2"
    }, { 
      "event": "ID3"
    }
  ]
}
curl -X POST -d @data.json -H "Content-Type: application/json"
  "http://server/api/33/events?strategy=DELETE"

Opětovné použití identifikátoru a odstranění položky metodami POST a PUT

Tracker endpoints /trackedEntityInstances, /enrollments, /events support CRUD operations. The system keeps track of used identifiers. Therefore, an item which has been created and then deleted (e.g. events, enrollments) cannot be created or updated again. If attempting to delete an already deleted item, the system returns a success response as deletion of an already deleted item implies no change.

The system does not allow to delete an item via an update (PUT) or create (POST) method. Therefore, an attribute deleted is ignored in both PUT and POST methods, and in POST method it is by default set to false.

Import parametrů

Proces importu lze přizpůsobit pomocí sady parametrů importu:

Tabulka: Parametry importu

Parametr Hodnoty (výchozí první) Popis
dataElementIdScheme id | jméno | kód | atribut:ID Vlastnost objektu datového prvku, který se má použít k mapování hodnot dat.
orgUnitIdScheme id | jméno | kód | atribut:ID Vlastnost objektu organizační jednotky, která se má použít k mapování datových hodnot.
idScheme id | name | code| attribute:ID Vlastnost všech objektů včetně datových prvků, organizačních jednotek a kombinací možností kategorií, které se mají použít k mapování datových hodnot.
dryRun false | true Zda uložit změny na serveru nebo jen vrátit souhrn importu.
strategie CREATE | UPDATE | CREATE_AND_UPDATE | DELETE Uložit objekty všech, nový nebo aktualizovat stav importu na server.
skipNotifications true | false Označuje, zda se mají odesílat upozornění na dokončené události.
skipFirst true | false Relevantní pouze pro import CSV. Označuje, zda soubor CSV obsahuje řádek záhlaví, který by měl být přeskočen.
importReportMode FULL, ERRORS, DEBUG Sets the ImportReport mode, controls how much is reported back after the import is done. ERRORS only includes ObjectReports for object which has errors. FULL returns an ObjectReport for all objects imported, and DEBUG returns the same plus a name for the object (if available).

CSV Import / Export

In addition to XML and JSON for event import/export, in DHIS2.17 we introduced support for the CSV format. Support for this format builds on what was described in the last section, so here we will only write about what the CSV specific parts are.

To use the CSV format you must either use the /api/events.csv endpoint, or add content-type: text/csv for import, and accept: text/csv for export when using the /api/events endpoint.

The order of column in the CSV which are used for both export and import is as follows:

Tabulka: Sloupec CSV

Index Klíč Typ Popis
1 událost identifikátor Identifikátor události
2 status enum Status of event, can be ACTIVE | COMPLETED | VISITED | SCHEDULE | OVERDUE | SKIPPED
3 program identifikátor Identifikátor programu
4 programStage identifikátor Identifikátor fáze programu
5 zápis identifikátor Identifikátor zápisu (instance programu)
6 orgUnit identifikátor Identifikátor organizační jednotky
7 eventDate datum Datum události
8 dueDate datum Datum splatnosti
9 latitude dvojnásobek Zeměpisná šířka, kde se událost stala
10 longitude dvojnásobek Zeměpisná délka, kde se událost stala
11 dataElement identifikátor Identifikátor datového prvku
12 value řetězec Hodnota / míra události
13 storedBy řetězec Událost byla uložena uživatelem (výchozí nastavení pro aktuálního uživatele)
14 providedElsewhere boolean Byla tato hodnota shromážděna někde jinde
14 completedDate datum Dokončený termín akce
14 completedBy řetězec Uživatelské jméno uživatele, který dokončil událost

Example of 2 events with 2 different data value each:

EJNxP3WreNP,COMPLETED,<pid>,<psid>,<enrollment-id>,<ou>,2016-01-01,2016-01-01,,,<de>,1,,
EJNxP3WreNP,COMPLETED,<pid>,<psid>,<enrollment-id>,<ou>,2016-01-01,2016-01-01,,,<de>,2,,
qPEdI1xn7k0,COMPLETED,<pid>,<psid>,<enrollment-id>,<ou>,2016-01-01,2016-01-01,,,<de>,3,,
qPEdI1xn7k0,COMPLETED,<pid>,<psid>,<enrollment-id>,<ou>,2016-01-01,2016-01-01,,,<de>,4,,

Strategie importu: SYNC

Strategie importu SYNC by měla být používána pouze interní synchronizační úlohou a ne pro běžný import. Strategie SYNC umožňuje, aby všechny 3 operace: CREATE, UPDATE, DELETE byly přítomny současně i v datovém obsahu.

Správa vlastnictví trasovače

A new concept called Tracker Ownership is introduced from 2.30. There will now be one owner organisation unit for a tracked entity instance in the context of a program. Programs that are configured with an access level of PROTECTED or CLOSED will adhere to the ownership privileges. Only those users belonging to the owning org unit for a tracked entity-program combination will be able to access the data related to that program for that tracked entity.

Přepsání vlastnictví trasovače: Rozbijte sklo

It is possible to temporarily override this ownership privilege for a program that is configured with an access level of PROTECTED. Any user will be able to temporarily gain access to the program related data, if the user specifies a reason for accessing the tracked entity-program data. This act of temporarily gaining access is termed as breaking the glass. Currently, the temporary access is granted for 3 hours. DHIS2 audits breaking the glass along with the reason specified by the user. It is not possible to gain temporary access to a program that has been configured with an access level of CLOSED. To break the glass for a tracked entity program combination, you can issue a POST request as shown:

/api/33/tracker/ownership/override?trackedEntityInstance=DiszpKrYNg8
  &program=eBAyeGv0exc&reason=patient+showed+up+for+emergency+care

Převod vlastnictví trasovače

Je možné převést vlastnictví sledovaného subjektu - programu z jedné organizační jednotky na druhou. To bude užitečné v případě předávání pacientů nebo migrace. Vlastnictví může převést pouze vlastník (nebo uživatelé, kteří rozbili sklo). Chcete-li převést vlastnictví sledované entity-programu na jinou organizační jednotku, můžete vystavit požadavek PUT, jak je znázorněno na obrázku:

/api/33/tracker/ownership/transfer?trackedEntityInstance=DiszpKrYNg8
  &program=eBAyeGv0exc&ou=EJNxP3WreNP

Potenciální duplikáty

Potenciální duplikáty jsou záznamy, se kterými pracujeme ve funkci deduplikace dat. Vzhledem k povaze funkce deduplikace je tento koncový bod API poněkud omezen.

Potenciální duplikát představuje dvojici záznamů, u kterých existuje podezření, že jsou duplikáty.

Datový obsah potenciálního duplikátu vypadá takto:

{
  "original": "<id>",
  "duplicate": "<id>",
  "status": "OPEN|INVALID|MERGED"
}

Seznam potenciálních duplikátů můžete načíst pomocí následujícího koncového bodu:

GET /api/potentialDuplicates
Název parametru Popis Typ Povolené hodnoty
tei Seznam instancí trasovaných entit Seznam řetězců (oddělených čárkou) ID existující instance trasované entity
status Potenciální duplicitní stav řetězec OPEN <default>, INVALID, MERGED, ALL
Stavový kód Popis
400 Neplatný stav vstupu

Jednotlivé potenciální duplicitní záznamy můžete zkontrolovat:

GET /api/potentialDuplicates/<id>
Stavový kód Popis
404 Potenciální duplikát nebyl nalezen

Chcete-li vytvořit nový potenciální duplikát, můžete použít tento koncový bod:

POST /api/potentialDuplicates

The payload you provide must include IDs of Original and Duplicate TEIs.

{
  "original": "<id>",
  "duplicate": "<id>"
}
Stavový kód Popis
400 Input original or duplicate is null or has invalid id
403 User do not have access to read origianl or duplicate TEIs
404 TEI not found
409 Pair of original and duplicate TEIs already existing

Chcete-li aktualizovat potenciální duplicitní stav:

PUT /api/potentialDuplicates/<id>
Název parametru Popis Typ Povolené hodnoty
status Potenciální duplicitní stav řetězec OPEN, INVALID, MERGED
Stavový kód Popis
400 Potenciální duplikát nemůžete aktualizovat na MERGED, protože to je možné pouze na základě žádosti o sloučení
400 Nelze aktualizovat potenciální duplikát, který je již ve stavu MERGED

Merging Tracked Entity Instances

Tracked entity instances can now be merged together if they are viable. To initiate a merge, the first step is to define two tracked entity instances as a Potential Duplicate. The merge endpoint will move data from the duplicate tracked entity instance to the original tracked entity instance, and delete the remaining data of the duplicate.

Ke sloučení potenciálního duplikátu nebo dvou instancí trasovaných entit, které potenciální duplikát představuje, lze použít následující koncový bod:

POST /api/potentialDuplicates/<id>/merge
Název parametru Popis Typ Povolené hodnoty
mergeStrategy Strategie, která se má použít pro sloučení potenciálního duplikátu enum AUTO (výchozí) nebo MANUAL

The endpoint accepts a single parameter, "mergeStrategy", which decides which strategy to use when merging. For the AUTO strategy, the server will attempt to merge the two tracked entities automatically, without any input from the user. This strategy only allows merging tracked entities without conflicting data (See examples below). The other strategy, MANUAL, requires the user to send in a payload describing how the merge should be done. For examples and rules for each strategy, see their respective sections below.

Merge Strategy AUTO

The automatic merge will evaluate the mergability of the two tracked entity instances, and merge them if they are deemed mergable. The mergability is based on whether the two tracked entity instances has any conflicts or not. Conflicts refers to data which cannot be merged together automatically. Examples of possible conflicts are: - Stejný atribut má v každé instanci trasované entity různé hodnoty - Obě instance trasovaných entit jsou zapsány do stejného programu - Instance trasovaných entit mají různé typy

Pokud dojde ke konfliktu, uživateli se vrátí chybová zpráva.

When no conflicts are found, all data in the duplicate that is not already in the original will be moved over to the original. This includes attribute values, enrollments (Including events) and relationships. After the merge completes, the duplicate is deleted and the potentialDuplicate is marked as MERGED.

Při požadavku na automatické sloučení, jako je tento, není datový obsah vyžadován a bude ignorován.

Merge Strategy MANUAL

The manual merge is suitable when the merge has resolvable conflicts, or when not all the data is required to be moved over during a merge. For example, if an attribute has different values in both tracked entity instances, the user can specify whether to keep the original value, or move over the duplicate's value. Since the manual merge is the user explicitly requesting to move data, there are some different checks being done here: - Vztah nemůže být mezi originálem a duplikátem (To má za následek neplatný vztah odkazující na sebe) - Vztah nemůže být stejného typu a ke stejnému objektu v obou instancích trasované entity (např. mezi původní a jinou a duplicitní a jinou; výsledkem by byl duplicitní vztah)

Existují dva způsoby, jak provést ruční sloučení: S a bez datového obsahu.

When a manual merge is requested without a payload, we are telling the API to merge the two tracked entity instances without moving any data. In other words, we are just removing the duplicate and marking the potentialDuplicate MERGED. This might be valid in a lot of cases where the tracked entity instance was just created, but not enrolled for example.

V opačném případě, pokud je požadováno ruční sloučení s datovou částí, datová část odkazuje na to, jaká data by měla být přesunuta z duplikátu do originálu. Datový obsah vypadá takto:

{
  "trackedEntityAttributes": ["B58KFJ45L9D"],
  "enrollments": ["F61SJ2DhINO"],
  "relationships": ["ETkkZVSNSVw"]
}

This payload contains three lists, one for each of the types of data that can be moved. trackedEntityAttributes is a list of uids for tracked entity attributes, enrollments is a list of uids for enrollments and relationships a list of uids for relationships. The uids in this payload have to refer to data that actually exists on the duplicate. There is no way to add new data or change data using the merge endpoint - Only moving data.

Additional information about merging

Currently it is not possible to merge tracked entity instances that are enrolled in the same program, due to the added complexity. A workaround is to manually remove the enrollments from one of the tracked entity instances before starting the merge.

All merging is based on data already persisted in the database, which means the current merging service is not validating that data again. This means if data was already invalid, it will not be reported during the merge. The only validation done in the service relates to relationships, as mentioned in the previous section.

Program Notification Template

Program Notification Template lets you create message templates which can be sent as a result of different type of events. Message and Subject templates will be translated into actual values and can be sent to the configured destination. Each program notification template will be transformed to either MessageConversation object or ProgramMessage object based on external or internal notificationRecipient. These intermediate objects will only contain translated message and subject text. There are multiple configuraiton parameters in Program Notification Template which are critical for correct working of notifications. All those are explained in the table below.

POST /api/programNotificationTemplates
{
    "name": "Case notification",
    "notificationTrigger": "ENROLLMENT",
    "subjectTemplate": "Case notification V{org_unit_name}",
    "displaySubjectTemplate": "Case notification V{org_unit_name}",
    "notifyUsersInHierarchyOnly": false,
    "sendRepeatable": false,
    "notificationRecipient": "ORGANISATION_UNIT_CONTACT",
    "notifyParentOrganisationUnitOnly": false,
    "displayMessageTemplate": "Case notification A{h5FuguPFF2j}",
    "messageTemplate": "Case notification A{h5FuguPFF2j}",
    "deliveryChannels": [
        "EMAIL"
    ]
}

Pole jsou vysvětlena v následující tabulce.

Tabulka: Datový obsah šablony oznámení programu

Pole Požadované Popis Hodnoty
název Ano name of Program Notification Template case-notification-alert
notificationTrigger Ano Kdy má být spuštěno oznámení. Možné hodnoty jsou ENROLLMENT, COMPLETION, PROGRAM_RULE, SCHEDULED_DAYS_DUE_DATE ZÁPIS
subjectTemplate Ne Šablona řetězce předmětu Case notification V{org_unit_name}
messageTemplate Ano Řetězec šablony zprávy Oznámení o případu A{h5FuguPFF2j}
notificationRecipient ANO Kdo bude dostávat oznámení. Možné hodnoty jsou USER_GROUP, ORGANISATION_UNIT_CONTACT, TRACKED_ENTITY_INSTANCE, USERS_AT_ORGANISATION_UNIT, DATA_ELEMENT, PROGRAM_ATTRIBUTE, WEB_HOOK USER_GROUP
deliveryChannels Ne Který kanál by měl být použit pro toto oznámení. Může to být buď SMS, EMAIL nebo HTTP SMS
sendRepeatable Ne Zda má být oznámení odesláno vícekrát false

POZNÁMKA: WEB_HOOK notificationRecipient se používá pouze k POST http požadavku na externí systém. Při použití WEB_HOOK se ujistěte, že jste zvolili doručovací kanál HTTP.

Retrieving and deleting Program Notification Template

Seznam šablon oznámení programu lze získat pomocí GET.

GET /api/programNotificationTemplates

Pro jednu konkrétní šablonu oznámení programu.

GET /api/33/programNotificationTemplates/{uid}

Chcete-li získat filtrovaný seznam šablon oznámení programu

GET /api/programNotificationTemplates/filter?program=<uid>
GET /api/programNotificationTemplates/filter?programStage=<uid>

Šablonu oznámení programu lze odstranit pomocí DELETE.

DELETE /api/33/programNotificationTemplates/{uid}

Program Messages

Program message lets you send messages to tracked entity instances, contact addresses associated with organisation units, phone numbers and email addresses. You can send messages through the messages resource.

/api/33/messages

Odesílání zpráv programu

Programové zprávy lze odesílat pomocí dvou doručovacích kanálů:

  • SMS (SMS)

  • E-mailová adresa (EMAIL)

Zprávy programu lze zasílat různým příjemcům:

  • Tracked entity instance: The system will look up attributes of value type PHONE_NUMBER or EMAIL (depending on the specified delivery channels) and use the corresponding attribute values.

  • Organisation unit: The system will use the phone number or email information registered for the organisation unit.

  • List of phone numbers: The system will use the explicitly defined phone numbers.

  • List of email addresses: The system will use the explicitly defined email addresses.

Below is a sample JSON payload for sending messages using POST requests. Note that message resource accepts a wrapper object named programMessages which can contain any number of program messages.

POST /api/33/messages
{
  "programMessages": [{
    "recipients": {
      "trackedEntityInstance": {
        "id": "UN810PwyVYO"
      },
      "organisationUnit": {
        "id": "Rp268JB6Ne4"
      },
      "phoneNumbers": [
        "55512345",
        "55545678"
      ],
      "emailAddresses": [
        "johndoe@mail.com",
        "markdoe@mail.com"
      ]
    },
    "programInstance": {
      "id": "f3rg8gFag8j"
    },
    "programStageInstance": {
      "id": "pSllsjpfLH2"
    },
    "deliveryChannels": [
      "SMS", "EMAIL"
    ],
    "notificationTemplate": "Zp268JB6Ne5",
    "subject": "Outbreak alert",
    "text": "An outbreak has been detected",
    "storeCopy": false
  }]
}

Pole jsou vysvětlena v následující tabulce.

Tabulka: Datový obsah zprávy programu

Pole Požadované Popis Hodnoty
příjemci Ano Příjemci programové zprávy. Musí být uveden alespoň jeden příjemce. Pro zprávu lze zadat libovolný počet příjemců / typů. Lze sledovat EntityInstance, OrganizationUnit, řadu telefonních čísel nebo řadu e-mailových adres.
programInstance Je vyžadováno buď toto, nebo programStageInstance Instance programu / zápisu. ID zápisu.
programStageInstance Vyžaduje se buď toto, nebo programInstance Instance / událost fáze programu. Event ID.
deliveryChannels Ano Pole doručovacích kanálů. SMS | EMAIL
předmět Ne Předmět zprávy. Neplatí pro kanál doručování SMS. Text.
text Ano Text zprávy. Text.
storeCopy Ne Zda uložit kopii zprávy programu v DHIS2. false (default) | true

Minimalistický příklad pro odeslání zprávy přes SMS na instanci trasované entity vypadá takto:

curl -d @message.json "https://play.dhis2.org/demo/api/33/messages"
  -H "Content-Type:application/json" -u admin:district
{
  "programMessages": [{
    "recipients": {
      "trackedEntityInstance": {
        "id": "PQfMcpmXeFE"
      }
    },
    "programInstance": {
      "id": "JMgRZyeLWOo"
    },
    "deliveryChannels": [
      "SMS"
    ],
    "text": "Please make a visit on Thursday"
  }]
}

Načítání a mazání zpráv programu

Seznam zpráv lze načíst pomocí GET.

GET /api/33/messages

Chcete-li získat seznam odeslaných zpráv trasování, můžete použít níže uvedený koncový bod. Musí být poskytnuto uid ProgramInstance nebo ProgramStageInstance.

GET /api/33/messages/scheduled/sent?programInstance={uid}
GET /api/33/messages/scheduled/sent?programStageInstance={uid}

Chcete-li získat seznam všech naplánovaných zpráv

GET /api/33/messages/scheduled
GET /api/33/messages/scheduled?scheduledAt=2020-12-12

Jednu konkrétní zprávu lze také načíst pomocí GET.

GET /api/33/messages/{uid}

Zprávu lze smazat pomocí DELETE.

DELETE /api/33/messages/{uid}

Dotazování na zprávy programu

The program message API supports program message queries based on request parameters. Messages can be filtered based on below mentioned query parameters. All requests should use the GET HTTP verb for retrieving information.

Tabulka: API zpráv dotazovacího programu

Parametr URL
programInstance /api/33/messages?programInstance=6yWDMa0LP7
programStageInstance /api/33/messages?programStageInstance=SllsjpfLH2
trackedEntityInstance /api/33/messages?trackedEntityInstance=xdfejpfLH2
organisationUnit /api/33/messages?ou=Sllsjdhoe3
processedDate /api/33/messages?processedDate=2016-02-01