ЕСОЗ - публічна документація

[DRAFT] Qualify Medication Request by ID [API-005-008-002-0145]

Сторінка знаходиться в процесі розробки. Інформація на ній може бути застарілою.

https://e-health-ua.atlassian.net/wiki/spaces/EN/pages/17591304241 (remove the link block before publishing the document)

Properties of a REST API method document

Document type

Метод REST API

Document title

[Document status] REST API [Назва методу] [ID методу]

Guideline ID

GUI-0011

Author

@

Document version

1

Document status

DRAFT

Date of creation

ХХ.ХХ.ХХХХ (дата фінальної версії документа – RC або PROD)

Date of update

ХХ.ХХ.ХХХХ (дата зміни версії)

Method API ID

API-005-008-002-0145

Microservices (namespace)

IL

Component

ePrescription

Component ID

COM-005-008

Link на API-специфікацію

https://ehealthmisapi1.docs.apiary.io/#reference/public.-reimbursement/medication-request/qualify-medication-request-by-id

Resource

{{host}}/api/medication_requests/{{id}}/actions/qualify

Scope

medication_request:details

Protocol type

REST

Request type

POST

Sync/Async

Sync

Public/Private

Public

Purpose

This WS is designed to qualify Medication request (post) - check the ability to use Medication request within the Medication program and receive program participants

Logic

Процеси роботи з погашенням електронних рецептів

Технічний опис бізнес-процесу погашення рецепту в ЦБД ЕСОЗ

Preconditions

MR should be found by number

Configuration parameters

Description of the configuration parameters that are used when processing a request in the system

Dictionaries

Input parameters

Description of input parameters

Input parameter

Mandatory

Type

Description

Example

Input parameter

Mandatory

Type

Description

Example

1

id

 M

String

Medication request identifier

2848a935-5fd7-48ba-b235-a9b5d475c647

Request structure

See on API-specification (посилання на сторінку з API-специфікацією)

Description of the REST API request structure, example

{ "division_id": "2848a935-5fd7-48ba-b235-a9b5d475c647", "programs": [ { "id": "59781de0-2e64-4359-b716-bcc05a32c10f" } ] }

Request data validation

Authorize

  1. Verify the validity of access token.

  2. Check user scope (scope = 'medication_request:details') in order to perform this action

    1. In case error - generate 401 response.

Validate request

Validate request using JSON schema.

Validate FK

  1. Validate id - medication_request_id exists

    1. Return  404 in case (not found medication request in DB with this ID).

  2. Validate [programs.id] - medical programs id  exists

    • Return 422 in case validation fails (422 EView - not found medical program in DB with this ID)

Get Medication Request 

Invoke Get Medication request by ID 

Validation status

  1. For info - status charts: Medication_request.

  2. Check Medication Request `status` = ACTIVE

    1. if invalid - return 409 error (message: "Invalid status Medication request for qualify action!")'.

Validate related Care plan

If medication_request.based_on is present and not null:

  1. Verify Care plan:

    1. It should be in active status

      1. in case of error - return 409 (message: "Invalid care plan status").

    2. Care plan's period end (if exist) should be greater than current date or equal

      1. in case of error - return 409 (message: “Care plan expired“).

  2. Verify care plan Activity:

    1. It has scheduled, in_progress status

      1. in case of error - return 409 (message: "Invalid activity status").

    2. Validate quantity is not exceeded

      1. Select all MD (medication dispenses) in status PROCESSED related to the Medication requests which based_on one activity 

        1. Sum medication_qty in the filtered Medication dispenses as dispensed_qty

        2. medication_qty from current MR as current_qty

        3. Calculate remaining_qty = activity.quantity - (dispensed_qty+current_qty)

      2. Check remaining_qty is greater then zero

        1. error return 409 "The total amount of the dispensed medication quantity exceeds quantity in care plan activity"

Validate division

  1. Validate division is active

    1. in case of error - return 409 ("Division is not active")

  2. Validate division belongs to user's legal entity

    1. in case of error - return 409 ("Division does not belong to user's legal entity")

  3. If chart parameter DISPENSE_DIVISION_DLS_VERIFY is on, then validate division is DLS verified (dls_verified=true)

    1. in case of error - return 409 "Division is not verified in DLS"

  4. Check division participates in submitted programs. Validate Provision for each Medical Program:

    1. If the medical program has no setting skip_contract_provision_verify or it is equal to false/null:

      1. if medical program in the request has funding_source one of NHS, LOCAL

        1. In case of error - return status=INVALID for a program, rejection_reason="Program was configured incorrectly. Either incorrect source of funding or option skip_contract_provision_verify"

      2. provision exist and active for the division:

        1. in case of error - return status=INVALID for a program, rejection_reason= "Division does not provide the medical program"

      3. if medical program in the request has funding_source = NHS:

        1. provision relates to the actual reimbursement contract: contract.start_date <= current_date <= contract.end_date, is_active = true, status = VERIFIED, contracts.type==reimbursement, contracts.contractor_legal_entity_id=token.client_id, contracts.medical_program_id==$.medical_program_id

          1. in case of error - return status=INVALID for a program, rejection_reason="Medical program provision is not related to any actual contract for the current date"

        2. contract is_suspended = false

          1. in case of error - return status=INVALID for a program, rejection_reason="Contract with number <contract_number> is suspended"

      4. if medical program in the request has funding_source = LOCAL, then check medical_program_provision.msp_legal_entity_id = medication_request.legal_entity_id

        1. in case of error - return status=INVALID for a program, rejection_reson = "Medical program can not be provided for the legal entity specified in the medication request"

    2. else if skip_contract_provision_verify = true, then skip provision verification for the medical program

  5. Get license_types_allowed parameter from settings of medical program from request $.medical_program_id:

    1. if it is exists and not empty, get list of all license types from parameter.
      Check that division has active healthcare services with following parameters:

      1. legal_entity_id = client_id from access token

      2. division_id = division_id from request

      3. status = 'ACTIVE'

      4. licensed_healthcare_service.status = 'ACTIVE'

      5. healthcare_service.license_id is not null and licenses.type = value from license_types_allowed parameter

        1. in case of error - return status=INVALID for a program, rejection_reason = 'Division does not have active licenses to provide the medical program'

Logic for qualify (analyze compliance with programs)

  • Each Medical program may have its unique conditions for the medication dispense. It can be based on analysis of personal info, medications list, terms, locations and combinations of them.

    Also, it is possible to have the medication dispense without any Medical program.

    However for any Medical program we need a separate block of branching logic.

    Check compatibility only for programs which are available in payload (array)

    If program status is invalid, the reason must be saved and returned in response.

Check compliance for programs

  1. Validate 2 checks (below in the text) for programs

    1. if passed - save status this program for response = VALID.

Check INNM_dosage compliance for the programs

Validation purpose:  There is a list of medications (which links to innm_dosage) which can be used for the program. It must be check whether there is at least one available medication for the innm_dosage for the particular program.

Check that there is at least one medication (brand or innm_dosage) associated with medical program that can be dispensed to the patient

  1. Get info from Medication request  by id in payload, set temp variable object `_MR`

  2. Validate the compatibility of innm with the medication program list 

    1. Search for active innm_dosages that associated with medical program

      1. medications.is_active = true

      2. medications.type = INNM_DOSAGE

      3. program_medications.is_active = true

    2. Search for active brands that have innm_dosage as primary ingredient and are associated with medical program

      1. medications.is_active = true

      2. medications.type = BRAND

      3. ingredients.is_primary = true

      4. program_medications.is_active = true

    3. if nothing found:

      1. add to response: status = INVALID

      2. add to response: rejection_reason = "Innm not on the list of approved innms for program '#{program.name}"

IF EXISTS (SELECT * FROM program_medications MP INNER JOIN medications M ON M.id = MP.medication_id AND M.type = BRANDS INNER JOIN ingredients I ON I.parend_id = M.id AND I.is_primary = TRUE AND I.medication_child_id = _MR.medication_id WHERE MP.medical_program_id == $.id AND MP.is_active == TRUE AND M.is_active == TRUE)

Check absence a same medication for the programs

Validation purpose: It could be done several dispenses for one medication request per one innm for one patient until sum(medication_dispenses.medication_qty) < medication_request.medication_qty

Example validation: without crossing time

 

EP

 Preconditions # 1

Result validate #1 

 Preconditions #2

Result validate #2 

 Preconditions #3

Result validate #2 

EP

 Preconditions # 1

Result validate #1 

 Preconditions #2

Result validate #2 

 Preconditions #3

Result validate #2 

PreQualifyMedicationRequestRequest

No records in
MedicationRequestRequest 
and in MedicationRequest

OK

Create record in
MedicationRequestRequest 
or in MedicationRequest

Not valid

Medications request
dispensed (COMPLETED)

Not valid

QualifyMedicationRequestByID

No records in
MedicationRequestRequest 
and in MedicationRequest

Not possible

Create record in
MedicationRequestRequest 
or in MedicationRequest

OK

Medications request
dispensed (COMPLETED) 

Not valid

 

  1. For info - status charts: Medication Request Status Chart & Medication Dispense Status Chart

  2. Get `check_innm_id`

    SELECT I.innm_child_id FROM ingredients I WHERE I.parent_id = _MR.medication_id AND I.is_primary = TRUE

     

  3. Get Medication requests with their linked completed Medication dispense by person_id & innm_id

     

     

  4. Validate medication request_id

    1. for medication_dispense.medication_request_id !== $.id

      1. Validate exist (IF EXIST ()  - that is any crossing  calculating term (started_at + ended_at) for payload with terms selecting Medication requests with linked Medication dispense (started_at + ended_at))

      2. if found 

        1. get $.medical_programs.medical_program_setting by medical_program_id from request

          1. validate skip_mnn_in_treatment_period variable

            1. in case skip_mnn_in_treatment_period == FALSE (or absent) 

              1. validate request according to logic:

                1. add to response: status = INVALID

                  add to response: rejection_reason = "For the patient at the same term there can be only 1 dispensed medication request per one and the same innm!"

            2. in case skip_mnn_in_treatment_period == TRUE

              1. skip validating frequency of receiving drugs

    2. for medication_dispense.medication_request_id = $.id

      1. Validate medication request qty: sum(medication_dispenses.medication_qty) >= medication_request.medication_qty 

      2. if found

        1. add to response: status = INVALID

          add to response: rejection_reason = "Sum of dispense's medication quantity can not be more then medication_request.medication_qty".

 

Parameters that are used when processing the request

Configuration parameters

Access to the method is defined by the scope medication_request:details. Permission for this scope is determined by the System administrator by configuring scopes in the context of clients and roles.

Processing

A list of processes related to receiving, changing or transmitting data according to the logic defined in the REST API

Response structure examples

Generate structure for response

  • Collect response array for all programs in payload with status for each (VALID or INVALID) and rejection_reason

  • For all VALID programs - Get linked medications (type = BRAND) with reimbursement info 

  • Show only active program medications based on start_date and end (start_date must be earlier or equal to current date or empty, end_date must be greater or equal to current date or empty)

    • Filter participants simultaneously by container_dosage and max_request_dosage

Prepare & return response data structure

Fill response WS data structure

  1. Validate response using JSON schemas

    1. Return 422 with list of validation errors in case validation fails (422 EView)

Also see on Apiary.

Example:

See on API-specification (посилання на сторінку з API-специфікацією)

Description of the REST API response structure, example

HTTP status codes

Response code

HTTP Status code

Message

Internal name

Description

Response code

HTTP Status code

Message

Internal name

Description

1

Базові

2

 

401

response

 

 

3

 

404

not found medication request in DB with this ID

 

Не знайдено електронний рецепт у базі даних з цим ідентифікатором

4

 

409

Invalid status Medication request for qualify action!

 

Недопустимий статус електронного рецепту для перевірки на відповідність програмі реімбурсації

5

 

409

Invalid care plan status

 

Невірний статус плану лікування

6

 

409

Care plan expired

 

Закінчився термін дії плану лікування

7

 

409

Invalid activity status

 

Недопустимий статус призначення

8

 

409

The total amount of the dispensed medication quantity exceeds quantity in care plan activity

 

Загальна кількість лікарського засобу, що зазначена у рецепті перевищує кількість лікарського засобу, що доступна у призначенні плану лікування

9

 

409

Division is not active

 

Структурний підрозділ не активний

10

 

409

Division does not belong to user's legal entity

 

Структурний підрозділ не належить юридичній особі користувача

11

 

409

Division is not verified in DLS

 

У структурного підрозділу відсутня ліцензія на роздрібну торгівлю лікарськими засобами

12

 

 

Program was configured incorrectly. Either incorrect source of funding or option skip_contract_provision_verify

 

Неправильно визначені налаштування програми. Або вказане некоректне джерело фінансування або встановлено опцію "скинути налаштування верифікації контракту АЗ з НСЗУ

13

 

 

Division does not provide the medical program

 

Для структурного підрозділу не вказано можливість відпуску ліків за даною програмою відшкодування

14

 

 

Medical program provision is not related to any actual contract for the current date

 

Забезпечення медичної програми не пов'язане з будь-яким фактичним договором на поточну дату

15

 

 

Contract with number <contract_number> is suspended

 

Договір з номером <contract_number> призупинено

16

 

 

Medical program can not be provided for the legal entity specified in the medication request

 

Створення рецепта за обраною програмою не дозволене для вашого закладу

17

 

 

Division does not have active licenses to provide the medical program

 

Підрозділ не має активної ліцензії для відпуску ліків за даною медичною програмою

18

 

 

Innm not on the list of approved innms for program '#{program.name}

 

Лікарський засіб відсутній у програмі реімбурсації #{program.name}

19

 

 

For the patient at the same term there can be only 1 dispensed medication request per one and the same innm!

 

Для пацієнта на той самий термін може бути лише 1 погашений рецепт на один і той самий лікарський засіб

20

 

 

Sum of dispense's medication quantity can not be more then medication_request.medication_qty

 

Загальна кількість ЛЗ до погашення не може бути більшою, ніж кількість ЛЗ, зазначена у рецепті

21

Специфічні

22

 

422

not found medical program in DB with this ID

 

Не знайдено медичну програму у базі даних з цим ідентифікатором

Post-processing processes

No

Technical modules where the method is used

List of pages describing technical modules where the method is used

 

ЕСОЗ - публічна документація