/*
* Автор: Борисов Д.Г.
* Дата: 2013-05-29
* Задача: Замена русской буквы "с" на английскую "c".
* Описание: Замена русской буквы "с" на английскую "c" в полях oper_currency_code и oper_currency_amount таблиц mess_cfm_announce_oper и mess_cfm_exec
* Изменяются объекты:
		alter table mess_cfm_announce_oper rename column OPER_CURRENCY_CODE  - русская буква "С" заменена на английскую
		alter table mess_cfm_exec rename column OPER_CURRENCY_CODE  - русская буква "С" заменена на английскую
		alter table mess_cfm_announce_oper rename column OPER_CURRENCY_AMOUNT  - русская буква "С" заменена на английскую
		alter table mess_cfm_exec rename column OPER_CURRENCY_AMOUNT  - русская буква "С" заменена на английскую
		
        create or replace package KFM.PKG_MESSAGES_CFM
		create or replace package body KFM.PKG_MESSAGES_CFM
		create or replace package KFM.PKG_MESS_CFM_1
		create or replace package body KFM.PKG_MESS_CFM_1
		create or replace package KFM.PKG_MESS_CFM_2
		create or replace package body KFM.PKG_MESS_CFM_2
		create or replace package KFM.PKG_MESS_CFM_2_1
		create or replace package body KFM.PKG_MESS_CFM_2_1
		create or replace package KFM.PKG_REPORTS
		create or replace package body KFM.PKG_REPORTS
		create or replace package KFM.PKG_IMPORT
		create or replace package body KFM.PKG_IMPORT
* Примечание: также необходимо вручную записать в таблицу MESSAGES_TEMPLATES измененные шаблоны формы ФМ-1
*/

/*
  ****** Инструкции для SQLPlus (обязательно) ******
  Для печати сообщений:
  DBMS_OUTPUT.put_line('<Message>');
*/
whenever sqlerror exit 1;
set serveroutput on;
set echo off;

declare
    filename      varchar2(256) := 'sfm.database-update.2013-00-01.ChangeCLetter.sql';
    purpose       varchar2(4000) := 'Замена русской буквы "с" на английскую "c" в полях oper_currency_code и oper_currency_amount таблиц mess_cfm_announce_oper и mess_cfm_exec';
    script_exists number := 0;

begin

    --delete from KFM.DB_Update_History where script_name = filename; commit;
    select count(*)
        into script_exists
        from KFM.DB_Update_History
     where script_name = filename;

    if (script_exists > 0) then
        RAISE_APPLICATION_ERROR(-20001,
                                                        '"' || filename || '" уже присутствует в базе');
    else
        insert into KFM.DB_Update_History
            (script_name, purpose)
        values
            (filename, purpose);
    end if;

    /*
  ****** Begin update script ******
  */
  
  /*
  ****** End update script ******
  */
    commit;

exception
    when others then
        rollback;
        raise;
end;
/

  alter table mess_cfm_announce_oper rename column "OPER_CURRENСY_CODE" to "OPER_CURRENCY_CODE";
  alter table mess_cfm_exec rename column "OPER_CURRENСY_CODE" to "OPER_CURRENCY_CODE";
  alter table mess_cfm_announce_oper rename column "OPER_CURRENСY_AMOUNT" to "OPER_CURRENCY_AMOUNT";
  alter table mess_cfm_exec rename column "OPER_CURRENСY_AMOUNT" to "OPER_CURRENCY_AMOUNT";
  alter table imp_messinfo rename column "OPER_CURRENСY_CODE" to "OPER_CURRENCY_CODE";
  alter table imp_messinfo rename column "OPER_CURRENСY_AMOUNT" to "OPER_CURRENCY_AMOUNT";

  CREATE OR REPLACE PACKAGE KFM."PKG_MESSAGES_CFM" as

  function RequestCounterLastDate(pLastDate out date) return number;
  /*
    Дата конца периода формирования последнего отчета
      Входные параметры:
      Выходные параметры:
        pLastDate         date, -- дата конца периода формирования последнего отчета
      Возврат
    0 - без ошибок
  */

  function RequestCounterReport(pBeginDate in date,
                                pEndDate   in date,
                                pMessId    out number) return number;
  /*
    Формирование запроса встречной отечтности
      Входные параметры:
       pBeginDate         date, -- начало отчетного периода
       pEndDate           date, -- конце отчетного периода
      Выходные параметры:
       pMessId            number -- идентификатор сфомированного сообщения
      Возврат
    0 - без ошибок
  */

  function GetTempMessNumb return number;
  function GenerateSendMessageNumber return number;
  function GetMessSignedData(pmessid   in number,
                             vsender   out varchar2,
                             vreceiver out varchar2) return number;
  /* Получить данные об отправителе и получателе документа
    Входные параметры:
       pmessid   - number       - идентификатор сообщения;
       vsender   - varchar2(30 char) - отправитель сообщения;
       vreceiver - varchar2(30 char) - получатель сообщения;

  */

  function Get_CheckXML(pMessID   in number,
                        pCheckXML out CLOB) return number;
  /*Формирование квитанции о принятии*/
  function Create_Ticket2NO(pMessID     in number,
                            pErrorCode  in number,
                            pAnswerText in varchar2,
                            pCheckXML   out CLOB) return number;
  /* Формирование квитанции о непринятии п роизвольным текстом */
  function Get_AutoErrorCheckXML(pMessID   in number,
                                 pCheckXML out CLOB) return number;
  /*Формирование квитанции о непринятии в случае нахождения ошибки базой данных*/

  function Save_Message(pMessXML            in CLOB,
                        pMessID             out number,
                        pCheckXML           out CLOB,
                        pError              in number := -1,
                        pValidationComplete in number := -1,
                        pValidationResult   in clob := null) return number;
  /*Сохранение сообщения обмена без подтверждения.
     Входные параметры:
             pMessXML - XML-текст сообшения
             pError - код/признак ошибки при проведении внешнего контроля
                   -1(default) - контроль не проводился
                    0 - нет ошибки
                    1 - ошибка контроля подписи
                    2 - Срок сертификата истек
                    3 - CRL сертификат является отозванным
                    4 - Ocsp сертификат является отозванным
                    5 - Ocsp статус сертификата не определен

             pValidationComplete - код/признак завершения проведения структурно-логического контроля
                   -1(default) - контроль не проводилося
                    0 - нет ошибки
                    1 - контроль завершился с ошибкой
             pValidationResult clob-  текст ошибки
     Выходные пераметры:
             pMessID - Идентификатор сообщения в БД
             pCheckXML - XML-текст ответного сообшения/подтверждения
  */
  function Update_Message(pMessID  in number,
                          pMessXML in CLOB) return number;
  /*Изменение сообщения.
     Входные параметры:
             pMessID - Идентификатор сообщения в БД
             pMessXML - XML-текст сообшения
  */

  function Get_Message(pMessID     in number,
                       pMessXML    out CLOB,
                       pIsEditable out number) return number;
  /*Получение XML-текста сообщения из БД
     Входные параметры:
             pMessID - Идентификатор сообщения в БД
     Выходные пераметры:
             pMessXML - XML-текст сообшения
             pIsEditable - признак разрешения редактирования
  */

  function Get_MessageShortData(pMessID    in number,
                                pResCursor out sys_refcursor) return number;
  /*Получение списка сообщений из БД
     Входные параметры:
             pMessID - ID сообщения
     Выходные пераметры:
             pResCursor - курсор структуры:
                 mess_cfm_id     (NUMBER), - Идентификатор сообщения в БД
                 receive_date    (DATE),   - Дата и время получения/сохранения сообщения
                 cfmcode         (NUMBER), - Код типа СФМ отправителя
                 IDTypeOperation (NUMBER), - тип операции
                 IDViewOperation (NUMBER), - тип реестра
                 OperationNumber (VARCHAR2),- номер операции
                 CurrencyCode    (NUMBER),  - код валюты
                 AmountCurrency  (NUMBER),  - сумма в валюте
                 AmountCurrencyTenge(NUMBER),  - сумма в эквиваленте
                 DocOperationName   (VARCHAR2),- наименование документа
                 DocOperationNumber (VARCHAR2),- дата и номер документа
                 messdate           (DATE),    - Дата формирования сообщения
                 status             (NUMBER),  - Статус
                 messversion        (VARCHAR2),- Версия сообщения
                 messdocid          (VARCHAR2) - Уникальный идентификатор документа
                 workstage          (NUMBER)   - текущая стадия обработки
                 messtype           (NUMBER),  - Тип сообщения
                 updateversion      (varchar2),- Номер версии обновления
                 daterelease        (date)     - Дата выпуска обновления
                 sender,            (varchar2) - Отправител ьсообщения
                 receiver           (varchar2) - Получатель сообщения
                 messnumber         varchar2(50 char) - Номер сообщения
                 messdoctype        number     - Вид сообщения
                 iseditable         number     - Можно ли редактирвоать сообщение
                 messreason   (NUMBER )        - Основание подачи
                 statusname   (varchar2(100 char))  - Наименование статуса сообщения
                 operstatus   NUMBER           - Статус операции
  */

  function Get_MessagesList(pResCursor out sys_refcursor,
                            pListID    in number := 1) return number;
  /*Получение списка сообщений из БД
   Входные параметры:
           pListID - Тип выборки
           1  Все сообщения
           2  Готовятся к передаче
           3  Отправляются
           4  Приняты КФМ
           5  Отвергнуты КФМ
           6  Исключены из обработки
           7  Необработанные запросы на доп инфо
           8  Обработанные запросы на доп инфо
           9  Ответы на запросы доп инфо

           17 - Информационные сообщения об обновлениях
           19 - Сообщения с обновлениями
           20 - Запросы на обновления

   Выходные пераметры:
           pResCursor - курсор структуры:
               mess_cfm_id  (NUMBER), - Идентификатор сообщения в БД
               receive_date (DATE),   - Дата и время получения/сохранения сообщения
               cfmcode      (NUMBER), - Код типа СФМ отправителя
               IDTypeOperation (NUMBER),     - тип операции
               IDViewOperation (NUMBER),     - тип реестра
               OperationNumber (VARCHAR2),   - номер операции
               CurrencyCode       (NUMBER),  - код валюты
               AmountCurrency     (NUMBER),  - сумма в валюте
               AmountCurrencyTenge(NUMBER),  - сумма в эквиваленте
               DocOperationName   (VARCHAR2),- наименование документа
               DocOperationNumber (VARCHAR2),- дата и номер документа
               messdate     (DATE),          - Дата формирования сообщения
               status       (NUMBER),        - Статус
               messversion  (VARCHAR2),      - Версия сообщения
               messdocid    (VARCHAR2)       - Уникальный идентификатор документа
               workstage    (NUMBER)         - текущая стадия обработки
               messtype     (NUMBER),        - Тип сообщения
               updateversion(VARCHAR2),      - Номер версии обновления
               daterelease  (DATE)           - Дата выпуска обновления
               sender       (VARCHAR2) ,     - Отправител ьсообщения
               receiver     (VARCHAR2)       - Получатель сообщения
               messnumber   (NUMBER)         - Номер сообщения
               messdoctype  (NUMBER)         - Вид сообщения
               messreason   (NUMBER )        - Основание подачи
               statusname   (varchar2(100 char))  - Наименование статуса сообщенияб
               operstatus   NUMBER           - Статус операции
  */

  function Get_MessagesListForPeriod(pListID           in number := 1,
                                     pReceiveDateBegin in date,
                                     pReceiveDateEnd   in date,
                                     pResCursor        out sys_refcursor) return number;
  /* Получить сообщения из БД за период
     Входные параметры:
             pListID - Тип выборки
               1  Все сообщения
               2  Готовятся к передаче
               3  Отправляются
               4  Приняты КФМ
               5  Отвергнуты КФМ
               6  Исключены из обработки
               7  Необработанные запросы на доп инфо
               8  Обработанные запросы на доп инфо
               9  Ответы на запросы доп инфо

               17 - Информационные сообщения об обновлениях
               19 - Сообщения с обновлениями
               20 - Запросы на обновления
             pReceiveDateBegin - дата с которой запрашиваются сообщения  включительно
             pReceiveDateEnd   - дата по которую запрашиваются сообщения включительно
     Выходные пераметры:
             pResCursor - курсор структуры:
                 mess_cfm_id  (NUMBER), - Идентификатор сообщения в БД
                 receive_date (DATE),   - Дата и время получения/сохранения сообщения
                 cfmcode      (NUMBER), - Код типа СФМ отправителя
                 IDTypeOperation (NUMBER),     - тип операции
                 IDViewOperation (NUMBER),     - тип реестра
                 OperationNumber (VARCHAR2),   - номер операции
                 CurrencyCode       (NUMBER),  - код валюты
                 AmountCurrency     (NUMBER),  - сумма в валюте
                 AmountCurrencyTenge(NUMBER),  - сумма в эквиваленте
                 DocOperationName   (VARCHAR2),- наименование документа
                 DocOperationNumber (VARCHAR2),- дата и номер документа
                 messdate     (DATE),          - Дата формирования сообщения
                 status       (NUMBER),        - Статус
                 messversion  (VARCHAR2),      - Версия сообщения
                 messdocid    (VARCHAR2)       - Уникальный идентификатор документа
                 workstage    (NUMBER)         - текущая стадия обработки
                 messtype     (NUMBER),        - Тип сообщения
                 updateversion(VARCHAR2),      - Номер версии обновления
                 daterelease  (DATE)           - Дата выпуска обновления
                 sender       (VARCHAR2) ,     - Отправител ьсообщения
                 receiver     (VARCHAR2)       - Получатель сообщения
                 messnumber   (NUMBER)         - Номер сообщения
                 messdoctype  (NUMBER)         - Вид сообщения
                 messreason   (NUMBER )        - Основание подачи
                 statusname   (varchar2(100 char))  - Наименование статуса сообщенияб
                 operstatus   NUMBER           - Статус операции
  */

  function Get_FilteredMessagesList(pListID                   in number := 1,
                                    pReceiveDateBegin         in date,
                                    pReceiveDateEnd           in date,
                                    pSendDateBegin            in date,
                                    pSendDateEnd              in date,
                                    pMessNumberBegin          in number,
                                    pMessNumberEnd            in number,
                                    pMessReason               in number,
                                    pMessOperationStatus      in number,
                                    pOperationNumber          in varchar2,
                                    pIDTypeOperation          in number,
                                    pIDViewOperation          in number,
                                    pCurrencycode             in number,
                                    pAmountcurrencyBegin      in number,
                                    pAmountcurrencyEnd        in number,
                                    pAmountcurrencytengeBegin in number,
                                    pAmountcurrencytengeEnd   in number,
                                    pResCursor                out sys_refcursor) return number;
  /* Получить список документов согласно выбранному фильтру
      pListID                   - Тип выборки
      pReceiveDateBegin  date   - Дата с которой выбираается параметр  - дата создания\получения документа
      pReceiveDateEnd    date   - Дата по которую выбираается параметр - дата создания\получения документа
      pSendDateBegin  date   - Дата с которой выбираается параметр  - дата отправки документа
      pSendDateEnd    date   - Дата по которую выбираается параметр - дата отправки документа
      pMessNumberBegin  number   - Число с которого выбираается параметр  - номер сообщения
      pMessNumberEnd    number   - Число по которое выбираается параметр  - номер сообщения
      pMessReason       number   - основание подачи сообщения
      pMessOperationStatus number - Статус операции
      pOperationNumber  varchar2  - номер операции
      pIDTypeOperation number    - тип операции
      pIDViewOperation number    - вид операции
      pCurrencycode    number    - код валюты совершения операции
      pAmountcurrencyBegin number - Число с которого выбирается параметр - сумма в валюте проведения операции
      pAmountcurrencyEnd  number - Число по которое выбирается параметр  - сумма в валюте проведения операции
      pAmountcurrencytengeBegin number - Число с которого выбирается параметр - сумма в тенге
      pAmountcurrencytengeEnd  number - Число по которое выбирается параметр - сумма в тенге
   Выходные параметры:
                  pResCursor - курсор структуры:
                 mess_cfm_id  (NUMBER), - Идентификатор сообщения в БД
                 receive_date (DATE),   - Дата и время получения/сохранения сообщения
                 cfmcode      (NUMBER), - Код типа СФМ отправителя
                 IDTypeOperation (NUMBER),     - тип операции
                 IDViewOperation (NUMBER),     - тип реестра
                 OperationNumber (VARCHAR2),   - номер операции
                 CurrencyCode       (NUMBER),  - код валюты
                 AmountCurrency     (NUMBER),  - сумма в валюте
                 AmountCurrencyTenge(NUMBER),  - сумма в эквиваленте
                 DocOperationName   (VARCHAR2),- наименование документа
                 DocOperationNumber (VARCHAR2),- дата и номер документа
                 messdate     (DATE),          - Дата формирования сообщения
                 status       (NUMBER),        - Статус
                 messversion  (VARCHAR2),      - Версия сообщения
                 messdocid    (VARCHAR2)       - Уникальный идентификатор документа
                 workstage    (NUMBER)         - текущая стадия обработки
                 messtype     (NUMBER),        - Тип сообщения
                 updateversion(VARCHAR2),      - Номер версии обновления
                 daterelease  (DATE)           - Дата выпуска обновления
                 sender       (VARCHAR2) ,     - Отправител ьсообщения
                 receiver     (VARCHAR2)       - Получатель сообщения
                 messnumber   (NUMBER)         - Номер сообщения
                 messdoctype  (NUMBER)         - Вид сообщения
                 messreason   (NUMBER )        - Основание подачи
                 statusname   (varchar2(100 char))  - Наименование статуса сообщенияб
                 operstatus   NUMBER           - Статус операции
  */

  function Get_FixedMessagesList(pReceiveDateBegin         in date,
                                 pReceiveDateEnd           in date,
                                 pSendDateBegin            in date,
                                 pSendDateEnd              in date,
                                 pMessNumberBegin          in number,
                                 pMessNumberEnd            in number,
                                 pMessReason               in number,
                                 pMessOperationStatus      in number,
                                 pOperationNumber          in varchar2,
                                 pIDTypeOperation          in number,
                                 pIDViewOperation          in number,
                                 pCurrencycode             in number,
                                 pAmountcurrencyBegin      in number,
                                 pAmountcurrencyEnd        in number,
                                 pAmountcurrencytengeBegin in number,
                                 pAmountcurrencytengeEnd   in number,
                                 pResCursor                out sys_refcursor) return number;
  /* Получить фиксированный список документов согласно выбранному фильтру без рабиения по группам

      pListID                   - Тип выборки
      pReceiveDateBegin  date   - Дата с которой выбираается параметр  - дата создания\получения документа
      pReceiveDateEnd    date   - Дата по которую выбираается параметр - дата создания\получения документа
      pSendDateBegin  date   - Дата с которой выбираается параметр  - дата отправки документа
      pSendDateEnd    date   - Дата по которую выбираается параметр - дата отправки документа
      pMessNumberBegin  number   - Число с которого выбираается параметр  - номер сообщения
      pMessNumberEnd    number   - Число по которое выбираается параметр  - номер сообщения
      pMessReason       number   - основание подачи сообщения
      pMessOperationStatus number - Статус операции
      pOperationNumber  varchar2  - номер операции
      pIDTypeOperation number    - тип операции
      pIDViewOperation number    - вид операции
      pCurrencycode    number    - код валюты совершения операции
      pAmountcurrencyBegin number - Число с которого выбирается параметр - сумма в валюте проведения операции
      pAmountcurrencyEnd  number - Число по которое выбирается параметр  - сумма в валюте проведения операции
      pAmountcurrencytengeBegin number - Число с которого выбирается параметр - сумма в тенге
      pAmountcurrencytengeEnd  number - Число по которое выбирается параметр - сумма в тенге
   Выходные параметры:
                   mess_cfm_id (NUMBER), - Идентификатор сообщения в БД
                   receive_date (DATE),  - Дата и время получения/сохранения сообщения
                   cfmcode (NUMBER),     - Код типа СФМ отправителя
                   IDTypeOperation (VARCHAR2),      - тип операции
                   IDViewOperation (VARCHAR2),      - тип реестра
                   OperationNumber (VARCHAR2),   - номер операции
                   CurrencyCode (VARCHAR2),         - код валюты
                   AmountCurrency (VARCHAR2),       - сумма в валюте
                   AmountCurrencyTenge (VARCHAR2),  - сумма в эквиваленте
                   DocOperationName (VARCHAR2),     - наименование документа
                   DocOperationNumber (VARCHAR2),   - дата и номер документа
                   messdate (DATE),      - Дата формирования сообщения
                   status (NUMBER),      - Статус
                   messversion (VARCHAR2),  - Версия сообщения
                   messdocid (VARCHAR2)     - Уникальный идентификатор документа
                   workstage (number)    - текущая стадия обработки
                   messtype (NUMBER),    - Тип сообщения
                   updateversion(varchar2),  - Номер версии обновления
                   daterelease(date)        -Дата выпуска обновления
                   sender,               -Отправител ьсообщения
                   receiver              -Получатель сообщения
                   messnumber varchar2(50 char) - Номер сообщения
                   messdoctype  number  - Вид сообщения
                   messreason   number  - Основание подачи
                   statusname   varchar2(100 char)  - Наименование статуса сообщения,
                   operstatus   NUMBER           - Статус операции
  */

  function Get_RelationMessagesList(pMessID    in number,
                                    pResCursor out sys_refcursor,
                                    pListID    in number := 1) return number;
  /*Получение списка связанных сообщений(квитанций) из БД
      Входные параметры:
              pMessID - ID сообщения-родителя
              pListID - Тип выборки
      Выходные пераметры:
              pResCursor - курсор структуры:
                  mess_cfm_id (NUMBER), - Идентификатор сообщения в БД
                  receive_date (DATE),  - Дата и время получения/сохранения сообщения
                  cfmcode (NUMBER),     - Код типа СФМ отправителя
                  messdate (DATE),      - Дата формирования сообщения
                  status (NUMBER),      - Статус
                  Version (VARCHAR2),  - Версия сообщения
                  DocumentUniqueIdentifier (VARCHAR2)     - Уникальный идентификатор документа
                  ErrorCode (VARCHAR2)  - Код ошибки в квитанции
                  ErrorName (VARCHAR2)  - Текст ошибки в квитанции
                  workstage (number)    - текущая стадия обработки
                  messtype (NUMBER),    - Тип сообщения
                  sender, (VARCHAR2)    - Отправител ьсообщения
                  receiver (VARCHAR2)   - Получатель сообщения

  */

  function Get_RelationMessagesTree(pMessID    in number,
                                    pResCursor out sys_refcursor,
                                    pListID    in number := 1) return number;
  /*
   Получить список связанных документов
   pmessid   - number       - идентификатор сообщения;
   pListID - Тип выборки
   Выход:  pResCursor - курсор структуры
           mess_cfm_id (NUMBER), - Идентификатор сообщения в БД
           receive_date (DATE),  - Дата и время получения/сохранения сообщения
           messdate (DATE),      - Дата формирования сообщения
           messtype (VARCHAR2),    - Тип сообщения
           parentmessid,         - Идентификатор родителя
           level                 - Уровень вложенности (начиная с 2)

  */

  function Get_MessagesTypesList(pRolesGroup in number,
                                 pResCursor  out sys_refcursor) return number;
  /*
   Получить список типов документов
   pRolesGroup  - number       - группа прав;
   Выход:  pResCursor - курсор структуры
           listnum (NUMBER)- номер группы,
           listname (VARCHAR2) - описание
  */

  function Get_MessagesTypesListForPeriod(pRolesGroup       in number,
                                          pReceiveDateBegin in date,
                                          pReceiveDateEnd   in date,
                                          pResCursor        out sys_refcursor) return number;
  /* Получить список сообщений с их количеством за период
  Выход:  pResCursor - курсор структуры
           listnum (NUMBER)- номер группы,
           listname (VARCHAR2) - описание */

  function Get_MessagesTypesListFiltered(pRolesGroup               in number,
                                         pReceiveDateBegin         in date,
                                         pReceiveDateEnd           in date,
                                         pSendDateBegin            in date,
                                         pSendDateEnd              in date,
                                         pMessNumberBegin          in number,
                                         pMessNumberEnd            in number,
                                         pMessReason               in number,
                                         pMessOperationStatus      in number,
                                         pOperationNumber          in varchar2,
                                         pIDTypeOperation          in number,
                                         pIDViewOperation          in number,
                                         pCurrencycode             in number,
                                         pAmountcurrencyBegin      in number,
                                         pAmountcurrencyEnd        in number,
                                         pAmountcurrencytengeBegin in number,
                                         pAmountcurrencytengeEnd   in number,
                                         pResCursor                out sys_refcursor) return number;
  /* Получить список сообщений с их количеством на основе фильтра
  Выход:  pResCursor - курсор структуры
          listnum (NUMBER)- номер группы,
          listname (VARCHAR2) - описание */

  function GetCountOfMessagesInGroup(plistid     in number,
                                     pRolesGroup in number,
                                     pModuleName in varchar2) return number;
  /* Подсчитывает количество сообщений в группе plistid (listnum)
     pRolesGroup - группа ролей, к которой относится данный пользователь
     pModuleName - имя модуля в котором работает пользователь
  */

  function GetCountOfMessagesInGroupP(plistid           in number,
                                      pRolesGroup       in number,
                                      pReceiveDateBegin in date,
                                      pReceiveDateEnd   in date,
                                      pModuleName       in varchar2) return number;
  /*Подсчитывает количество сообщений в группе plistid (listnum) за указанную дату*/

  function GetCountOfMessagesInGroupF(plistid                   in number,
                                      pRolesGroup               in number,
                                      pReceiveDateBegin         in date,
                                      pReceiveDateEnd           in date,
                                      pSendDateBegin            in date,
                                      pSendDateEnd              in date,
                                      pMessNumberBegin          in number,
                                      pMessNumberEnd            in number,
                                      pMessReason               in number,
                                      pMessOperationStatus      in number,
                                      pOperationNumber          in varchar2,
                                      pIDTypeOperation          in number,
                                      pIDViewOperation          in number,
                                      pCurrencycode             in number,
                                      pAmountcurrencyBegin      in number,
                                      pAmountcurrencyEnd        in number,
                                      pAmountcurrencytengeBegin in number,
                                      pAmountcurrencytengeEnd   in number,
                                      pModuleName               in varchar2) return number;
  /*Подсчитывает количество сообщений в группе plistid (listnum) удовлетворяющих фильтру*/

  function Get_MessagesTypesListSettings(pResCursor out sys_refcursor) return number;

  /* Получение настроечной таблицы для разбиения сообщений по модулям
      Выходные параметры
             pResCursor - курор структуры:
                        -- LISTNUM   NUMBER not null Номер группы
                        -- STATUSID  NUMBER not null ID статуса
                        -- STAGESID  NUMBER not null ID стадии
                        -- DOCTYPE   NUMBER not null ID типа докумеента

  */
  function Get_TransformedMessage(pMessID        in number,
                                  pTransformType in number,
                                  pMessOut       out CLOB) return number;
  /*Получение сообщения из БД
     Входные параметры:
             pMessID - Идентификатор сообщения в БД
             pTransformType - тип внешнего вида сообщения
                  0 - Внутренний документ
                  1  - Внешний документ
                  3  - HTML - просмотр
                  4 - Подписанный документ
     Выходные пераметры:
             pMessOut - текст сообшения
  */

  function Save_TransformedMessage(pMessID        in number,
                                   pTransformType in number,
                                   pMessIn        in CLOB,
                                   pExtErrorCode  in number := -1) return number;
  /*Сохранение преобразованного сообщения
     Входные параметры:
             pMessID - Идентификатор сообщения в БД
             pTransformType  - тип внешнего вида сообщения
                   0 - Внутренний документ
                  1  - Внешний документ
                  3  - HTML - просмотр
                  4 - Подписанный документ
             pMessIn - текст сообшения
             pExtErrorCode - код/признак ошибки при проведении внешнего контроля
                   -1(default) - контроль не проводился
                    0 - нет ошибки
                    1 - ошибка контроля подписи
  */

  function Transform_Message(pMessID        in number,
                             pTransformType in number,
                             pMessOut       out CLOB) return number;
  /*Преобразование сообщения
     Входные параметры:
             pMessID - Идентификатор сообщения в БД
             pTransformType  - тип преобразования
                0  Внутренний
                1  Преобразование внутреннего XML во внешний
                2  Преобразование внутреннего XML во внешний для экспорта в АИС
                3  Преобразование XML для просмотра в HTML
                4  Подписанный внешний
     Выходные пераметры:
             pMessOut - текст преобразованного сообшения
  */

  function ChangeStatus(pMessID     in number,
                        pWorkStage  in number,
                        pWorkStatus in number) return number;
  /*Изменение статуса документа
     Входные параметры:
             pMessID - Идентификатор сообщения в БД
             pWorkStage - Устанавливаемая стадия обработки документа
             pWorkStatus - устанавливаемый статус
               Для отправляемых документов pWorkStage, pWorkStatus принимают значения:
                                           30           1  Отправляется
                                           30           20  Ошибка отправки
                                           30           30  Отправка завершена (получена квитанция-1)
                                           30           10  Требуется доработка(квитанция-2 нет)
                                           30           40  Принят КФМ(квитанция-2 да)
  */

  function ToNextStage(pmessid number) return number;
  /* Перевести документ на следующую стадию обработки

    pmessid   - number       - идентификатор сообщения;
  */
  function ToPreviousStage(pmessid number) return number;
  /* Перевести документ на предыдущую стадию обработки

    pmessid   - number       - идентификатор сообщения;
  */

  function Exclude(pmessid number) return number;
  /* Исключить документ из обработки
  */

  /*function GetPermission(pmessid number, ptaskid in number, isavailable out number ) return number;*/
  /* Получить разрешение выполнять задание для сообщения

   pmessid   - number       - идентификатор сообщения;
   ptaskid   - number       - идентификатор задачи

   Выход: isavailable - 0 - нельзя выполнять задачу
                        1 - можно выполнить задачу

  */

  function Delete_Message(pmessid number) return number;
  /* Удалить документ из рабочих таблиц СФМ
  */

  function Get_MessagesIDByParentID(pParentID in number,
                                    pMessID   out number, /*sCur   out sys_refcursor*/
                                    pMessType in number := 4) return number;
  /*Получение связанного сообщения по ID родителя
     Входные параметры:
             pParentID - Идентификатор сообщения в БД
             pMessType - тип получаемого сообшения
     Выходные пераметры:
             pMessIDsCur - курсор структуры : messid - number
  */

  function Get_MessagesListByParentID(pParentID    in number,
                                      pMessagesCur out sys_refcursor,
                                      pMessType    in number := 4) return number;
  /*
     Входные параметры:
             pParentID - Идентификатор сообщения в БД
             pMessType - тип получаемого сообшения
     Выходные пераметры:
             pResCursor - курсор структуры:
                 mess_cfm_id (NUMBER), - Идентификатор сообщения в БД
                 receive_date (DATE),  - Дата и время получения/сохранения сообщения
                 cfmcode (NUMBER),     - Код типа СФМ отправителя
                 IDTypeOperation (VARCHAR2),      - тип операции
                 IDViewOperation (VARCHAR2),      - тип реестра
                 OperationNumber (VARCHAR2),   - номер операции
                 CurrencyCode (VARCHAR2),         - код валюты
                 AmountCurrency (VARCHAR2),       - сумма в валюте
                 AmountCurrencyTenge (VARCHAR2),  - сумма в эквиваленте
                 DocOperationName (VARCHAR2),     - наименование документа
                 DocOperationNumber (VARCHAR2),   - дата и номер документа
                 messdate (DATE),      - Дата формирования сообщения
                 status (NUMBER),      - Статус
                 messversion (VARCHAR2),  - Версия сообщения
                 messdocid (VARCHAR2)     - Уникальный идентификатор документа
                 workstage (number)    - текущая стадия обработки
                 messtype (NUMBER),    - Тип сообщения
                 updateversion(varchar2),  - Номер версии обновления
                 daterelease(date)        -Дата выпуска обновления
                 sender,               -Отправител ьсообщения
                 receiver              -Получатель сообщения
                  messnumber varchar2(50 char) - Номер сообщения
                 messdoctype  number  - Вид сообщения
                 messreason   number  - Основание подачи
                 statusname   varchar2(100 char)  - Наименование статуса сообщения,
                 operstatus   NUMBER           - Статус операции
  */

  function Get_ParentIDByMessagesID(pMessID   in number,
                                    pParentID out number) return number;
  /*Получение ID родителя по ID сообщения
     Входные параметры:
             pMessID - Идентификатор сообщения в БД
     Выходные пераметры:
             pParentID - ID запроса
  */

  function GetFirstNodeID(pmessid     number,
                          firstnodeid out number) return number;
  /* Получить ID  самого раннего предка
  */

  function GetInternalDocument(pMessID  in number,
                               pMessOut out CLOB) return number;
  /*Получить документ в формате xml*/

  function GenerateMessageNumber return number;
  /*
   Получить следующий номер сообщения
       Возвращает - номер сообщения
  */

  function IsLabelEditable(pmessid     in number,
                           labelCheck  out number,
                           labelRenew  out number,
                           labelDelete out number) return number;
  /* Входной параметр - ID сообщения nbgf 1(Информационное сообщение)
     Выход:
       labelCheck out number, --показатель активности кнопки проверить (0-нет, 1 -да)
       labelRenew out number,--показатель активности кнопки заменить (0-нет, 1 -да)
       labelDelete out number--показатель активности кнопки удалить (0-нет, 1 -да)

  */
  function GetSendPermission(pmessid number) return number;
  /*Проверка , можно ли отправить документ*/

  function GetEditableField(pmessid number) return number;
  /*Проверка , можно ли редкактировать документ*/

  function GetMessageType(pmessid in number) return number;
  /* Получить тип документа */

  function GetMessOperNumber(pmessid in number) return varchar2;
  /* Получить номер опрации предшествующего документа */

  function GetMessNumber(pmessid in number) return number;
  /* Получить номер предшествующего документа */

  function GetCFMCodeNumber(pmessid in number) return number;
  /* Получить код СФМ предшествующего документа */

  function GetCFMName(pmessid in number) return varchar2;
  function GetMessReason(messreason   in number,
                         suspicreason in number,
                         messversion  varchar2) return number;
  /* Получить основание подачи сообщения в зависимости от версии документа   */

  function GetStatusDescription(pstatus in number,
                                pstage  in number,
                                ptype   in number) return nvarchar2;
  /*Получить описание статуса документа */

  function GetStatusDescriptionRus(pstatus in number,
                                   pstage  in number,
                                   ptype   in number) return varchar2;
  /*Получить описание статуса документа на русском*/

  function GetStatusDescriptionKz(pstatus in number,
                                  pstage  in number,
                                  ptype   in number) return nvarchar2;
  /*Получить описание статуса документа на казахском*/

  function GetcountofFounders(pmessid   number,
                              pmemberid number) return number;
  /*Получить количество учредителей участника*/

  procedure InsertEnchanceData(pmessid number);
  /*Вставить продублированнные данные о сообщении */

  procedure UpdateEnchanceData(pmessid number);
  /*Обновить продублированнные данные о сообщении */

  procedure UpdateEnchanceStatusName(pmessid number);
  /*Обновить продублированнные данные о статусе сообщения */

  function GetOuterAnnounceXML_1(PXMLSCH xmltype) return xmltype;
  /* Преобраззовать хмл к разбираемому виду */

  function GetOuterRegistrationData_1(PXMLSCH xmltype) return xmltype;
  /* Преобраззовать хмл к разбираемому виду */
  --------------------------------------------------------------------------------
  --
  procedure Copy_Info(pMessID in number);
  --создает новый пустой докумнет и заполняет его константами
  function Prepare_Save(pMessID out number) return number;
  --отменяет создание нового документа удаляя документ
  function Cancel_Save(pMessID in number) return number;
  --подготавливает редактирование нового документа, заполняя необходимые контснаты
  function Prepare_Update(pMessID in number) return number;
  --сохраняет отредактированные данные
  function Update_Message(pMessID in number) return number;
  --
  function checkRNN(widget_value in VARCHAR2) return number;
  --
  function checkBIC(widget_value in VARCHAR2) return number;
  --
  function checkINN(widget_value in VARCHAR2) return number;
  --
  function CHECKREGION(widget_value in VARCHAR2) return number;
  --
  function CHECKCITY(widget_value in VARCHAR2) return number;
  --
  function check_user_ol(widget_value in VARCHAR2) return number;
  --
end PKG_MESSAGES_CFM;
/

CREATE OR REPLACE PACKAGE BODY KFM."PKG_MESSAGES_CFM" as

  function Create_XML(pMessID in number,
                      pXML    out xmltype) return number is
    Result     number;
    vXMLString CLOB;
  begin
    Result := 0;

    select mc_xml.mess_xml
    into vXMLString
    from mess_cfm_xml mc_xml
    where mc_xml.mess_cfm_id = pMessID;

    Result := PKG_MESSAGES_XML.Create_XMLFromClob(vXMLString, pXML);

    Return(Result); ---300

  EXCEPTION
    when no_data_found then
      result := -1000;
      Return(Result);
    WHEN OTHERS THEN
      Result := -305; --Неверный XML документ
      Return(Result);
  end;

  function Get_FieldAsVarchar(pMessID    in number,
                              pFieldName in varchar2) return varchar2 is
    Result varchar2(5000);
    pXML   xmltype;
    Res    number;
  begin
    Result := NULL;

    Res := Create_XML(pMessID, pXML);
    if Res <> 0 then
      return Res;
    end if;
    Res := PKG_MESSAGES_XML.Get_FieldFromXML(pXML, pFieldName, Result);
    if Res <> 0 then
      null;
    end if;
    Return(Result);

  EXCEPTION
    WHEN OTHERS THEN
      Result := null;
      Return(Result);
  end;

  function Get_FieldAsNumber(pMessID    in number,
                             pFieldName in varchar2) return number is
    Result         number;
    pFieldValueStr varchar2(50 char);
  begin
    Result := 0;

    pFieldValueStr := Get_FieldAsVarchar(pMessID, pFieldName);

    Result := to_number(pFieldValueStr);

    Return(Result);

  EXCEPTION
    WHEN OTHERS THEN
      Result := NULL;
      Return(Result);
  end;

  function Get_FieldAsDate(pMessID    in number,
                           pFieldName in varchar2) return date is
    Result         date;
    pFieldValueStr varchar2(50 char);
  begin
    Result := null;

    pFieldValueStr := Get_FieldAsVarchar(pMessID, pFieldName);

    Result := to_date(pFieldValueStr, 'YYYY-MM-DD');

    Return(Result);

  EXCEPTION
    WHEN OTHERS THEN
      Result := NULL;
      Return(Result);
  end;

  function RequestCounterLastDate(pLastDate out date) return number as
  begin
    return pkg_rqst_cntr_cfm.RequestCounterLastDate(pLastDate);
  end;

  function RequestCounterReport(pBeginDate in date,
                                pEndDate   in date,
                                pMessID    out number) return number as
    v_result number default 0;
  begin
    return pkg_rqst_cntr_cfm.RequestCounterReport(pBeginDate, pEndDate, pMessID);
  end;

  function GetTempMessNumb return number is
    tempval number;
  begin
    select messnumb_temp.nextval
    into tempval
    from dual;
    return to_number(to_char(sysdate, 'mmdd') || lpad(to_char(tempval), 5, '0'));
  end;

  function GetMessSignedData(pMessID   in number,
                             vsender   out varchar2,
                             vreceiver out varchar2) return number is
    result number default 0;
  begin
    select sender,
           receiver
    into vsender,
         vreceiver
    from mess_cfm
    where mess_cfm_id = pMessID;
    return result;

  exception
    when no_data_found then
      return - 315;
  end;

  procedure UpdateMessNumber(pMessID number,
                             pMessIn clob) is
    pNumber number;
  begin
    select extractvalue(xmltype(pMessIn), '/ExportData/SignedData/FormNumber/text()')
    into pNumber
    from dual;
    --Исправлено 05.01.2012
    if pNumber is not null then
      update mess_cfm_xml
      set mess_xml = updatexml(xmltype(mess_xml),'/Root/MessageInformation/MessageNumber/text()', pNumber).getclobval()
      where mess_cfm_id = pMessID;

      update mess_cfm_announce_info
      set mess_number = pNumber
      where mess_cfm_id = pMessID;

      update mess_cfm_exec
      set mess_number = pNumber
      where mess_cfm_id = pMessID;
    end if;
  end;

  --наоборот, при отправке
  function GetSenderFromParent(pparentid in number,
                               vSender   out varchar2,
                               vReceiver out varchar2) return number is
    result number default 0;
  begin
    if (pparentid = 0 or pparentid is null) then
      return result;
    else
      select Receiver,
             Sender
      into vSender,
           vReceiver
      from mess_cfm
      where mess_cfm_id = pparentid;
    end if;
    return result;
  exception
    when no_data_found then
      return result;
  end;

  function GetSenderFromMessage(pMessID   in number,
                                vSender   out varchar2,
                                vReceiver out varchar2,
                                vDate     out date) return number is
    result number default 0;
  begin
    if (pMessID = 0 or pMessID is null) then
      return result;
    else
      select Sender,
             Receiver,
             send_date
      into vSender,
           vReceiver,
           vdate
      from mess_cfm
      where mess_cfm_id = pMessID;
    end if;
    return result;
  exception
    when no_data_found then
      return result;
  end;

  function Get_CheckXML(pMessID   in number,
                        pCheckXML out CLOB) return number is
    Result number default 0;
    vDocID varchar2(50 char);
    vcount number default 0;
  begin
    --проверить тип, можно ли по нему отправлять квитанцию?
    select count(*)
    into vcount
    from mess_cfm
    where mess_cfm_id = pMessID;
    if vcount = 0 then
      return - 1000;
    end if;
    vDocID := get_fieldasvarchar(pMessID, 'DocumentUniqueIdentifier');

    pCheckXML := '<?xml version="1.0" encoding="UTF-16"?>
               <Check>
                   <Version>5A151B65-0842-4FAA-99BA-F51364F8DDA6</Version>
                   <DocumentUniqueIdentifier>' || sys_guid() || '</DocumentUniqueIdentifier>
                   <OriginalDocumentGuid>' || vDocID || '</OriginalDocumentGuid>
                   <ErrorCode>0</ErrorCode>
                   <ErrorName>Без ошибок</ErrorName>
               </Check>';
    Return(Result);
    --было 4 +R1
  exception
    when NO_DATA_FOUND then
      Return(-1000);
    when others then
      return - 1007; --Ошибка формирования квитанции
  end;

  function Create_Ticket2NO(pMessID     in number,
                            pErrorCode  in number,
                            pAnswerText in varchar2,
                            pCheckXML   out CLOB) return number is
    Result           number;
    vDocID           varchar2(50 char);
    pstatus          number;
    vcount           number;
    ErrorDescription varchar2(3000 char);
    vErrorCode       varchar2(3000 char);

  begin
    vErrorCode := pErrorCode;
    Result     := 0;
    select count(*)
    into vcount
    from mess_cfm
    where mess_cfm_id = pMessID;
    if vcount = 0 then
      return - 1000;
    end if;
    vDocID := get_fieldasvarchar(pMessID, 'DocumentUniqueIdentifier');

    pkg_main.GetError(pErrorCode, vErrorCode, ErrorDescription, pstatus);

    select '<Root>
            <Version>F5982B4F-932C-44EA-BB61-78B0C3218DF3</Version>
            <DocumentUniqueIdentifier>' || sys_guid() || '</DocumentUniqueIdentifier>
            <OriginalDocumentGuid>' || vDocID || '</OriginalDocumentGuid>
            <ErrorCode>' || pErrorCode || '</ErrorCode>
            <ErrorName>' || pAnswerText || ErrorDescription || '</ErrorName>
          </Root>'
    into pCheckXML
    from mess_cfm mc
    where mc.mess_cfm_id = pMessID;

    Return(Result);

  exception
    when NO_DATA_FOUND then
      Return(-1000);
    when others then
      return - 1007; --Ошибка формирования квитанции
  end;

  function Get_AutoErrorCheckXML(pMessID   in number,
                                 pCheckXML out CLOB) return number is
    Result           number default 0;
    vDocID           varchar2(50 char);
    vcount           number default 0;
    errorname        varchar2(4000 char);
    errordescription varchar2(4000 char);
    pstatus          number default 0;
  begin

    --проверить тип, можно ли по нему отправлять квитанцию?
    select count(*)
    into vcount
    from mess_cfm
    where mess_cfm_id = pMessID;
    if vcount = 0 then
      return - 1000;
    end if;

    vDocID := get_fieldasvarchar(pMessID, 'DocumentUniqueIdentifier');

    select int_err_code
    into vcount
    from mess_cfm
    where mess_cfm_id = pMessID;
    pkg_main.GetError(vcount, ErrorName, ErrorDescription, pstatus);

    pCheckXML := '<?xml version="1.0" encoding="UTF-16"?>
               <Check>
                   <Version>F5982B4F-932C-44EA-BB61-78B0C3218DF3</Version>
                   <DocumentUniqueIdentifier>' || sys_guid() || '</DocumentUniqueIdentifier>
                   <OriginalDocumentGuid>' || vDocID || '</OriginalDocumentGuid>
                   <ErrorCode>' || vcount || '</ErrorCode>
                   <ErrorName>' || ErrorName || '</ErrorName>
               </Check>';

    Return(Result);
    --было 4 +R1
  exception
    when NO_DATA_FOUND then
      Return(-1000);
    when others then
      return - 1007; --Ошибка формирования квитанции
  end;

  function Save_Message(pMessXML            in CLOB,
                        pMessID             out number,
                        pCheckXML           out CLOB,
                        pError              in number := -1,
                        pValidationComplete in number := -1,
                        pValidationResult   in clob := null) return number is
    result          number default 0;
    vCount          number default 0;
    vRes            number default 0; -- Временный результат промежуточных проверок
    vMess_cfm       mess_cfm%rowtype; -- Строка ключевой информации
    vMessId         number; -- ID связанного сообщения
    vMessageVersion varchar2(50 char); -- Версия сообщения (из XML)
    vMessageGuid    varchar2(50 char); -- Guid сообщения (из XML)
    vCFMMessageDoc  varchar2(50 char); -- Версия оригинального сообщения (из XML)
    vXML            xmltype;
    vRootNode       clob; -- Сообщение без пакета
    vSignature      clob; -- ЭЦП
    vExistCover     number; -- Флаг наличия конверта
    pVersionId      number; -- ID версии сообщения
  begin
    --ЭЦП

    result := pkg_mess_cfm_1.ExtractSignatureData(pMessXML, vSignature);
    if Result <> 0 then
      return Result;
    end if;

    --Данные отправителя и получателя
    result := pkg_mess_cfm_1.ExtractMessInSignedData(pMessXML, vExistCover, vMess_cfm.Sender, vMess_cfm.Receiver, vMess_cfm.Send_Date);
    if Result <> 0 then
      return Result;
    end if;

    --Распаковка из конверта
    result := pkg_messages_xml.Get_RootNodeFromXML(pMessXML, vRootNode);
    if result <> 0 then
      return result; -- -305 или -307 (not valid или узел не найден)
    end if;

    vXML := XMLTYPE.createxml(vRootNode); --Главная ветка

    --Преобразование, проверка и сохранение версии документа
    Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'Version', vMessageVersion);
    if Result <> 0 then
      return Result;
    end if;
    vres := pkg_common.GetFormattedGuid(vMessageVersion, vMess_cfm.Mess_Version);
    if vres <> 0 then
      return - 1301; -- Неверный формат идентификационного номера версии документа
    else
      begin
        select mv.mess_type,
               versionid
        into vMess_cfm.Mess_Type,
             pVersionId --Тип сообщения
        from messages_versions mv
        where mv.versioncode = vMess_cfm.Mess_Version;
      exception
        when others then
          return - 306; --Неверная версия сообщения. Сообщение не сохранено.
          vMess_cfm.Mess_Type := -1;
      end;
    end if;

    --Преобразование, проверка и сохранение GUID документа
    Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'DocumentUniqueIdentifier', vMess_cfm.Mess_Docid);
    if Result <> 0 then
      return Result;
    end if;
    vres := pkg_common.GetFormattedGuid(vMess_cfm.Mess_Docid, vMess_cfm.Mess_Form_Guid);
    if vres <> 0 then
      return - 1302; --  Неверный формат идентификационного номера документа
    else
      select count(*)
      into vcount
      from mess_cfm
      where Mess_Form_Guid = vMess_cfm.Mess_Form_Guid;
      if vcount > 0 then
        return - 1003; --Сообщение с данным уникальным идентификатором  уже находится в базе
      end if;
    end if;
    --Преобразование, проверка и сохранение GUID оригинального документа
    if vMess_cfm.Mess_Type in (2, 3, 4, 5, 12, 13, 14) then
      Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'OriginalDocumentGuid', vCFMMessageDoc);
      vres   := pkg_common.GetFormattedGuid(vCFMMessageDoc, vMessageGuid);
      if vres <> 0 then
        return - 1303; --  Неверный формат идентификационного номера документа
      else
        begin
          select mc.mess_cfm_id
          into vMess_cfm.Mess_Parentid --Идентификатор родительской записи
          from mess_cfm mc
          where mc.Mess_Form_Guid = vMessageGuid
          and rownum = 1; --Проверить когда такое возможно!
        exception
          when others then
            if vMess_cfm.Mess_Type <> 4 then
              return - 1008; --Не найдено изначальное сообщение, по которому пришло новое сообщение
            else
              vMess_cfm.Mess_Parentid := -1;
              result                  := -1009; --Сообщение сохранено
            end if;
        end;
      end if;
    end if;
    -- назначить отправителя и получателя в случае отправки сформированных откументов
    if vExistCover = 0 then
      result := GetSenderFromParent(vMess_cfm.Mess_Parentid, vMess_cfm.Sender, vMess_cfm.Receiver);
    end if;
    --
    --Сохранение в основной таблице
    vMess_cfm.Status       := 1;
    vMess_cfm.Stage        := 1;
    vMess_cfm.Receive_Date := sysdate;
    vMess_cfm.Ext_Err_Code := pError;
    insert into mess_cfm
    values vMess_cfm
    returning mess_cfm_id into pMessID;
    insert into mess_cfm_xml
      (mess_cfm_id,
       mess_xml,
       mess_sign)
    values
      (pMessID,
       vRootNode,
       vSignature);
    --  commit;

    --   result:=ChangeStatus(pMessID,1,1);

    case vMess_cfm.Mess_Type
      when 1 then
        result := ChangeStatus(pMessID, 1, 1);
        if pversionid = 1 then
          result := pkg_mess_cfm_1.parseAnnounceXML(pMessID);
        else
          result := pkg_mess_cfm_2.parseAnnounceXML(pMessID, pversionid);
        end if;
        if result <> 0 then
          InsertEnchanceData(pMessID);
          return result;
        end if;
      when 2 then
        -- result:=ChangeStatus(pMessID,1,1);
        result := pkg_mess_cfm_1.parseCheckXML(pMessID);
        if result <> 0 then
          InsertEnchanceData(pMessID);
          return result;
        end if;
        vMessid := vMess_cfm.Mess_Parentid;
        if vmessid <> -1 then
          -- if vCFMMessageDocID is not null and vCFMMessageDocID <>-1 then
          -- result:= Get_ParentIDByMessagesID(pMessID,vMessId);
          if GetMessageType(vMessId) in (1, 5) then
            result := ChangeStatus(pMessID, 50, 1);
            vcount := 0;
            select count(*)
            into vcount
            from mess_cfm
            where mess_parentid = vMessId
            and mess_type = 3;

            if vcount = 0 then
              --Не было отвергнуто ранее (в случае нерпавильного порядка загрузки сообщений от транспорта)
              result := ChangeStatus(vMessId, 40, 40);
            end if;
          elsif GetMessageType(vMessId) = 4 then
            result := ChangeStatus(pMessID, 1, 1); --Cформирована
            --     result:=ChangeStatus(vMessId,50,1); --не обработано
          else
            result := ChangeStatus(pMessID, 1, 1);
          end if;
        else
          rollback;
          result := -2111; --Пришла квитанция о принятии неизвестного базе документа. Не сохранена.
        end if;

      when 3 then
        result := pkg_mess_cfm_1.parseCheckXML(pMessID);
        if result <> 0 then
          InsertEnchanceData(pMessID);
          return result; --откат??
        end if;
        vMessid := vMess_cfm.Mess_Parentid;
        if vmessid <> -1 then
          if GetMessageType(vMessId) in (1, 5) then
            result := ChangeStatus(pMessID, 50, 1); --Получена
            if result <> 0 then
              null;
            end if;
            result := ChangeStatus(vMessId, 40, 50); --Пришла квитанция с отказом
          elsif GetMessageType(vMessId) = 4 then
            result := ChangeStatus(pMessID, 1, 1); --Cформирована
          else
            result := ChangeStatus(pMessID, 1, 1);
            -- elsif  GetMessageType(vMessId)=5 then
            --  result:=ChangeStatus(vMessId,30,20); --Ошибка отправки ответа
          end if;
        else
          rollback;
          result := -2112; --Пришла квитанция о непринятии неизвестного базе документа. Не сохранена.*/ --------?????????????
        end if;
      when 4 then
        --result:=ChangeStatus(pMessID,1,1);
        result := pkg_mess_cfm_1.parseDopInfXML(pMessID);
        if result <> 0 then
          vres := Get_AutoErrorCheckXML(pMessID, pCheckXML);
          if vres <> 0 then
            null;
          end if;
          InsertEnchanceData(pMessID);
          return result;
        end if;
        result := ChangeStatus(pMessID, 50, 1);

      when 5 then
        result := ChangeStatus(pMessID, 1, 1);
        if result <> 0 then
          null;
        end if;
        result := pkg_mess_cfm_1.parseDopInfAnswXML(pMessID);
        if result <> 0 then
          InsertEnchanceData(pMessID);
          return result;
        end if;
        vMessid := vMess_cfm.Mess_Parentid;
        if vmessid <> -1 then
          result := ChangeStatus(vMessId, 60, 1); --Отправляется ответ или 60,30????
        end if;

      when 8 then
        --result:=parseupdaterequestxml(pMessID);
        result := ChangeStatus(pMessID, 1, 1);
        if result <> 0 then
          null;
        end if;
        result := pkg_mess_cfm_1.ParseUpdateInfoXML(pMessID);
        if result <> 0 then
          vres := Get_AutoErrorCheckXML(pMessID, pCheckXML);
          if vres <> 0 then
            null;
          end if;
          InsertEnchanceData(pMessID);
          return result;
        end if;
        --   result:=SaveXMLtoDB(vRootNode,vMessageType,vMessageVersion, vMessageDocID,vCFMMessageDoc,pError,vSender, vReceiver, pMessID,pMessDocDate);
        null;
      when 9 then
        --    InsertEnchanceData(pMessID);
        result := ChangeStatus(pMessID, 1, 1);
        if result <> 0 then
          null;
        end if;
        result := pkg_mess_cfm_1.parseupdaterequestxml(pMessID);
        null;
      when 10 then
        result := ChangeStatus(pMessID, 1, 1);
        if result <> 0 then
          null;
        end if;
        --result:=parseupdaterequestxml(pMessID);
        result := pkg_mess_cfm_1.parseupdatexml(pMessID);
        if result <> 0 then
          vres := Get_AutoErrorCheckXML(pMessID, pCheckXML);
          if vres <> 0 then
            null;
          end if;
          InsertEnchanceData(pMessID);
          return result;
        end if;
      when 11 then
        result := ChangeStatus(pMessID, 20, 1);
      when 12 then
        vMessid := vMess_cfm.Mess_Parentid;
        result  := ChangeStatus(vMessId, 30, 40);
      when 13 then
        vMessid := vMess_cfm.Mess_Parentid;
        result  := ChangeStatus(vMessId, 40, 50);
      when 14 then
        vMessid := vMess_cfm.Mess_Parentid;
        result  := ChangeStatus(vMessId, 40, 40);
        result  := pkg_passport_cfm.UpdatePassportData(vRootNode);
        -- result:=SaveXMLtoDB(vRootNode,vMessageType,vMessageVersion, vMessageDocID,vCFMMessageDoc,pError,vSender, vReceiver, pMessID,pMessDocDate);
      when 15 then
        result := ChangeStatus(pMessID, 20, 1);
        result := pkg_counter_report_cfm.FillCounterReportExec(pMessID, vRootNode);
        return result;
      else
        result := -1005; --Невозможно утсановить тип документа.Документ не сохранен.  ---изменить!!!!!!

    end case;

    case pError
      when 2 then
        result := Create_Ticket2NO(pMessID, -350, 'Ошибка ЭЦП документа. ', pCheckXML);
      when 3 then
        result := Create_Ticket2NO(pMessID, -351, 'Ошибка ЭЦП документа. ', pCheckXML);
      when 4 then
        result := Create_Ticket2NO(pMessID, -352, 'Ошибка ЭЦП документа. ', pCheckXML);
      when 5 then
        result := Create_Ticket2NO(pMessID, -353, 'Ошибка ЭЦП документа. ', pCheckXML);
      else

        --Квитанции
        if vMess_cfm.Mess_Type in (4, 8, 10) then
          Result := Get_CheckXML(pMessID, pCheckXML);
          if (result = -1000) then
            return - 1003;
          end if;
        end if;
        null;
    end case;
    InsertEnchanceData(pMessID);
    pkg_audits.WriteUserAudit(8, 'pkg_messages_cfm.SaveMessage', 'ID: ' || pMessID);
    Return(Result);
  exception
    when others then
      pMessID := null;
      pkg_exceptions.AddException(sqlcode, sqlerrm, 'Save_Message');
      return - 2100; --Ошибка операции сохранения
  end;

  function Update_Message(pMessID  in number,
                          pMessXML in CLOB) return number is
    Result          number default 0;
    vcount          number default 0;
    vRes            number default 0; -- Временный результат промежуточных проверок
    vMess_cfm       mess_cfm%rowtype; -- Строка ключевой информации
    vMessageVersion varchar2(50 char); -- Версия сообщения (из XML)
    vCFMMessageDoc  varchar2(50 char); -- Версия оригинального сообщения (из XML)
    vMessageGuid    varchar2(50 char); -- Guid сообщения (из XML)
    vMessGuid       varchar2(50 char); -- Guid сообщения (из БД)
    vXML            xmltype;
    vRootNode       clob; -- Сообщение без пакета
    vStage          number; -- Стадия обработки сообщения
    vStatus         number; -- Статус сообщения
    vMessType       number; -- Тип сообщения
    pversionid      number; -- ID версии сообщения

  begin
    Result := 0;

    select count(*)
    into vcount
    from mess_cfm
    where mess_cfm_id = pMessID;
    if vcount = 0 then
      return - 1000; --Сообщение не найдено
    end if;

    select mc.mess_type,
           mc.status,
           mc.stage,
           mc.mess_form_guid
    into vMessType,
         vStatus,
         vStage,
         vMessGuid
    from mess_cfm mc
    where mess_cfm_id = pMessID;

    if (vStage >= 30) then
      return - 531;
    end if;

    --Распаковка из конверта
    result := pkg_messages_xml.Get_RootNodeFromXML(pMessXML, vRootNode);
    if result <> 0 then
      return result; -- -305 или -307 (not valid или узел не найден)
    end if;

    vXML := xmltype.createxml(vRootNode);

    --Преобразование, проверка и сохранение версии документа
    Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'Version', vMessageVersion);
    if Result <> 0 then
      return Result;
    end if;
    vres := pkg_common.GetFormattedGuid(vMessageVersion, vMess_cfm.Mess_Version);
    if vres <> 0 then
      return - 1301; -- Неверный формат идентификационного номера версии документа
    else
      begin
        select mv.mess_type,
               versionid
        into vMess_cfm.Mess_Type,
             pVersionId --Тип сообщения
        from messages_versions mv
        where mv.versioncode = vMess_cfm.Mess_Version;
      exception
        when others then
          return - 306; --Неверная версия сообщения. Сообщение не сохранено.
          vMess_cfm.Mess_Type := -1;
      end;
    end if;

    --Преобразование, проверка и сохранение GUID документа
    Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'DocumentUniqueIdentifier', vMess_cfm.Mess_Docid);
    if Result <> 0 then
      return Result;
    end if;
    vres := pkg_common.GetFormattedGuid(vMess_cfm.Mess_Docid, vMess_cfm.Mess_Form_Guid);
    if vres <> 0 then
      return - 1302; --  Неверный формат идентификационного номера документа
    else
      ---!!!!!!!!!!!!!!!!!!Если будет доп столбец, то проверять его!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

      if vMess_cfm.Mess_Form_Guid <> vMessGuid then
        return - 1011;
        --!!!!!!!!Оставить вторую ветку, если будет дополнительное поле
      end if;
    end if;

    if vMess_cfm.Mess_Type in (2, 3, 4, 5) then
      --убрать типы
      Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'OriginalDocumentGuid', vCFMMessageDoc);
      vres   := pkg_common.GetFormattedGuid(vCFMMessageDoc, vMessageGuid);
      if vres <> 0 then
        return - 1303; --  Неверный формат идентификационного номера документа
      else
        begin
          select mc.mess_cfm_id
          into vMess_cfm.Mess_Parentid
          from mess_cfm mc
          where mc.Mess_Form_Guid = vMessageGuid
          and rownum = 1;
        exception
          when others then
            if vMess_cfm.Mess_Type <> 4 then
              return - 1008; --Не найдено изначальное сообщение, по которому пришло новое сообщение
            else
              vMess_cfm.Mess_Parentid := -1;
              return - 1009; --Сообщение сохранено(!!!нет)
            end if;
        end;
      end if;
    end if;

    update mess_cfm_xml
    set mess_xml = vRootNode
    where mess_cfm_id = pMessID;
    commit;
    case vMess_cfm.Mess_Type
      when 1 then
        delete from mess_cfm_announce_info
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_cont
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_found
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_memb
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_oper
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_subj
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_accounts
        where mess_cfm_id = pMessID;
        if pversionid = 1 then
          result := pkg_mess_cfm_1.parseAnnounceXML(pMessID);
        else
          result := pkg_mess_cfm_2.parseAnnounceXML(pMessID, pversionid);
        end if;
        if result <> 0 then
          UpdateEnchanceData(pMessID);
          return result;
        end if;

        null;
      when 2 then
        delete from mess_cfm_check
        where mess_cfm_id = pMessID;
        result := pkg_mess_cfm_1.parseCheckXML(pMessID);
        if result <> 0 then
          UpdateEnchanceData(pMessID);
          return result;
        end if;

      when 3 then
        delete from mess_cfm_check
        where mess_cfm_id = pMessID;
        result := pkg_mess_cfm_1.parseCheckXML(pMessID);
        if result <> 0 then
          UpdateEnchanceData(pMessID);
          return result;
        end if;

      when 4 then
        delete from mess_cfm_dopinf
        where mess_cfm_id = pMessID;
        result := pkg_mess_cfm_1.parseDopInfXML(pMessID);
        if result <> 0 then
          UpdateEnchanceData(pMessID);
          return result;
        end if;

      when 5 then
        delete from mess_cfm_dopinf_answ
        where mess_cfm_id = pMessID;
        result := pkg_mess_cfm_1.parseDopInfAnswXML(pMessID);
        if result <> 0 then
          UpdateEnchanceData(pMessID);
          return result;
        end if;

      when 8 then
        delete from mess_cfm_update_info
        where mess_cfm_id = pMessID;
        result := pkg_mess_cfm_1.parseUpdateInfoXML(pMessID);
        if result <> 0 then
          UpdateEnchanceData(pMessID);
          return result;
        end if;

      when 9 then
        delete from mess_cfm_update_info
        where mess_cfm_id = pMessID;
        result := pkg_mess_cfm_1.parseUpdateRequestXML(pMessID);
        if result <> 0 then
          UpdateEnchanceData(pMessID);
          return result;
        end if;
      when 10 then
        delete from mess_cfm_update_info
        where mess_cfm_id = pMessID;
        result := pkg_mess_cfm_1.parseUpdateXML(pMessID);
        if result <> 0 then
          UpdateEnchanceData(pMessID);
          return result;
        end if;
    end case;
    UpdateEnchanceData(pMessID);
    pkg_audits.WriteUserAudit(9, 'pkg_messages_cfm.UpdateMessage', 'ID: ' || pMessID);
    Return(Result);

  exception
    when others then
      return - 2101;

  end;

  function Get_Message(pMessID     in number,
                       pMessXML    out CLOB,
                       pIsEditable out number) return number is
    Result       number;
    vType        number;
    vStage       number;
    vStatus      number;
    vMessDocType number;
  begin
    Result      := 0;
    pIsEditable := 1;
    begin
      select mc_xml.mess_xml,
             mc.mess_type,
             mc.stage,
             mc.status,
             mc_an.mess_type
      into pMessXML,
           vType,
           vStage,
           vStatus,
           vmessdoctype
      from mess_cfm mc
      left join mess_cfm_xml mc_xml
      on (mc.mess_cfm_id = mc_xml.mess_cfm_id)
      left join mess_cfm_announce_info mc_an
      on (mc.mess_cfm_id = mc_an.mess_cfm_id)
      where mc.mess_cfm_id = pMessID; --and mc_xml.mess_cfm_id = pMessID and mc_an.mess_cfm_id = pMessID;

    exception
      when NO_DATA_FOUND then
        Return(-1000);
    end;
    begin
      select iseditable
      into pIsEditable
      from work_stages_dic
      where workstageid = vStage
      and messagetype = vType;
      if vmessdoctype = 4 then
        pIsEditable := 0;
      elsif vStatus = 20 then
        pIsEditable := 0;
      end if;

    exception
      when NO_DATA_FOUND then
        pIsEditable := 1;
        Return(-1001); --Стадия обработки сообщения или его тип задан неверно
    end;
    return result;
  end;

  function Get_MessageShortData(pMessID    in number,
                                pResCursor out sys_refcursor) return number is
    Result      number default 0;
    pMessType   number;
    vuserlang   varchar2(1000 char);
    vmodulename varchar2(1000 char);
  begin

    result := pkg_main.GetCurrentSettings(vuserlang, vmodulename);
    if result <> 0 then
      return result;
    end if;

    case vuserlang
      when 'Kazakh' then
        open pResCursor for
          select mc.mess_cfm_id                as mess_cfm_id,
                 mc.receive_date               as receive_date,
                 mc_exec.cfm_code              as cfmcode,
                 mc_exec.oper_idtype           as IDTypeOperation,
                 mc_exec.oper_idview           as IDViewOperation,
                 mc_exec.oper_number           as OperationNumber,
                 mc_exec.oper_currency_code   as CurrencyCode,
                 mc_exec.oper_currency_amount as AmountCurrency,
                 mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                 mc_exec.oper_doc_name         as DocOperationName,
                 mc_exec.oper_doc_number       as DocOperationNumber,
                 mc.send_date                  as messdate,
                 mc.status                     as status,
                 mc.mess_version               as Version,
                 mc.mess_docid                 as DocumentUniqueIdentifier,
                 mc.stage                      as workstage,
                 mc.mess_type                  as messtype,
                 mc_exec.update_version        as UpdateVersion,
                 mc_exec.release_date          as DateRelease,
                 mc.sender                     as sender,
                 mc.receiver                   as receiver,
                 mc_exec.mess_number           as messnumber,
                 mc_exec.mess_doctype          as messdoctype,
                 --    mc_exec.mess_reason           as messreason,
                 --    mc_exec.statusname            as statusname,
                 GetEditableField(mc.mess_cfm_id) as iseditable,
                 mc_exec.mess_reason as messreason,
                 mc_exec.statusname_kz as statusname,
                 mc_exec.oper_status as operstatus

          from mess_cfm mc
          join mess_cfm_exec mc_exec
          on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
          where mc.mess_cfm_id = pMessID;
      else
        open pResCursor for
          select mc.mess_cfm_id                as mess_cfm_id,
                 mc.receive_date               as receive_date,
                 mc_exec.cfm_code              as cfmcode,
                 mc_exec.oper_idtype           as IDTypeOperation,
                 mc_exec.oper_idview           as IDViewOperation,
                 mc_exec.oper_number           as OperationNumber,
                 mc_exec.oper_currency_code   as CurrencyCode,
                 mc_exec.oper_currency_amount as AmountCurrency,
                 mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                 mc_exec.oper_doc_name         as DocOperationName,
                 mc_exec.oper_doc_number       as DocOperationNumber,
                 mc.send_date                  as messdate,
                 mc.status                     as status,
                 mc.mess_version               as Version,
                 mc.mess_docid                 as DocumentUniqueIdentifier,
                 mc.stage                      as workstage,
                 mc.mess_type                  as messtype,
                 mc_exec.update_version        as UpdateVersion,
                 mc_exec.release_date          as DateRelease,
                 mc.sender                     as sender,
                 mc.receiver                   as receiver,
                 mc_exec.mess_number           as messnumber,
                 mc_exec.mess_doctype          as messdoctype,
                 --    mc_exec.mess_reason           as messreason,
                 --    mc_exec.statusname            as statusname,
                 GetEditableField(mc.mess_cfm_id) as iseditable,
                 mc_exec.mess_reason as messreason,
                 mc_exec.statusname as statusname,
                 mc_exec.oper_status as operstatus

          from mess_cfm mc
          join mess_cfm_exec mc_exec
          on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
          where mc.mess_cfm_id = pMessID;
    end case;
    Return(Result);
  exception
    when no_data_found then
      return - 1000; -- Сообщение не найдено
  end;

  function Get_MessagesList(pResCursor out sys_refcursor,
                            pListID    in number := 1) return number is
    Result      number default 0;
    vrolegroup  number;
    vmodulename varchar2(100 char);
    vuserlang   varchar2(100 char);
  begin

    result := pkg_users.GetUsersRolesGroup(vrolegroup);
    if result <> 0 then
      return result;
    end if;
    result := pkg_main.GetCurrentSettings(vuserlang, vmodulename);
    if result <> 0 then
      return result;
    end if;
    case vuserlang
      when 'Kazakh' then
        open pResCursor for
          select mc.mess_cfm_id                as mess_cfm_id,
                 mc.receive_date               as receive_date,
                 mc_exec.cfm_code              as cfmcode,
                 mc_exec.oper_idtype           as IDTypeOperation,
                 mc_exec.oper_idview           as IDViewOperation,
                 mc_exec.oper_number           as OperationNumber,
                 mc_exec.oper_currency_code   as CurrencyCode,
                 mc_exec.oper_currency_amount as AmountCurrency,
                 mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                 mc_exec.oper_doc_name         as DocOperationName,
                 mc_exec.oper_doc_number       as DocOperationNumber,
                 mc.send_date                  as messdate,
                 mc.status                     as status,
                 mc.mess_version               as Version,
                 mc.mess_docid                 as DocumentUniqueIdentifier,
                 mc.stage                      as workstage,
                 mc.mess_type                  as messtype,
                 mc_exec.update_version        as UpdateVersion,
                 mc_exec.release_date          as DateRelease,
                 mc.sender                     as sender,
                 mc.receiver                   as receiver,
                 mc_exec.mess_number           as messnumber,
                 mc_exec.mess_doctype          as messdoctype,
                 mc_exec.mess_reason           as messreason,
                 mc_exec.statusname_kz         as statusname,
                 mc_exec.oper_status           as operstatus

          from mess_cfm mc
          join mess_cfm_exec mc_exec
          on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
          where exists (select rowid
                 from mess_listdic_roledest --roledest_ofm_mview
                 where (listnum = pListID and softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type))
          order by mc.receive_date desc; --end select

      else

        case pListID
          when 15 then
            --type=8,9,10
            open pResCursor for
              select mc.mess_cfm_id                as mess_cfm_id,
                     mc.receive_date               as receive_date,
                     mc_exec.cfm_code              as cfmcode,
                     mc_exec.oper_idtype           as IDTypeOperation,
                     mc_exec.oper_idview           as IDViewOperation,
                     mc_exec.oper_number           as OperationNumber,
                     mc_exec.oper_currency_code   as CurrencyCode,
                     mc_exec.oper_currency_amount as AmountCurrency,
                     mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                     mc_exec.oper_doc_name         as DocOperationName,
                     mc_exec.oper_doc_number       as DocOperationNumber,
                     mc.send_date                  as messdate,
                     mc.status                     as status,
                     mc.mess_version               as Version,
                     mc.mess_docid                 as DocumentUniqueIdentifier,
                     mc.stage                      as workstage,
                     mc.mess_type                  as messtype,
                     mc_exec.update_version        as UpdateVersion,
                     mc_exec.release_date          as DateRelease,
                     mc.sender                     as sender,
                     mc.receiver                   as receiver,
                     mc_exec.mess_number           as messnumber,
                     mc_exec.mess_doctype          as messdoctype,
                     mc_exec.mess_reason           as messreason,
                     mc_exec.statusname            as statusname,
                     mc_exec.oper_status           as operstatus

              from mess_cfm mc
              join mess_cfm_exec mc_exec
              on (mc.mess_cfm_id = mc_exec.mess_cfm_id)

              where exists (select rowid
                     from mess_listdic_roledest --roledest_ofm_mview
                     where (listnum = pListID and softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type))
              order by DateRelease desc;

          when 16 then
            --type=8,9,10
            open pResCursor for
              select mc.mess_cfm_id                as mess_cfm_id,
                     mc.receive_date               as receive_date,
                     mc_exec.cfm_code              as cfmcode,
                     mc_exec.oper_idtype           as IDTypeOperation,
                     mc_exec.oper_idview           as IDViewOperation,
                     mc_exec.oper_number           as OperationNumber,
                     mc_exec.oper_currency_code   as CurrencyCode,
                     mc_exec.oper_currency_amount as AmountCurrency,
                     mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                     mc_exec.oper_doc_name         as DocOperationName,
                     mc_exec.oper_doc_number       as DocOperationNumber,
                     mc.send_date                  as messdate,
                     mc.status                     as status,
                     mc.mess_version               as Version,
                     mc.mess_docid                 as DocumentUniqueIdentifier,
                     mc.stage                      as workstage,
                     mc.mess_type                  as messtype,
                     mc_exec.update_version        as UpdateVersion,
                     mc_exec.release_date          as DateRelease,
                     mc.sender                     as sender,
                     mc.receiver                   as receiver,
                     mc_exec.mess_number           as messnumber,
                     mc_exec.mess_doctype          as messdoctype,
                     mc_exec.mess_reason           as messreason,
                     mc_exec.statusname            as statusname,
                     mc_exec.oper_status           as operstatus

              from mess_cfm mc
              join mess_cfm_exec mc_exec
              on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
              where exists (select rowid
                     from mess_listdic_roledest --roledest_ofm_mview
                     where (listnum = pListID and softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type))
              --             and DateRelease>nvl(pkg_updates_cfm.GetLastReleaseDate,to_date('30.10.2009','mm.dd.yyyy'))
              order by DateRelease desc;

          else
            open pResCursor for
              select mc.mess_cfm_id                as mess_cfm_id,
                     mc.receive_date               as receive_date,
                     mc_exec.cfm_code              as cfmcode,
                     mc_exec.oper_idtype           as IDTypeOperation,
                     mc_exec.oper_idview           as IDViewOperation,
                     mc_exec.oper_number           as OperationNumber,
                     mc_exec.oper_currency_code   as CurrencyCode,
                     mc_exec.oper_currency_amount as AmountCurrency,
                     mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                     mc_exec.oper_doc_name         as DocOperationName,
                     mc_exec.oper_doc_number       as DocOperationNumber,
                     mc.send_date                  as messdate,
                     mc.status                     as status,
                     mc.mess_version               as Version,
                     mc.mess_docid                 as DocumentUniqueIdentifier,
                     mc.stage                      as workstage,
                     mc.mess_type                  as messtype,
                     mc_exec.update_version        as UpdateVersion,
                     mc_exec.release_date          as DateRelease,
                     mc.sender                     as sender,
                     mc.receiver                   as receiver,
                     mc_exec.mess_number           as messnumber,
                     mc_exec.mess_doctype          as messdoctype,
                     mc_exec.mess_reason           as messreason,
                     mc_exec.statusname            as statusname,
                     mc_exec.oper_status           as operstatus

              from mess_cfm mc
              join mess_cfm_exec mc_exec
              on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
              where exists (select rowid
                     from mess_listdic_roledest --roledest_ofm_mview
                     where (listnum = pListID and softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type)) --end select
              order by mc.receive_date desc;

        end case;
    end case;
    Return(Result);
  exception
    when others then
      return - 2102;

  end;
  function Get_MessagesListForPeriod(pListID           in number := 1,
                                     pReceiveDateBegin in date,
                                     pReceiveDateEnd   in date,
                                     pResCursor        out sys_refcursor) return number is
    Result      number default 0;
    vrolegroup  number;
    vmodulename varchar2(100 char);
    vuserlang   varchar2(100 char);
  begin
    result := pkg_users.GetUsersRolesGroup(vrolegroup);
    if result <> 0 then
      return result;
    end if;
    result := pkg_main.GetCurrentSettings(vuserlang, vmodulename);
    if result <> 0 then
      return result;
    end if;
    case vuserlang
      when 'Kazakh' then
        open pResCursor for
          select mc.mess_cfm_id                as mess_cfm_id,
                 mc.receive_date               as receive_date,
                 mc_exec.cfm_code              as cfmcode,
                 mc_exec.oper_idtype           as IDTypeOperation,
                 mc_exec.oper_idview           as IDViewOperation,
                 mc_exec.oper_number           as OperationNumber,
                 mc_exec.oper_currency_code   as CurrencyCode,
                 mc_exec.oper_currency_amount as AmountCurrency,
                 mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                 mc_exec.oper_doc_name         as DocOperationName,
                 mc_exec.oper_doc_number       as DocOperationNumber,
                 mc.send_date                  as messdate,
                 mc.status                     as status,
                 mc.mess_version               as Version,
                 mc.mess_docid                 as DocumentUniqueIdentifier,
                 mc.stage                      as workstage,
                 mc.mess_type                  as messtype,
                 mc_exec.update_version        as UpdateVersion,
                 mc_exec.release_date          as DateRelease,
                 mc.sender                     as sender,
                 mc.receiver                   as receiver,
                 mc_exec.mess_number           as messnumber,
                 mc_exec.mess_doctype          as messdoctype,
                 mc_exec.mess_reason           as messreason,
                 mc_exec.statusname_kz         as statusname,
                 mc_exec.oper_status           as operstatus

          from mess_cfm mc
          join mess_cfm_exec mc_exec
          on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
          where mc.receive_date between trunc(pReceiveDateBegin) and trunc(pReceiveDateEnd) + 1
          and exists (select rowid
                 from mess_listdic_roledest --roledest_ofm_mview
                 where ( /*listnum  = pListID
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      and */
                        softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type)) --end select
          order by mc.receive_date desc;
      else
        open pResCursor for
          select mc.mess_cfm_id                as mess_cfm_id,
                 mc.receive_date               as receive_date,
                 mc_exec.cfm_code              as cfmcode,
                 mc_exec.oper_idtype           as IDTypeOperation,
                 mc_exec.oper_idview           as IDViewOperation,
                 mc_exec.oper_number           as OperationNumber,
                 mc_exec.oper_currency_code   as CurrencyCode,
                 mc_exec.oper_currency_amount as AmountCurrency,
                 mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                 mc_exec.oper_doc_name         as DocOperationName,
                 mc_exec.oper_doc_number       as DocOperationNumber,
                 mc.send_date                  as messdate,
                 mc.status                     as status,
                 mc.mess_version               as Version,
                 mc.mess_docid                 as DocumentUniqueIdentifier,
                 mc.stage                      as workstage,
                 mc.mess_type                  as messtype,
                 mc_exec.update_version        as UpdateVersion,
                 mc_exec.release_date          as DateRelease,
                 mc.sender                     as sender,
                 mc.receiver                   as receiver,
                 mc_exec.mess_number           as messnumber,
                 mc_exec.mess_doctype          as messdoctype,
                 mc_exec.mess_reason           as messreason,
                 mc_exec.statusname            as statusname,
                 mc_exec.oper_status           as operstatus

          from mess_cfm mc
          join mess_cfm_exec mc_exec
          on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
          where mc.receive_date between trunc(pReceiveDateBegin) and trunc(pReceiveDateEnd) + 1
          and exists (select rowid
                 from mess_listdic_roledest
                 where ( /*listnum  = pListID
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      and */
                        softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type)) --end select
          order by mc.receive_date desc;
    end case;
    return result;
  end;

  function Get_FilteredMessagesList(pListID                   in number := 1,
                                    pReceiveDateBegin         in date,
                                    pReceiveDateEnd           in date,
                                    pSendDateBegin            in date,
                                    pSendDateEnd              in date,
                                    pMessNumberBegin          in number,
                                    pMessNumberEnd            in number,
                                    pMessReason               in number,
                                    pMessOperationStatus      in number,
                                    pOperationNumber          in varchar2,
                                    pIDTypeOperation          in number,
                                    pIDViewOperation          in number,
                                    pCurrencycode             in number,
                                    pAmountcurrencyBegin      in number,
                                    pAmountcurrencyEnd        in number,
                                    pAmountcurrencytengeBegin in number,
                                    pAmountcurrencytengeEnd   in number,
                                    pResCursor                out sys_refcursor) return number is
    Result      number default 0;
    vrolegroup  number;
    vmodulename varchar2(100 char);
    vuserlang   varchar2(100 char);
  begin

    result := pkg_users.GetUsersRolesGroup(vrolegroup);
    if result <> 0 then
      return result;
    end if;
    result := pkg_main.GetCurrentSettings(vuserlang, vmodulename);
    if result <> 0 then
      return result;
    end if;
    case vuserlang
      when 'Kazakh' then
        open pResCursor for
          select mc.mess_cfm_id                as mess_cfm_id,
                 mc.receive_date               as receive_date,
                 mc_exec.cfm_code              as cfmcode,
                 mc_exec.oper_idtype           as IDTypeOperation,
                 mc_exec.oper_idview           as IDViewOperation,
                 mc_exec.oper_number           as OperationNumber,
                 mc_exec.oper_currency_code   as CurrencyCode,
                 mc_exec.oper_currency_amount as AmountCurrency,
                 mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                 mc_exec.oper_doc_name         as DocOperationName,
                 mc_exec.oper_doc_number       as DocOperationNumber,
                 mc.send_date                  as messdate,
                 mc.status                     as status,
                 mc.mess_version               as Version,
                 mc.mess_docid                 as DocumentUniqueIdentifier,
                 mc.stage                      as workstage,
                 mc.mess_type                  as messtype,
                 mc_exec.update_version        as UpdateVersion,
                 mc_exec.release_date          as DateRelease,
                 mc.sender                     as sender,
                 mc.receiver                   as receiver,
                 mc_exec.mess_number           as messnumber,
                 mc_exec.mess_doctype          as messdoctype,
                 mc_exec.mess_reason           as messreason,
                 mc_exec.statusname_kz         as statusname,
                 mc_exec.oper_status           as operstatus

          from mess_cfm mc
          join mess_cfm_exec mc_exec
          on (mc.mess_cfm_id = mc_exec.mess_cfm_id)

          where exists (select rowid
                 from mess_listdic_roledest --roledest_ofm_mview
                 where (listnum = pListID and softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type)) --end select

          and mc.receive_date between nvl(pReceiveDateBegin, to_date('31.12.1999', 'dd.mm.yyyy')) and nvl(pReceiveDateEnd, to_date('31.12.2999', 'dd.mm.yyyy'))
          and ((mc.send_date between nvl(pSendDateBegin, to_date('31.12.1999', 'dd.mm.yyyy')) and nvl(pSendDateEnd, to_date('31.12.2999', 'dd.mm.yyyy'))) or (mc.send_date is null and pSendDateEnd is null and pSendDateBegin is null))
          and ((mc_exec.mess_number between nvl(pMessNumberBegin, 0) and pMessNumberEnd) or (pMessNumberEnd is null and mc_exec.mess_number >= nvl(pMessNumberBegin, 0)) or (pMessNumberEnd is null))
          and ((mc_exec.mess_reason = pMessReason) or (pMessReason is null))
          and ((mc_exec.oper_number = pOperationNumber) or (pOperationNumber is null))
          and ((mc_exec.oper_status = pMessOperationStatus) or (pMessOperationStatus is null))
          and ((mc_exec.oper_currency_code = pCurrencycode) or (pCurrencycode is null))
          and ((mc_exec.oper_idtype = pIDTypeOperation) or (pIDTypeOperation is null))
          and ((mc_exec.oper_idview = pIDViewOperation) or (pIDViewOperation is null))
          and ((mc_exec.oper_currency_amount between nvl(pAmountcurrencyBegin, 0) and pAmountcurrencyEnd) or (pAmountcurrencyEnd is null and nvl(mc_exec.oper_currency_amount, 0) >= nvl(pAmountcurrencyBegin, 0)) or
                (mc_exec.oper_currency_amount is null and pAmountcurrencyBegin is null and pAmountcurrencyEnd is null))
          and ((mc_exec.oper_tenge_amount between nvl(pAmountcurrencytengeBegin, 0) and pAmountcurrencytengeEnd) or (pAmountcurrencytengeEnd is null and nvl(mc_exec.oper_tenge_amount, 0) >= nvl(pAmountcurrencytengeBegin, 0)) or
                (mc_exec.oper_tenge_amount is null and pAmountcurrencytengeBegin is null and pAmountcurrencytengeEnd is null))
          order by mc.receive_date desc;
      else

        case pListID

          when 15 then
            --type=8,9,10
            open pResCursor for
              select mc.mess_cfm_id                as mess_cfm_id,
                     mc.receive_date               as receive_date,
                     mc_exec.cfm_code              as cfmcode,
                     mc_exec.oper_idtype           as IDTypeOperation,
                     mc_exec.oper_idview           as IDViewOperation,
                     mc_exec.oper_number           as OperationNumber,
                     mc_exec.oper_currency_code   as CurrencyCode,
                     mc_exec.oper_currency_amount as AmountCurrency,
                     mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                     mc_exec.oper_doc_name         as DocOperationName,
                     mc_exec.oper_doc_number       as DocOperationNumber,
                     mc.send_date                  as messdate,
                     mc.status                     as status,
                     mc.mess_version               as Version,
                     mc.mess_docid                 as DocumentUniqueIdentifier,
                     mc.stage                      as workstage,
                     mc.mess_type                  as messtype,
                     mc_exec.update_version        as UpdateVersion,
                     mc_exec.release_date          as DateRelease,
                     mc.sender                     as sender,
                     mc.receiver                   as receiver,
                     mc_exec.mess_number           as messnumber,
                     mc_exec.mess_doctype          as messdoctype,
                     mc_exec.mess_reason           as messreason,
                     mc_exec.statusname            as statusname,
                     mc_exec.oper_status           as operstatus

              from mess_cfm mc
              join mess_cfm_exec mc_exec
              on (mc.mess_cfm_id = mc_exec.mess_cfm_id)

              where exists (select rowid
                     from mess_listdic_roledest --roledest_ofm_mview
                     where (listnum = pListID and softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type))
              order by mc_exec.release_date desc;

          when 16 then
            --type=8,9,10
            open pResCursor for
              select mc.mess_cfm_id                as mess_cfm_id,
                     mc.receive_date               as receive_date,
                     mc_exec.cfm_code              as cfmcode,
                     mc_exec.oper_idtype           as IDTypeOperation,
                     mc_exec.oper_idview           as IDViewOperation,
                     mc_exec.oper_number           as OperationNumber,
                     mc_exec.oper_currency_code   as CurrencyCode,
                     mc_exec.oper_currency_amount as AmountCurrency,
                     mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                     mc_exec.oper_doc_name         as DocOperationName,
                     mc_exec.oper_doc_number       as DocOperationNumber,
                     mc.send_date                  as messdate,
                     mc.status                     as status,
                     mc.mess_version               as Version,
                     mc.mess_docid                 as DocumentUniqueIdentifier,
                     mc.stage                      as workstage,
                     mc.mess_type                  as messtype,
                     mc_exec.update_version        as UpdateVersion,
                     mc_exec.release_date          as DateRelease,
                     mc.sender                     as sender,
                     mc.receiver                   as receiver,
                     mc_exec.mess_number           as messnumber,
                     mc_exec.mess_doctype          as messdoctype,
                     mc_exec.mess_reason           as messreason,
                     mc_exec.statusname            as statusname,
                     mc_exec.oper_status           as operstatus

              from mess_cfm mc
              join mess_cfm_exec mc_exec
              on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
              where exists (select rowid
                     from mess_listdic_roledest --roledest_ofm_mview
                     where (listnum = pListID and softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type))
              order by mc_exec.release_date desc;
            -- and DateRelease>nvl(pkg_updates_cfm.GetLastReleaseDate,'30.10.2009') order by DateRelease;
          else
            open pResCursor for
              select mc.mess_cfm_id                as mess_cfm_id,
                     mc.receive_date               as receive_date,
                     mc_exec.cfm_code              as cfmcode,
                     mc_exec.oper_idtype           as IDTypeOperation,
                     mc_exec.oper_idview           as IDViewOperation,
                     mc_exec.oper_number           as OperationNumber,
                     mc_exec.oper_currency_code   as CurrencyCode,
                     mc_exec.oper_currency_amount as AmountCurrency,
                     mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                     mc_exec.oper_doc_name         as DocOperationName,
                     mc_exec.oper_doc_number       as DocOperationNumber,
                     mc.send_date                  as messdate,
                     mc.status                     as status,
                     mc.mess_version               as Version,
                     mc.mess_docid                 as DocumentUniqueIdentifier,
                     mc.stage                      as workstage,
                     mc.mess_type                  as messtype,
                     mc_exec.update_version        as UpdateVersion,
                     mc_exec.release_date          as DateRelease,
                     mc.sender                     as sender,
                     mc.receiver                   as receiver,
                     mc_exec.mess_number           as messnumber,
                     mc_exec.mess_doctype          as messdoctype,
                     mc_exec.mess_reason           as messreason,
                     mc_exec.statusname            as statusname,
                     mc_exec.oper_status           as operstatus

              from mess_cfm mc
              join mess_cfm_exec mc_exec
              on (mc.mess_cfm_id = mc_exec.mess_cfm_id)

              where exists (select rowid
                     from mess_listdic_roledest --roledest_ofm_mview
                     where (listnum = pListID and softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type)) --end select

              and mc.receive_date between nvl(pReceiveDateBegin, to_date('31.12.1999', 'dd.mm.yyyy')) and nvl(pReceiveDateEnd, to_date('31.12.2999', 'dd.mm.yyyy'))
              and ((mc.send_date between nvl(pSendDateBegin, to_date('31.12.1999', 'dd.mm.yyyy')) and nvl(pSendDateEnd, to_date('31.12.2999', 'dd.mm.yyyy'))) or (mc.send_date is null and pSendDateEnd is null and pSendDateBegin is null))
              and ((mc_exec.mess_number between nvl(pMessNumberBegin, 0) and pMessNumberEnd) or (pMessNumberEnd is null and mc_exec.mess_number >= nvl(pMessNumberBegin, 0)) or (pMessNumberEnd is null))
              and ((mc_exec.mess_reason = pMessReason) or (pMessReason is null))
              and ((mc_exec.oper_number = pOperationNumber) or (pOperationNumber is null))
              and ((mc_exec.oper_status = pMessOperationStatus) or (pMessOperationStatus is null))
              and ((mc_exec.oper_currency_code = pCurrencycode) or (pCurrencycode is null))
              and ((mc_exec.oper_idtype = pIDTypeOperation) or (pIDTypeOperation is null))
              and ((mc_exec.oper_idview = pIDViewOperation) or (pIDViewOperation is null))
              and ((mc_exec.oper_currency_amount between nvl(pAmountcurrencyBegin, 0) and pAmountcurrencyEnd) or (pAmountcurrencyEnd is null and nvl(mc_exec.oper_currency_amount, 0) >= nvl(pAmountcurrencyBegin, 0)) or
                    (mc_exec.oper_currency_amount is null and pAmountcurrencyBegin is null and pAmountcurrencyEnd is null))
              and ((mc_exec.oper_tenge_amount between nvl(pAmountcurrencytengeBegin, 0) and pAmountcurrencytengeEnd) or (pAmountcurrencytengeEnd is null and nvl(mc_exec.oper_tenge_amount, 0) >= nvl(pAmountcurrencytengeBegin, 0)) or
                    (mc_exec.oper_tenge_amount is null and pAmountcurrencytengeBegin is null and pAmountcurrencytengeEnd is null))
              order by mc.receive_date desc;
        end case;
    end case;
    Return(Result);
  exception
    when others then
      return - 2102;
  end;

  function Get_FixedMessagesList(pReceiveDateBegin         in date,
                                 pReceiveDateEnd           in date,
                                 pSendDateBegin            in date,
                                 pSendDateEnd              in date,
                                 pMessNumberBegin          in number,
                                 pMessNumberEnd            in number,
                                 pMessReason               in number,
                                 pMessOperationStatus      in number,
                                 pOperationNumber          in varchar2,
                                 pIDTypeOperation          in number,
                                 pIDViewOperation          in number,
                                 pCurrencycode             in number,
                                 pAmountcurrencyBegin      in number,
                                 pAmountcurrencyEnd        in number,
                                 pAmountcurrencytengeBegin in number,
                                 pAmountcurrencytengeEnd   in number,
                                 pResCursor                out sys_refcursor) return number is
    Result      number default 0;
    vrolegroup  number;
    vmodulename varchar2(100 char);
    vuserlang   varchar2(100 char);
  begin

    result := pkg_users.GetUsersRolesGroup(vrolegroup);
    if result <> 0 then
      return result;
    end if;
    result := pkg_main.GetCurrentSettings(vuserlang, vmodulename);
    if result <> 0 then
      return result;
    end if;
    /*vmodulename:='SFM.CLIENTARM';
    vrolegroup:=4;*/

    case vuserlang
      when 'Kazakh' then
        open pResCursor for
          select mc.mess_cfm_id                as mess_cfm_id,
                 mc.receive_date               as receive_date,
                 mc_exec.cfm_code              as cfmcode,
                 mc_exec.oper_idtype           as IDTypeOperation,
                 mc_exec.oper_idview           as IDViewOperation,
                 mc_exec.oper_number           as OperationNumber,
                 mc_exec.oper_currency_code   as CurrencyCode,
                 mc_exec.oper_currency_amount as AmountCurrency,
                 mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                 mc_exec.oper_doc_name         as DocOperationName,
                 mc_exec.oper_doc_number       as DocOperationNumber,
                 mc.send_date                  as messdate,
                 mc.status                     as status,
                 mc.mess_version               as Version,
                 mc.mess_docid                 as DocumentUniqueIdentifier,
                 mc.stage                      as workstage,
                 mc.mess_type                  as messtype,
                 mc_exec.update_version        as UpdateVersion,
                 mc_exec.release_date          as DateRelease,
                 mc.sender                     as sender,
                 mc.receiver                   as receiver,
                 mc_exec.mess_number           as messnumber,
                 mc_exec.mess_doctype          as messdoctype,
                 mc_exec.mess_reason           as messreason,
                 mc_exec.statusname_kz         as statusname,
                 mc_exec.oper_status           as operstatus

          from mess_cfm mc
          join mess_cfm_exec mc_exec
          on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
          where exists (select rowid
                 from mess_listdic_roledest --roledest_ofm_mview
                 where ( /*listnum = pListID
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      and*/
                        softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type)

                 )

          and mc.receive_date between nvl(pReceiveDateBegin, to_date('31.12.1999', 'dd.mm.yyyy')) and nvl(pReceiveDateEnd, to_date('31.12.2999', 'dd.mm.yyyy'))
          and ((mc.send_date between nvl(pSendDateBegin, to_date('31.12.1999', 'dd.mm.yyyy')) and nvl(pSendDateEnd, to_date('31.12.2999', 'dd.mm.yyyy'))) or (mc.send_date is null and pSendDateEnd is null and pSendDateBegin is null))
          and ((mc_exec.mess_number between nvl(pMessNumberBegin, 0) and pMessNumberEnd) or (pMessNumberEnd is null and mc_exec.mess_number >= nvl(pMessNumberBegin, 0)) or (pMessNumberEnd is null))
          and ((mc_exec.mess_reason = pMessReason) or (pMessReason is null))
          and ((mc_exec.oper_number = pOperationNumber) or (pOperationNumber is null))
          and ((mc_exec.oper_status = pMessOperationStatus) or (pMessOperationStatus is null))
          and ((mc_exec.oper_currency_code = pCurrencycode) or (pCurrencycode is null))
          and ((mc_exec.oper_idtype = pIDTypeOperation) or (pIDTypeOperation is null))
          and ((mc_exec.oper_idview = pIDViewOperation) or (pIDViewOperation is null))
          and ((mc_exec.oper_currency_amount between nvl(pAmountcurrencyBegin, 0) and pAmountcurrencyEnd) or (pAmountcurrencyEnd is null and nvl(mc_exec.oper_currency_amount, 0) >= nvl(pAmountcurrencyBegin, 0)) or
                (mc_exec.oper_currency_amount is null and pAmountcurrencyBegin is null and pAmountcurrencyEnd is null))
          and ((mc_exec.oper_tenge_amount between nvl(pAmountcurrencytengeBegin, 0) and pAmountcurrencytengeEnd) or (pAmountcurrencytengeEnd is null and nvl(mc_exec.oper_tenge_amount, 0) >= nvl(pAmountcurrencytengeBegin, 0)) or
                (mc_exec.oper_tenge_amount is null and pAmountcurrencytengeBegin is null and pAmountcurrencytengeEnd is null));
        --order by mc.receive_date;
      else
        open pResCursor for
          select mc.mess_cfm_id                as mess_cfm_id,
                 mc.receive_date               as receive_date,
                 mc_exec.cfm_code              as cfmcode,
                 mc_exec.oper_idtype           as IDTypeOperation,
                 mc_exec.oper_idview           as IDViewOperation,
                 mc_exec.oper_number           as OperationNumber,
                 mc_exec.oper_currency_code   as CurrencyCode,
                 mc_exec.oper_currency_amount as AmountCurrency,
                 mc_exec.oper_tenge_amount     as AmountCurrencyTenge,
                 mc_exec.oper_doc_name         as DocOperationName,
                 mc_exec.oper_doc_number       as DocOperationNumber,
                 mc.send_date                  as messdate,
                 mc.status                     as status,
                 mc.mess_version               as Version,
                 mc.mess_docid                 as DocumentUniqueIdentifier,
                 mc.stage                      as workstage,
                 mc.mess_type                  as messtype,
                 mc_exec.update_version        as UpdateVersion,
                 mc_exec.release_date          as DateRelease,
                 mc.sender                     as sender,
                 mc.receiver                   as receiver,
                 mc_exec.mess_number           as messnumber,
                 mc_exec.mess_doctype          as messdoctype,
                 mc_exec.mess_reason           as messreason,
                 mc_exec.statusname            as statusname,
                 mc_exec.oper_status           as operstatus

          from mess_cfm mc
          join mess_cfm_exec mc_exec
          on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
          where exists (select rowid
                 from mess_listdic_roledest --roledest_ofm_mview
                 where ( /*listnum = pListID
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      and*/
                        softname = vmodulename and roleid = vrolegroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type))

          and mc.receive_date between nvl(pReceiveDateBegin, to_date('31.12.1999', 'dd.mm.yyyy')) and nvl(pReceiveDateEnd, to_date('31.12.2999', 'dd.mm.yyyy'))
          and ((mc.send_date between nvl(pSendDateBegin, to_date('31.12.1999', 'dd.mm.yyyy')) and nvl(pSendDateEnd, to_date('31.12.2999', 'dd.mm.yyyy'))) or (mc.send_date is null and pSendDateEnd is null and pSendDateBegin is null))
          and ((mc_exec.mess_number between nvl(pMessNumberBegin, 0) and pMessNumberEnd) or (pMessNumberEnd is null and mc_exec.mess_number >= nvl(pMessNumberBegin, 0)) or (pMessNumberEnd is null))
          and ((mc_exec.mess_reason = pMessReason) or (pMessReason is null))
          and ((mc_exec.oper_number = pOperationNumber) or (pOperationNumber is null))
          and ((mc_exec.oper_status = pMessOperationStatus) or (pMessOperationStatus is null))
          and ((mc_exec.oper_currency_code = pCurrencycode) or (pCurrencycode is null))
          and ((mc_exec.oper_idtype = pIDTypeOperation) or (pIDTypeOperation is null))
          and ((mc_exec.oper_idview = pIDViewOperation) or (pIDViewOperation is null))
          and ((mc_exec.oper_currency_amount between nvl(pAmountcurrencyBegin, 0) and pAmountcurrencyEnd) or (pAmountcurrencyEnd is null and nvl(mc_exec.oper_currency_amount, 0) >= nvl(pAmountcurrencyBegin, 0)) or
                (mc_exec.oper_currency_amount is null and pAmountcurrencyBegin is null and pAmountcurrencyEnd is null))
          and ((mc_exec.oper_tenge_amount between nvl(pAmountcurrencytengeBegin, 0) and pAmountcurrencytengeEnd) or (pAmountcurrencytengeEnd is null and nvl(mc_exec.oper_tenge_amount, 0) >= nvl(pAmountcurrencytengeBegin, 0)) or
                (mc_exec.oper_tenge_amount is null and pAmountcurrencytengeBegin is null and pAmountcurrencytengeEnd is null));
        -- order by mc.receive_date;
    end case;
    return result;
  end;

  function Get_RelationMessagesList(pMessID    in number,
                                    pResCursor out sys_refcursor,
                                    pListID    in number := 1) return number is
    Result number default 0;
  begin

    open pResCursor for
      select mc.mess_cfm_id      as mess_cfm_id,
             mc.receive_date     as receive_date,
             mc_an_subj.cfm_code as cfmcode,
             mc.send_date        as messdate,
             mc.status           as status,
             mc.mess_version     as Version,
             mc.mess_docid       as DocumentUniqueIdentifier,
             mc_check.errorcode  as ErrorCode,
             mc_check.errorname  as ErrorName,
             mc.stage            as workstage,
             mc.mess_type        as messtype,
             mc.sender           as sender,
             mc.receiver         as receiver

      from mess_cfm mc

      left join mess_cfm_announce_subj mc_an_subj
      on (mc.mess_cfm_id = mc_an_subj.mess_cfm_id)
      left join mess_cfm_check mc_check
      on (mc.mess_cfm_id = mc_check.mess_cfm_id)

      where mc.mess_parentid = pMessID
      order by receive_date;

    Return(Result);
  end;

  function Get_RelationMessagesTree(pMessID    in number,
                                    pResCursor out sys_refcursor,
                                    pListID    in number := 1) return number is
    Result number default 0;
  begin

    open pResCursor for
      SELECT mc.mess_cfm_id as mess_cfm_id,
             mc.receive_date as receive_date,
             mc.send_date as messdate,
             pkg_analytic.GetMessName(mc.mess_type) as messtype,
             mc.mess_parentid as parentmessid,
             level
      from mess_cfm mc
      where level <> 1
      START WITH mess_cfm_id = pMessID
      CONNECT BY PRIOR mess_cfm_id = mc.mess_parentid
      order by level,
               receive_date;

    Return(Result);
  end;

  function Get_MessagesTypesList(pRolesGroup in number,
                                 pResCursor  out sys_refcursor) return number is
    Result      number default 0;
    vmodulename varchar2(30 char);
    vlanguage   varchar2(30 char);
  begin
    result := pkg_main.GetCurrentSettings(vlanguage, vmodulename);
    if result <> 0 then
      return result;
    end if;
    /* vmodulename:='SFM.CLIENTARM';*/

    case vlanguage
      when 'Russian' then
        open pResCursor for
          select mld.listnum,
                 mld.listname || ' (' || GetCountOfMessagesInGroup(mld.listnum, pRolesGroup, vmodulename) || ')' as listname
          from messages_list_dic mld
          where mld.tablename = 'MESSAGES_CFM'
          and rolemodule = vmodulename
          and bitand(pRolesGroup, mld.roledestination) <> 0
          order by mld.showpriority;

      when 'Kazakh' then
        open pResCursor for
          select mld.listnum,
                 mld.listname_kaz || ' (' || GetCountOfMessagesInGroup(mld.listnum, pRolesGroup, vmodulename) || ')' as listname
          from messages_list_dic mld
          where mld.tablename = 'MESSAGES_CFM'
          and rolemodule = vmodulename
          and bitand(pRolesGroup, mld.roledestination) <> 0
          order by mld.showpriority;
      else
        open pResCursor for
          select mld.listnum,
                 mld.listname || ' (' || GetCountOfMessagesInGroup(mld.listnum, pRolesGroup, vmodulename) || ')' as listname
          from messages_list_dic mld
          where mld.tablename = 'MESSAGES_CFM'
          and rolemodule = vmodulename
          and bitand(pRolesGroup, mld.roledestination) <> 0
          order by mld.showpriority;

    end case;

    Return(Result);

  exception
    when others then
      return - 2102;
  end;

  function Get_MessagesTypesListForPeriod(pRolesGroup       in number,
                                          pReceiveDateBegin in date,
                                          pReceiveDateEnd   in date,
                                          pResCursor        out sys_refcursor) return number is
    Result      number default 0;
    vmodulename varchar2(30 char);
    vlanguage   varchar2(30 char);

  begin
    result := pkg_main.GetCurrentSettings(vlanguage, vmodulename);
    if result <> 0 then
      return result;
    end if;
    /* vmodulename:='SFM.CLIENTARM';*/

    case vlanguage
      when 'Kazakh' then
        open pResCursor for
          select mld.listnum,
                 mld.listname_kaz || ' (' || GetCountOfMessagesInGroup(mld.listnum, pRolesGroup, vmodulename) || ' | ' || GetCountOfMessagesInGroupP(mld.listnum, pRolesGroup, pReceiveDateBegin, pReceiveDateEnd, vmodulename) || ')' as listname
          from messages_list_dic mld
          where mld.tablename = 'MESSAGES_CFM'
          and rolemodule = vmodulename
          and bitand(pRolesGroup, mld.roledestination) <> 0
          order by mld.showpriority;
      else
        open pResCursor for
          select mld.listnum,
                 mld.listname || ' (' || GetCountOfMessagesInGroup(mld.listnum, pRolesGroup, vmodulename) || ' | ' || GetCountOfMessagesInGroupP(mld.listnum, pRolesGroup, pReceiveDateBegin, pReceiveDateEnd, vmodulename) || ')' as listname
          from messages_list_dic mld
          where mld.tablename = 'MESSAGES_CFM'
          and rolemodule = vmodulename
          and bitand(pRolesGroup, mld.roledestination) <> 0
          order by mld.showpriority;
        Return(Result);
    end case;
  exception
    when others then
      return - 2102;
  end;

  function Get_MessagesTypesListFiltered(pRolesGroup               in number,
                                         pReceiveDateBegin         in date,
                                         pReceiveDateEnd           in date,
                                         pSendDateBegin            in date,
                                         pSendDateEnd              in date,
                                         pMessNumberBegin          in number,
                                         pMessNumberEnd            in number,
                                         pMessReason               in number,
                                         pMessOperationStatus      in number,
                                         pOperationNumber          in varchar2,
                                         pIDTypeOperation          in number,
                                         pIDViewOperation          in number,
                                         pCurrencycode             in number,
                                         pAmountcurrencyBegin      in number,
                                         pAmountcurrencyEnd        in number,
                                         pAmountcurrencytengeBegin in number,
                                         pAmountcurrencytengeEnd   in number,
                                         pResCursor                out sys_refcursor) return number is
    Result      number default 0;
    vmodulename varchar2(30 char);
    vlanguage   varchar2(30 char);
  begin
    result := pkg_main.GetCurrentSettings(vlanguage, vmodulename);
    if result <> 0 then
      return result;
    end if;

    /* vmodulename:='SFM.CLIENTARM';*/

    case vlanguage
      when 'Kazakh' then
        open pResCursor for
          select mld.listnum,
                 mld.listname_kaz || ' (' || GetCountOfMessagesInGroup(mld.listnum, pRolesGroup, vmodulename) || ' / ' ||
                 GetCountOfMessagesInGroupF(mld.listnum,
                                            pRolesGroup,
                                            pReceiveDateBegin,
                                            pReceiveDateEnd,
                                            pSendDateBegin,
                                            pSendDateEnd,
                                            pMessNumberBegin,
                                            pMessNumberEnd,
                                            pMessReason,
                                            pMessOperationStatus,
                                            pOperationNumber,
                                            pIDTypeOperation,
                                            pIDViewOperation,
                                            pCurrencycode,
                                            pAmountcurrencyBegin,
                                            pAmountcurrencyEnd,
                                            pAmountcurrencytengeBegin,
                                            pAmountcurrencytengeEnd,
                                            vmodulename) || ')' as listname
          from messages_list_dic mld
          where mld.tablename = 'MESSAGES_CFM'
          and rolemodule = vmodulename
          and bitand(pRolesGroup, mld.roledestination) <> 0
          order by mld.showpriority;
      else
        open pResCursor for
          select mld.listnum,
                 mld.listname || ' (' || GetCountOfMessagesInGroup(mld.listnum, pRolesGroup, vmodulename) || ' / ' ||
                 GetCountOfMessagesInGroupF(mld.listnum,
                                            pRolesGroup,
                                            pReceiveDateBegin,
                                            pReceiveDateEnd,
                                            pSendDateBegin,
                                            pSendDateEnd,
                                            pMessNumberBegin,
                                            pMessNumberEnd,
                                            pMessReason,
                                            pMessOperationStatus,
                                            pOperationNumber,
                                            pIDTypeOperation,
                                            pIDViewOperation,
                                            pCurrencycode,
                                            pAmountcurrencyBegin,
                                            pAmountcurrencyEnd,
                                            pAmountcurrencytengeBegin,
                                            pAmountcurrencytengeEnd,
                                            vmodulename) || ')' as listname
          from messages_list_dic mld
          where mld.tablename = 'MESSAGES_CFM'
          and rolemodule = vmodulename
          and bitand(pRolesGroup, mld.roledestination) <> 0
          order by mld.showpriority;

    end case;

    Return(Result);

  exception
    when others then
      return - 2102;
  end;

  function GetCountOfMessagesInGroup(plistid     in number,
                                     pRolesGroup in number,
                                     pModuleName in varchar2) return number is
    vcount number default 0;
  begin
    select count(*)
    into vcount
    from mess_cfm mc
    where exists (select rowid
           from mess_listdic_roledest --roledest_ofm_mview
           where (listnum = pListID and softname = pmodulename and roleid = prolesgroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type));
    return vcount;
  end;

  function GetCountOfMessagesInGroupP(plistid           in number,
                                      pRolesGroup       in number,
                                      pReceiveDateBegin in date,
                                      pReceiveDateEnd   in date,
                                      pModuleName       in varchar2) return number is
    vcount number default 0;
    pDate1 date;
    pDate2 date;
  begin
    pDate1 := trunc(pReceiveDateBegin);
    pDate2 := trunc(pReceiveDateEnd) + 1;
    select count(*)
    into vcount
    from mess_cfm mc
    where mc.receive_date between pDate1 and pDate2
    and exists (select rowid
           from mess_listdic_roledest --roledest_ofm_mview
           where (listnum = pListID and softname = pmodulename and roleid = prolesgroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type));
    return vcount;
  end;

  function GetCountOfMessagesInGroupF(plistid                   in number,
                                      pRolesGroup               in number,
                                      pReceiveDateBegin         in date,
                                      pReceiveDateEnd           in date,
                                      pSendDateBegin            in date,
                                      pSendDateEnd              in date,
                                      pMessNumberBegin          in number,
                                      pMessNumberEnd            in number,
                                      pMessReason               in number,
                                      pMessOperationStatus      in number,
                                      pOperationNumber          in varchar2,
                                      pIDTypeOperation          in number,
                                      pIDViewOperation          in number,
                                      pCurrencycode             in number,
                                      pAmountcurrencyBegin      in number,
                                      pAmountcurrencyEnd        in number,
                                      pAmountcurrencytengeBegin in number,
                                      pAmountcurrencytengeEnd   in number,
                                      pModuleName               in varchar2) return number is
    vcount                       number default 0;
    pReceiveDateBeginFin         date;
    pReceiveDateEndFin           date;
    pSendDateBeginFin            date;
    pSendDateEndFin              date;
    pAmountcurrencyBeginFin      number;
    pAmountcurrencytengeBeginFin number;
    pMessNumberBeginFin          number;
    --type pConditionsType is table of index by

  begin
    pReceiveDateBeginFin         := nvl(pReceiveDateBegin, to_date('31.12.1999', 'dd.mm.yyyy'));
    pReceiveDateEndFin           := nvl(pReceiveDateEnd, to_date('31.12.2999', 'dd.mm.yyyy'));
    pSendDateBeginFin            := nvl(pSendDateBegin, to_date('31.12.1999', 'dd.mm.yyyy'));
    pSendDateEndFin              := nvl(pSendDateEnd, to_date('31.12.2999', 'dd.mm.yyyy'));
    pAmountcurrencyBeginFin      := nvl(pAmountcurrencyBegin, 0);
    pAmountcurrencytengeBeginFin := nvl(pAmountcurrencytengeBegin, 0);
    pMessNumberBeginFin          := nvl(pMessNumberBegin, 0);
    --pAmountcurrencyEndFin    :=   nvl(pAmountcurrencyEnd,0);

    select /*+ ordered_predicates */
     count(*)
    into vcount
    from mess_cfm mc
    join mess_cfm_exec mc_exec
    on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
    where exists (select rowid
           from mess_listdic_roledest --roledest_ofm_mview
           where (listnum = pListID and softname = pmodulename and roleid = prolesgroup and statusid = mc.status and stagesid = mc.stage and doctype = mc.mess_type))
    and mc.receive_date between pReceiveDateBeginFin and pReceiveDateEndFin
    and ((pSendDateEnd is null and pSendDateBegin is null) or (mc.send_date between pSendDateBeginFin and pSendDateEndFin))
    and ((pMessNumberEnd is null and pMessNumberBegin is null) or (pMessNumberEnd is null and mc_exec.mess_number >= pMessNumberBeginFin) or (mc_exec.mess_number between pMessNumberBeginFin and pMessNumberEnd))
    and ((pMessReason is null) or (mc_exec.mess_reason = pMessReason))
    and ((pOperationNumber is null) or (mc_exec.oper_number = pOperationNumber))
    and ((pMessOperationStatus is null) or (mc_exec.oper_status = pMessOperationStatus))
    and ((pCurrencycode is null) or (mc_exec.oper_currency_code = pCurrencycode))
    and ((pIDTypeOperation is null) or (mc_exec.oper_idtype = pIDTypeOperation))
    and ((pIDViewOperation is null) or (mc_exec.oper_idview = pIDViewOperation))
    and ((pAmountcurrencyBegin is null and pAmountcurrencyEnd is null) or (pAmountcurrencyEnd is null and mc_exec.oper_currency_amount >= pAmountcurrencyBeginFin) or
          (mc_exec.oper_currency_amount between pAmountcurrencyBeginFin and pAmountcurrencyEnd))
    and ((pAmountcurrencytengeBegin is null and pAmountcurrencytengeEnd is null) or (pAmountcurrencytengeEnd is null and mc_exec.oper_tenge_amount >= pAmountcurrencytengeBeginFin) or
          (mc_exec.oper_tenge_amount between pAmountcurrencytengeBeginFin and pAmountcurrencytengeEnd));
    return vcount;
  end;

  function Get_MessagesTypesListSettings(pResCursor out sys_refcursor) return number is
    result         number default 0;
    currRoleId     number;
    currLangName   varchar2(30 char);
    currModuleName varchar2(30 char);
  begin
    result := pkg_users.GetUsersRolesGroup(currRoleId);
    if result <> 0 then
      return result;
    end if;

    result := pkg_main.GetCurrentSettings(currLangName, currModuleName);
    if result <> 0 then
      return result;
    end if;

    open pResCursor for
      select listnum,
             statusid,
             stagesid,
             doctype
      from mess_listdic_roledest t
      where t.roleid = currRoleId
      and t.softname = currModuleName;

    return result;
  end;

  function Get_TransformedMessage(pMessID        in number,
                                  pTransformType in number,
                                  pMessOut       out CLOB) return number is
    Result          number default 0;
    pXMLSCH         xmltype;
    pXML            xmltype;
    pXMLClob        clob;
    vParId          number;
    vParId2         number;
    vParNumber      number;
    vPardate        date;
    vParNAme        varchar2(1000 char);
    vMessdate       date;
    vLastModifyDAte date;
    pTempClob       clob;

    pmesstype    number;
    pmesspartype number;
    pmessversion number;

  begin

    case pTransformType
      when 0 then
        Result := GetInternalDocument(pMessID, pMessOut);
      when 1 then
        select mc_xml.mess_xml
        into pMessOut
        from mess_cfm_xml mc_xml
        where mc_xml.mess_cfm_id = pMessID;
      when 3 then
        pmesstype := GetMessageType(pMessID);
        case pmesstype
          when 1 then
            --ФМ-1
            select mc_xml.mess_xml,
                   mv.versionid
            into pXMLClob,
                 pmessversion
            from mess_cfm mc
            join mess_cfm_xml mc_xml
            on (mc_xml.mess_cfm_id = mc.mess_cfm_id)
            join messages_versions mv
            on mc.mess_version = mv.versioncode
            where mc.mess_cfm_id = pMessID
            and mc.mess_type = 1;

            PXMLSCH := xmltype.createxml(pXMLClob);
            pXML    := PXMLSCH;
            case pmessversion
              when 1 then
                pxml := GetOuterAnnounceXML_1(PXMLSCH);
                -- when 2 then
              else
                pxml := pkg_mess_cfm_2.GetOuterAnnounceXML(PXMLSCH, pmessversion);
                --  else null;
            end case;

            select xmltransform(PXML, xmltype.createxml(mv.messxmlschema)).getclobval()
            into pMessOut
            from messages_versions mv
            where mv.mess_type = 1
            and mv.versionid = pmessversion;
          when 2 then
            --О принятии
            select mc_xml.mess_xml,
                   mc.send_date
            into pXMLClob,
                 vmessdate
            from mess_cfm mc
            join mess_cfm_xml mc_xml
            on (mc_xml.mess_cfm_id = mc.mess_cfm_id)
            where mc.mess_cfm_id = pMessID;

            result := Get_ParentIDByMessagesID(pMessID, vParId);
            if result = 0 then
              pmesspartype := GetMessageType(vParId);
              case pmesspartype
                when 1 then
                  select mc.send_date,
                         mc_an_info.mess_number,
                         mc_an_info.mess_date,
                         mc_an_subj.cfm_name
                  into vPardate,
                       vParNumber,
                       vLastModifyDAte,
                       vParNAme
                  from mess_cfm mc
                  left join mess_cfm_announce_info mc_an_info
                  on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
                  left join mess_cfm_announce_subj mc_an_subj
                  on (mc.mess_cfm_id = mc_an_subj.mess_cfm_id)
                  where mc.mess_cfm_id = vParId;
                  pTempClob := replace(pXMLClob,
                                       '</Check>',
                                       '<MessNumber>' || vParNumber || '</MessNumber>
                                     <MessDate>' || to_char(vLastModifyDAte, 'dd.mm.yyyy') || '</MessDate>
                                     <SendDate>' || to_char(vmessdate, 'dd.mm.yyyy HH24:mi:ss') || '</SendDate>
                                     <MessOwn>' || vParNAme || '</MessOwn></Check>');
                  begin
                    select xmltransform(xmltype.createxml(pTempClob), xmltype.createxml(mv.messxmlschema)).getclobval()
                    into pMessOut
                    from mess_cfm          mc,
                         messages_versions mv
                    where mc.mess_cfm_id = pMessID
                    and mv.mess_type = 2;
                  exception
                    when others then
                      Return(-4000);
                  end;
                when 5 then
                  select mc_an_info.mess_number,
                         mc.send_date
                  into vParNumber,
                       vPardate
                  from mess_cfm mc
                  left join mess_cfm_announce_info mc_an_info
                  on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
                  where mc.mess_cfm_id = vParId;
                  pTempClob := replace(pXMLClob,
                                       '</Check>',
                                       '<MessDate>' || to_char(vPardate, 'dd.mm.yyyy HH24:mi:ss') || '</MessDate>
                                       <SendDate>' || to_char(vmessdate, 'dd.mm.yyyy HH24:mi:ss') || '</SendDate></Check>');

                  begin
                    select xmltransform(xmltype.createxml(pTempClob), xmltype.createxml(mv.messxmlschema)).getclobval()
                    into pMessOut
                    from mess_cfm          mc,
                         messages_versions mv
                    where mc.mess_cfm_id = pMessID
                    and mv.mess_type = 7; --Квитанция об отклонении
                  exception
                    when others then
                      Return(-4000);
                  end;
                when 4 then
                  select mc_an_info.mess_number,
                         mc.send_date
                  into vParNumber,
                       vPardate
                  from mess_cfm mc
                  left join mess_cfm_announce_info mc_an_info
                  on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
                  where mc.mess_cfm_id = vParId;

                  --PXMLSCH:= xmltype.createxml(pXMLClob);
                  --select extract(PXMLSCH,'/Root').getclobval() into pXMLClob from dual;
                  pTempClob := replace(pXMLClob,
                                       '</Check>',
                                       '<MessDate>' || to_char(vPardate, 'dd.mm.yyyy HH24:mi:ss') || '</MessDate>
                                            <SendDate>' || to_char(vmessdate, 'dd.mm.yyyy HH24:mi:ss') || '</SendDate></Check>');

                  begin
                    select xmltransform(xmltype.createxml(pTempClob), xmltype.createxml(mv.messxmlschema)).getclobval()
                    into pMessOut
                    from mess_cfm          mc,
                         messages_versions mv
                    where mc.mess_cfm_id = pMessID
                    and mv.mess_type = 6;
                  exception
                    when others then
                      Return(-4000);
                  end;
                else
                  return - 4000; --Принтие приходит только для 2,4,5
              end case;
            end if;
          when 3 then
            --Об отклонении
            select mc_xml.mess_xml,
                   mc.send_date
            into pXMLClob,
                 vmessdate
            from mess_cfm mc
            join mess_cfm_xml mc_xml
            on (mc_xml.mess_cfm_id = mc.mess_cfm_id)
            where mc.mess_cfm_id = pMessID;

            result       := Get_ParentIDByMessagesID(pMessID, vParId);
            pmesspartype := GetMessageType(vParId);
            case pmesspartype
              when 1 then
                select mc.send_date,
                       mc_an_info.mess_number,
                       mc_an_info.mess_date,
                       mc_an_subj.cfm_name
                into vPardate,
                     vParNumber,
                     vLastModifyDAte,
                     vParNAme
                from mess_cfm mc
                left join mess_cfm_announce_info mc_an_info
                on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
                left join mess_cfm_announce_subj mc_an_subj
                on (mc.mess_cfm_id = mc_an_subj.mess_cfm_id)
                where mc.mess_cfm_id = vParId;
                pTempClob := replace(pXMLClob,
                                     '</Root>',
                                     '<MessNumber>' || vParNumber || '</MessNumber>
                                               <MessDate>' || to_char(vLastModifyDAte, 'dd.mm.yyyy') || '</MessDate>
                                               <SendDate>' || to_char(vmessdate, 'dd.mm.yyyy HH24:mi:ss') || '</SendDate>
                                               <MessOwn>' || vParNAme || '</MessOwn></Root>');

                begin
                  select xmltransform(xmltype.createxml(pTempClob), xmltype.createxml(mv.messxmlschema)).getclobval()
                  into pMessOut
                  from mess_cfm          mc,
                       messages_versions mv
                  where mc.mess_cfm_id = pMessID
                  and mv.mess_type = 3;
                exception
                  when others then
                    Return(-4000);
                end;
              when 5 then
                select mc_an_info.mess_number,
                       mc.send_date
                into vParNumber,
                     vPardate
                from mess_cfm mc
                left join mess_cfm_announce_info mc_an_info
                on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
                where mc.mess_cfm_id = vParId;
                pTempClob := replace(pXMLClob,
                                     '</Root>',
                                     '<MessDate>' || to_char(vPardate, 'dd.mm.yyyy HH24:mi:ss') || '</MessDate>
                                               <SendDate>' || to_char(vmessdate, 'dd.mm.yyyy HH24:mi:ss') || '</SendDate></Root>');
                begin
                  select xmltransform(xmltype.createxml(pTempClob), xmltype.createxml(mv.messxmlschema)).getclobval()
                  into pMessOut
                  from mess_cfm          mc,
                       messages_versions mv
                  where mc.mess_cfm_id = pMessID
                  and mv.mess_type = 7;
                exception
                  when others then
                    Return(-4000);
                end;
              else
                return - 4000;
            end case;
          when 4 then
            --Запрос ДИ
            select mc_xml.mess_xml
            into pXMLClob
            from mess_cfm mc
            join mess_cfm_xml mc_xml
            on (mc_xml.mess_cfm_id = mc.mess_cfm_id)
            where mc.mess_cfm_id = pMessID;
            result := Get_ParentIDByMessagesID(pMessID, vParId);

            select mc_an_info.mess_number,
                   mc.send_date
            into vParNumber,
                 vPardate
            from mess_cfm mc
            left join mess_cfm_announce_info mc_an_info
            on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
            where mc.mess_cfm_id = vParId;
            pTempClob := replace(pXMLClob,
                                 '</Root>',
                                 '<MessNumber>' || vParNumber || '</MessNumber>
                                    <MessDate>' || to_char(vPardate, 'dd.mm.yyyy HH24:mi:ss') || '</MessDate>
                                    </Root>');
            begin
              select xmltransform(xmltype.createxml(pTempClob), xmltype.createxml(mv.messxmlschema)).getclobval()
              into pMessOut
              from mess_cfm          mc,
                   messages_versions mv
              where mc.mess_cfm_id = pMessID
              and mv.mess_type = 4;
            exception
              when others then
                pMessOut := PXMLClob;
            end;
          when 5 then
            --Ответ на зпрос ДИ
            select mc_xml.mess_xml
            into pXMLClob
            from mess_cfm mc
            join mess_cfm_xml mc_xml
            on (mc_xml.mess_cfm_id = mc.mess_cfm_id)
            where mc.mess_cfm_id = pMessID;

            result := Get_ParentIDByMessagesID(pMessID, vParId);
            if result <> 0 then
              null;
            end if;
            result := Get_ParentIDByMessagesID(vParId, vParId2);
            if result = 0 then
              select mc_an_info.mess_number,
                     mc.send_date
              into vParNumber,
                   vPardate
              from mess_cfm mc
              left join mess_cfm_announce_info mc_an_info
              on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
              where mc.mess_cfm_id = vParId2;

              pTempClob := replace(pXMLClob,
                                   '</Root>',
                                   '<MessNumber>' || vParNumber || '</MessNumber>
                                                <MessDate>' || to_char(vPardate, 'dd.mm.yyyy HH24:mi:ss') || '</MessDate></Root>');

            else
              pTempClob := replace(pXMLClob,
                                   '</Root>',
                                   '<MessNumber>' || pkg_main.GetSimpleError(-1013) || '</MessNumber>
                                                <MessDate>' || pkg_main.GetSimpleError(-1013) || '</MessDate></Root>');
              result    := 0;
            end if;
            pmessout := null;
            select xmltransform(xmltype.createxml(pTempClob), xmltype.createxml(mv.messxmlschema)).getclobval()
            into pMessOut
            from mess_cfm          mc,
                 messages_versions mv
            where mc.mess_cfm_id = pMessID
            and mv.mess_type = 5;
            --dbms_lob.append(pXMLClob, '<MessNumber>'||vParNumber||'</MessNumber><MessDate>'||vPardate||'</MessDate>');
          when 11 then
            select mc_xml.mess_xml
            into pTempClob
            from mess_cfm_xml mc_xml
            where mc_xml.mess_cfm_id = pMessID;

            select mv.messxmlschema
            into pXMLClob
            from messages_versions mv
            where mv.mess_type = 11;
            pxml := GetOuterRegistrationData_1(xmltype.createxml(pTempClob));
            select xmltransform(pxml, xmltype.createxml(pXMLClob)).getclobval()
            into pMessOut
            from dual;
          when 12 then
            select xmltransform(xmltype.createxml(mc_xml.mess_xml), xmltype.createxml(mv.messxmlschema)).getclobval()
            into pMessOut
            from mess_cfm_xml      mc_xml,
                 messages_versions mv
            where mc_xml.mess_cfm_id = pMessID
            and mv.mess_type = 12;
          when 13 then
            select xmltransform(xmltype.createxml(mc_xml.mess_xml), xmltype.createxml(mv.messxmlschema)).getclobval()
            into pMessOut
            from mess_cfm_xml      mc_xml,
                 messages_versions mv
            where mc_xml.mess_cfm_id = pMessID
            and mv.mess_type = 13;
          when 14 then
            select xmltransform(xmltype.createxml(mc_xml.mess_xml), xmltype.createxml(mv.messxmlschema)).getclobval()
            into pMessOut
            from mess_cfm_xml      mc_xml,
                 messages_versions mv
            where mc_xml.mess_cfm_id = pMessID
            and mv.mess_type = 14;
          when 15 then
            -- встречные отчеты
            select mess_xml
            into pXMLClob
            from mess_cfm_xml
            where mess_cfm_id = pMessID; -- получаем исходный XML

            Result := pkg_rqst_cntr_cfm.rqst_cntr_transform(pXMLClob, pXMLClob); -- поллучаем подготовленый XML

            select xmltransform(xmltype.createxml(pXMLClob), xmltype.createxml(mv.messxmlschema)).getclobval()
            into pMessOut
            from messages_versions mv
            where mv.mess_type = 15;
          else
            return - 4000;
        end case;

      when 4 then
        select mx.messxml
        into pMessOut
        from messages_cfm_xml mx
        where mx.mess_cfm_id = pMessID
        and mx.transformtype = pTransformType
        and rownum = 1; --  Исправление!!!! ---
    end case;
    Return(Result);

  exception
    when NO_DATA_FOUND then
      Return(-1000);
    when others then
      dbms_output.put_line(sqlerrm);
      return - 2115; --Ошибка преобразования XML
  end;

  function Save_TransformedMessage(pMessID        in number,
                                   pTransformType in number,
                                   pMessIn        in CLOB,
                                   pExtErrorCode  in number := -1) return number is
    Result       number;
    vmessid      number;
    vSender      varchar2(50 char);
    vReceiver    varchar2(50 char);
    pMessDocDate date;
    pType        number;
    vOldStage    number;
    vOldStatus   number;
    vExistCover  number;
  begin
    Result := 0;

    insert into messages_cfm_xml
      (mess_cfm_id,
       transformtype,
       messxml,
       exterrorcode)
    values
      (pMessID,
       pTransformType,
       pMessIn,
       pExtErrorCode);
    if pTransformType = 4 then
      pType := GetMessageType(pMessID);

      if pType in (1, 5, 9, 11, 15) then
        begin
          begin
            select stage,
                   status
            into vOldStage,
                 vOldStatus
            from mess_cfm
            where mess_cfm_id = pMessID;
            if ptype = 1 then
              case
              --   when  vOldStage = 1 then -- редактируется then null;    return -510;
                when (vOldStage = 20 and vOldStatus = 20) then
                  return - 514;
                when (vOldStage = 30) then
                  return - 511;
                when (vOldStage = 40 and vOldStatus = 40) then
                  return - 513;
                when (vOldStage = 40 and vOldStatus = 50) then
                  return - 512;
                when (vOldStage = 1 and vOldStatus in (1, 10)) then
                  return - 521;
                when (vOldStage = 1 and vOldStatus = 20) then
                  return - 522;
                else
                  Result := ChangeStatus(pMessID, 30, 1);
                  UpdateMessNumber(pMessID, pMessIn);

              end case;
              --Result:=ChangeStatus(pMessID,30,1);
            else

              if (vOldStage >= 30) then
                return - 511;
              end if;
              -- Result:=ChangeStatus(pMessID,30,1);
            end if;
          exception
            when no_data_found then
              return - 1000; -- не найдено сообщение
          end;
          if pType = 5 then
            Result := ChangeStatus(pMessID, 30, 1);
            result := Get_ParentIDByMessagesID(pMessID, vMessId);
            result := ChangeStatus(vMessId, 70, 1);
          end if;
          if pType = 11 then
            Result := ChangeStatus(pMessID, 30, 1);
          end if;
          if pType = 15 then
            Result := ChangeStatus(pMessID, 30, 1);
          end if;
          result := pkg_mess_cfm_1.ExtractMessInSignedData(pMessIn, vExistCover, vSender, vReceiver, pMessDocDate);
          update mess_cfm mc
          set mc.sender    = vsender,
              mc.receiver  = vreceiver,
              mc.send_date = pmessdocdate
          where mc.mess_cfm_id = pMessID;
          -- Result:=ChangeStatus(pMessID,30,1);

        exception
          when others then
            null;
        end;

      elsif pType in (2, 3) then
        begin
          result := pkg_mess_cfm_1.ExtractMessInSignedData(pMessIn, vExistCover, vSender, vReceiver, pMessDocDate); --------
          update mess_cfm mc
          set sender    = vsender,
              receiver  = vreceiver,
              send_date = pmessdocdate
          where mc.mess_cfm_id = pMessID;
          result := ChangeStatus(pMessID, 30, 1);
        exception
          when others then
            null;
        end;
      elsif pType in (4, 8, 10) then
        begin
          result := pkg_mess_cfm_1.ExtractMessInSignedData(pMessIn, vExistCover, vSender, vReceiver, pMessDocDate); ---------
          update mess_cfm mc
          set sender    = vsender,
              receiver  = vreceiver,
              send_date = pmessdocdate
          where mc.mess_cfm_id = pMessID;

        exception
          when others then
            null;
        end;
      end if;
    end if;

    Return(Result);

  exception
    when no_data_found then
      return - 1000; --Док не найден
    when others then
      return - 2113; --Ошибка сохранения преобразованного документа
  end;

  function Transform_Message(pMessID        in number,
                             pTransformType in number,
                             pMessOut       out CLOB) return number is
    Result number default 0;
  begin

    Result := Get_TransformedMessage(pMessID, pTransformType, pMessOut);
    Return(Result);

  exception
    when NO_DATA_FOUND then
      Return(-1000);
  end;

  function ChangeStatus(pMessID     in number,
                        pWorkStage  in number,
                        pWorkStatus in number) return number is
    Result number default 0;
    vcount number default 0;
  begin

    select count(*)
    into vcount
    from work_status_dic
    where workstageid = pWorkStage
    and workstatus = pWorkStatus;
    if vcount = 1 then
      update mess_cfm mc
      set mc.status = pWorkStatus,
          mc.stage  = pWorkStage
      where mc.mess_cfm_id = pMessID;

      UpdateEnchanceStatusName(pMessID);
      pkg_audits.writemessaudit('CFM', pMessID, pWorkStage, pWorkStatus);
    else
      result := -1002; -- Не определено входящее соотношение состояния к данному этапу обработки сообщения
    end if;
    Return(Result);

  exception
    when OTHERS then
      rollback;
      Return - 540;
  end;

  function ToNextStage(pMessID number) return number is
    result number default 0;

    vOldStage         number;
    vOldStatus        number;
    vNewStage         number;
    vNewStatus        number;
    resultValidate    varchar2(4000 char);
    expresultValidate clob;
    pType             number;
    pversionid        number;
  begin
    expresultValidate := empty_clob();
    begin
      select mc.stage,
             mc.status,
             mc.mess_type,
             mv.versionid
      into vOldStage,
           vOldStatus,
           pType,
           pversionid
      from mess_cfm mc
      left join messages_versions mv
      on (mc.mess_version = mv.versioncode)
      where mc.mess_cfm_id = pMessID;
    exception
      when no_data_found then
        return - 1000; -- не найдено сообщение
    end;

    begin
      --     select * into vNewStage from (select workstageid  from work_stages_dic where workstageid>vOldStage order by workstageid) where rownum =1;
      --      if (vOldStage,vOldStatus) in (1,20)  - исключено из обработки на этапе редактирования
      --      if (vOldStage,vOldStatus) in (20,20) - исключено из обработки на этапе проверки отв сотрудником
      --      if ()
      case
        when (vOldStage = 1 and (vOldStatus = 1 or vOldStatus = 10)) or (vOldStage = 1 and vOldStatus = 30) then
          -- редактируется
          if (pType = 1 and pversionid = 1) then
            if (pkg_messverifyprocs.VerifyMessage(pMessID, resultValidate, expresultValidate) <> 0) then
              return - 900;
            end if;
          end if;
          vNewStage  := 20;
          vNewStatus := 1;
          result     := ChangeStatus(pMessID, vNewStage, vNewStatus);
        when (vOldStage = 1 and vOldStatus = 20) then
          return - 502;

        else
          return - 503;
      end case;

    exception
      when no_data_found then
        return - 500; --Данная стадия обработки последняя
    end;
    return result;
  end;

  function ToPreviousStage(pMessID number) return number is
    result     number default 0;
    vOldStage  number;
    vOldStatus number;
    vNewStage  number;
    vNewStatus number;
    vMessType  number;
  begin
    begin
      --  if vMessType not in (1,5) then
      select stage,
             status,
             mess_type
      into vOldStage,
           vOldStatus,
           vmesstype
      from mess_cfm
      where mess_cfm_id = pMessID;
    exception
      when no_data_found then
        return - 1000; -- не найдено сообщение
    end;
    begin
      /*  select * into vNewStage from (select workstageid  from work_stages_dic where workstageid<vOldStage order by workstageid DESC) where rownum =1;
       result:= ChangeStatus(pMessID,vNewStage,10);
      */
      case
        when vOldStage = 1 then
          return - 504;
        when (vOldStage = 20 and vOldStatus = 1) or (vOldStage = 1 and (vOldStatus = 30 or vOldStatus = 10)) then
          -- редактируется
          vNewStage  := 1;
          vNewStatus := 10; --Доработка
          result     := ChangeStatus(pMessID, vNewStage, vNewStatus);
        when (vOldStage = 20 and vOldStatus = 20) then
          vNewStage  := 20;
          vNewStatus := 10;
          result     := ChangeStatus(pMessID, vNewStage, vNewStatus);
          return - 505;
        when (vOldStage = 1 and vOldStatus = 20) then
          --Доработка сообщения
          vNewStage  := 1;
          vNewStatus := 10;
          result     := ChangeStatus(pMessID, vNewStage, vNewStatus);
          return - 506;

        else
          return - 503;
      end case;

    exception
      when no_data_found then
        return - 501; --Данная стадия обработки последняя.
    end;
    return result;
  end;

  function Exclude(pMessID number) return number is
    result number default 0;

    vOldStage  number;
    vOldStatus number;

  begin
    begin
      select stage,
             status
      into vOldStage,
           vOldStatus
      from mess_cfm
      where mess_cfm_id = pMessID;
    exception
      when no_data_found then
        return - 1000; -- не найдено сообщение
    end;
    begin
      if (vOldStage in (1, 20) and vOldStatus in (1, 10)) then
        -- select * into vNewStage from (select workstageid  from work_stages_dic where workstageid<vOldStage order by workstageid DESC) where rownum =1;
        result := ChangeStatus(pMessID, vOldStage, 20);
      elsif (vOldStage in (1, 20) and vOldStatus = 20) then
        result := ChangeStatus(pMessID, vOldStage, 10);

      else
        return - 507;
      end if;
    exception
      when no_data_found then
        return - 501; --Данная стадия обработки последняя.
    end;
    return result;
  end;

  function Delete_Message(pMessID number) return number is
    result number default 0;

    vOldStage  number;
    vOldStatus number;

  begin
    begin
      select stage,
             status
      into vOldStage,
           vOldStatus
      from mess_cfm
      where mess_cfm_id = pMessID;
    exception
      when no_data_found then
        return - 1000; -- не найдено сообщение
    end;
    begin
      if (vOldStage in (1, 20) and vOldStatus in (1, 10, 20)) then
        -- select * into vNewStage from (select workstag eid  from work_stages_dic where workstageid<vOldStage order by workstageid DESC) where rownum =1;
        insert into MESS_CFM_GARBAGE
          (mess_cfm_id,
           mess_type,
           mess_version,
           mess_form_guid,
           receive_date,
           truncate_date,
           mess_xml)
          select mc.mess_cfm_id,
                 mc.mess_type,
                 mc.mess_version,
                 mc.mess_form_guid,
                 mc.receive_date,
                 sysdate,
                 mc_xml.mess_xml
          from mess_cfm mc
          join mess_cfm_xml mc_xml
          on mc_xml.mess_cfm_id = mc.mess_cfm_id
          where mc.mess_cfm_id = pMessID;

        delete from mess_cfm_xml
        where mess_cfm_id = pMessID;
        delete from mess_cfm_exec
        where mess_cfm_id = pMessID;

        delete from mess_cfm_update_info
        where mess_cfm_id = pMessID;
        delete from mess_cfm_dopinf_answ
        where mess_cfm_id = pMessID;
        delete from mess_cfm_dopinf
        where mess_cfm_id = pMessID;
        delete from mess_cfm_check
        where mess_cfm_id = pMessID;

        delete from mess_cfm_announce_accounts
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_found
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_memb
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_subj
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_oper
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_cont
        where mess_cfm_id = pMessID;
        delete from mess_cfm_announce_info
        where mess_cfm_id = pMessID;
        delete from mess_cfm
        where mess_cfm_id = pMessID;

        pkg_audits.WriteUserAudit(10, 'pkg_messages_cfm.Delete_Message', 'ID: ' || pMessID);
      else
        return - 507;
      end if;
    exception
      when others then
        return - 508; --При удалении сообщения возникли ошибки
    end;
    return result;
  end Delete_Message;

  --Возвращается только 1 ID (наиболее поздний)?
  function Get_MessagesIDByParentID(pParentID in number,
                                    pMessID   out number, /*sCur   out sys_refcursor*/
                                    pMessType in number := 4) return number is
    Result number default 0;
  begin

    select nvl(max(mc.mess_cfm_id), 0)
    into pMessID
    from mess_cfm mc
    where mc.mess_parentid = pParentID
    and mc.mess_type = pMessType;

    Return(Result);
  exception
    when no_data_found then
      pMessID := -1;
      return - 1004; --Порожденное сообщение заданного типа не найдено
  end;
  --Возвращается только 1 ID (наиболее поздний)?
  function Get_MessagesListByParentID(pParentID    in number,
                                      pMessagesCur out sys_refcursor,
                                      pMessType    in number := 4) return number is
    Result number default 0;
    vlang  varchar2(10 char) default 'Russian';
  begin
    vlang := pkg_main.GetUserLangSettings;
    open pMessagesCur for
      select mc.mess_cfm_id as mess_cfm_id,
             mc.receive_date as receive_date,
             mc_exec.cfm_code as cfmcode,
             mc_exec.oper_idtype as IDTypeOperation,
             mc_exec.oper_idview as IDViewOperation,
             mc_exec.oper_number as OperationNumber,
             mc_exec.oper_currency_code as CurrencyCode,
             mc_exec.oper_currency_amount as AmountCurrency,
             mc_exec.oper_tenge_amount as AmountCurrencyTenge,
             mc_exec.oper_doc_name as DocOperationName,
             mc_exec.oper_doc_number as DocOperationNumber,
             mc.send_date as messdate,
             mc.status as status,
             mc.mess_version as Version,
             mc.mess_docid as DocumentUniqueIdentifier,
             mc.stage as workstage,
             mc.mess_type as messtype,
             mc_exec.update_version as UpdateVersion,
             mc_exec.release_date as DateRelease,
             mc.sender as sender,
             mc.receiver as receiver,
             mc_exec.mess_number as messnumber,
             mc_exec.mess_doctype as messdoctype,
             mc_exec.mess_reason as messreason,
             decode(vlang, 'Kazakh', mc_exec.statusname_kz, mc_exec.statusname) as statusname,
             mc_exec.oper_status as operstatus
      from mess_cfm mc
      join mess_cfm_exec mc_exec
      on (mc.mess_cfm_id = mc_exec.mess_cfm_id)
      where mc.mess_parentid = pParentID
      and mc.mess_type = pMessType;

    Return(Result);
  exception
    when no_data_found then
      --pMessID := -1;
      return - 1004; --Порожденное сообщение заданного типа не найдено
  end;

  function Get_ParentIDByMessagesID(pMessID   in number,
                                    pParentID out number) return number is
    Result number default 0;
  begin

    select nvl(mc.mess_parentid, 0)
    into pParentID
    from mess_cfm mc
    where mc.mess_cfm_id = pMessID;

    if pParentID is null or pParentID = -1 then
      case GetMessageType(pMessID)
        when 4 then
          Result := -1009;
        else
          Result := -1013; --
      end case;
    end if;
    Return(Result);

  exception
    when no_data_found then
      pParentID := -1;
      return - 1000; --Сообщение не найдено
  end;

  function GetFirstNodeID(pMessID     number,
                          firstnodeid out number) return number is
    result number default 0;
  begin

    firstnodeid := pMessID;
    for prec in
    --result:=Get_ParentIDByMessagesID(childid,parentid);
     (select mc.mess_cfm_id
      from mess_cfm mc
      connect by prior mc.mess_parentid = mc.mess_cfm_id
      start with mc.mess_cfm_id = pMessID
      order by level desc) loop
      firstnodeid := prec.mess_cfm_id;
      exit;
    end loop;
    return result;
  end;

  function GetInternalDocument(pMessID  in number,
                               pMessOut out CLOB) return number is
    Result    number default 0;
    vMessCLOB CLOB;
  begin
    select mc_xml.mess_xml
    into vMessCLOB
    from mess_cfm_xml mc_xml
    where mc_xml.mess_cfm_id = pMessID;

    Result := pkg_messages_xml.Get_RootNodeFromXML(vMessCLOB, pMessOut);

    Return(Result);

  exception
    when NO_DATA_FOUND then
      Return(-1000);
  end;

  function GetMessageType(pMessID in number) return number is
    result number default 0;
  begin
    select mess_type
    into result
    from mess_cfm
    where mess_cfm_id = pMessID;
    return result;

  exception
    when no_data_found then
      return 0;
  end;

  function GenerateMessageNumber return number is
    result number;
  begin
    select GetTempMessNumb
    into result
    from dual;
    return result;
  end;

  function GenerateSendMessageNumber return number is
    result number;
  begin
    select messnumb.nextval
    into result
    from dual;
    return result;
  end;

  function IsLabelEditable(pMessID     in number,
                           labelCheck  out number,
                           labelRenew  out number,
                           labelDelete out number) return number is
    result         number default 0;
    pMessDocType   number;
    pMessDocNumber number;
    vType          number;
    vcount         number default 0;
    vcount1        number default 0;
    vStage         number;
  begin
    labelCheck  := 1;
    labelRenew  := 1;
    labelDelete := 1;
    select mc_an_info.mess_type,
           mc_an_info.mess_number,
           mc.mess_type,
           mc.stage
    into pMessDocType,
         pMessDocNumber,
         vType,
         vStage
    from mess_cfm mc
    left join mess_cfm_announce_info mc_an_info
    on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
    where mc.mess_cfm_id = pMessID;

    case pMessDocType
      when 1 then
        select iseditable
        into labelCheck
        from work_stages_dic
        where workstageid = vStage
        and messagetype = vType;
        if labelCheck = 0 then
          select count(*)
          into vcount
          from mess_cfm_announce_info mc_an_info
          where mc_an_info.mess_number = pMessDocNumber
          and mc_an_info.mess_type = 3;
          select count(*)
          into vcount1
          from mess_cfm_announce_info mc_an_info
          where mc_an_info.mess_number = pMessDocNumber
          and mc_an_info.mess_type = 4;
          if vcount1 <> 0 and vcount <> 0 then
            labelRenew  := 0;
            labelDelete := 0;
          elsif vcount = 0 then
            labelRenew := 0;
          elsif vcount = 0 then
            labelDelete := 0;
          end if;

        else
          labelRenew  := 0;
          labelDelete := 0;

        end if;
      when 2 then
        select iseditable
        into labelCheck
        from work_stages_dic
        where workstageid = vStage
        and messagetype = vType;
        --его можно было бы удалить(ели настроить OriginalDocGuid)
        labelRenew := 0;
        select count(*)
        into vcount
        from mess_cfm_announce_info mc_an_info
        where mc_an_info.mess_number = pMessDocNumber
        and mc_an_info.mess_type = 4;
        if vcount <> 0 then
          labelDelete := 0;
        end if;
      when 3 then
        select iseditable
        into labelCheck
        from work_stages_dic
        where workstageid = vStage
        and messagetype = vType;
        --его можно было бы удалить(ели настроить OriginalDocGuid)
        labelRenew := 0;
        select count(*)
        into vcount
        from mess_cfm_announce_info mc_an_info
        where mc_an_info.mess_number = pMessDocNumber
        and mc_an_info.mess_type = 4;
        if vcount <> 0 then
          labelDelete := 0;
        end if;
      when 4 then
        labelCheck := 0;
        --его можно было бы удалить(ели настроить OriginalDocGuid)
        labelRenew  := 0;
        labelDelete := 0;
    end case;

    return result;
  end;

  function GetSendPermission(pMessID in number) return number is
    result    number default 0;
    vStage    number;
    vStatus   number;
    vMessTYpe number;
    vSendDate date;
    vCount    number;
  begin
    --IsSendable:=0;
    select mc.mess_type,
           mc.stage,
           mc.status,
           mc.send_date
    into vMessTYpe,
         VStage,
         vStatus,
         vSendDate
    from mess_cfm mc
    where mc.mess_cfm_id = pMessID;

    if (vMesstype in (4, 8, 10, 12, 13, 14)) then
      return - 520; --не предусмотерно
    elsif vMesstype in (1, 5, 11) and vStatus = 20 then
      return - 522; --исключено
    elsif vMesstype in (1, 5) and vStage in (1, 10) then
      return - 521; --
    elsif vMesstype in (1, 5, 11) and vStage = 30 then
      -- за сутки проверить квитанцию!!!!!
      return - 523;
    elsif vMesstype = 1 and vStage = 40 then
      return - 524;
    elsif vMesstype in (5, 11) and vStage = 40 then
      return - 529;
    elsif vMesstype = 1 and vStage = 50 then
      return - 525;
    elsif vMesstype in (5, 11) and vStage = 50 then
      return - 530;
    elsif vMesstype = 9 and vStage = 30 then
      return - 523;
    elsif vMesstype = 3 and vSendDate is not null then
      return - 527; --данное сообщение уже было отклонено
    elsif vMesstype in (1, 5) then
      select count(*)
      into vCount
      from mess_cfm mc
      where mc.mess_type = 14;
      if vCount = 0 then
        return - 532; --СФМ не зарегистрирован. Сформируйте и отправьте запрос регистрации, дождитеь прихода извещения об одобрении регистрации
      end if;
    end if;
    return result;
  exception
    when no_data_found then
      return - 1000;

      return result;
  end;

  function GetEditableField(pMessID number) return number is
    vType   number;
    vStage  number;
    vStatus number;
    -- vMessDocType number;
    piseditable number default 1;

  begin

    --result:=pkg_users.GetUsersRolesGroup(vrolegroup);
    -- vrolegroup:=4;

    select mc.mess_type,
           mc.stage,
           mc.status
    into vType,
         vStage,
         vStatus
    from mess_cfm mc
    where mc.mess_cfm_id = pMessID; --and mc_xml.mess_cfm_id = pMessID and mc_an.mess_cfm_id = pMessID;

    select iseditable
    into pIsEditable
    from work_stages_dic
    where workstageid = vStage
    and messagetype = vType;
    if piseditable = 1 then
      -- if vstatus=10 and bitand(vrolegroup,);
      --   if bitand(vRoleGroup,4) = 0 then piseditable:=0;
      if vStatus = 20 then
        piseditable := 0;
      end if;
    end if;

    return piseditable;
  exception
    when NO_DATA_FOUND then

      Return 1; --Стадия обработки сообщения или его тип задан неверно
  end;

  function GetMessNumber(pMessID in number) return number is
    result  number default 0;
    vmessid number default 0;

  begin
    result := GetFirstNodeID(pMessID, vmessid);
    select mc_an_info.mess_number
    into result
    from mess_cfm mc
    join mess_cfm_announce_info mc_an_info
    on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
    where mc.mess_cfm_id = vmessid
    and mc.mess_type = 1;

    return result;
  exception
    when no_data_found then
      return null;
    when others then
      return null;
  end;

  function GetMessOperNumber(pMessID in number) return varchar2 is
    result  varchar2(1000 char);
    vmessid number default 0;
  begin
    result := GetFirstNodeID(pMessID, vmessid);
    select mc_an_oper.oper_number
    into result
    from mess_cfm mc
    join mess_cfm_announce_oper mc_an_oper
    on (mc.mess_cfm_id = mc_an_oper.mess_cfm_id)
    where mc.mess_cfm_id = vmessid
    and mc.mess_type = 1;

    return result;
  exception
    when no_data_found then
      return null;
    when others then
      return null;
  end;

  function GetCFMCodeNumber(pMessID in number) return number is
    result  number default 0;
    vmessid number default 0;

  begin
    result := GetFirstNodeID(pMessID, vmessid);
    select mc_an_subj.cfm_code
    into result
    from mess_cfm mc
    join mess_cfm_announce_subj mc_an_subj
    on (mc.mess_cfm_id = mc_an_subj.mess_cfm_id)
    where mc.mess_cfm_id = vmessid
    and mc.mess_type = 1;

    return result;
  exception
    when no_data_found then
      return null;
    when others then
      return null;
  end;

  function GetCFMName(pMessID in number) return varchar2 is
    result  varchar2(2000);
    vmessid number default 0;
    KFM constant varchar2(100 char) := 'Комитет финансового мониторинга';
    ptype    number;
    ppartype number default 0;
  begin
    ptype := GetMessageType(pMessID);
    if ptype in (4, 8, 10) then
      return KFM;
    else
      if ptype in (2, 3) then
        ppartype := GetMessageType(pMessID);
        if ppartype in (1, 5) then
          return KFM;
        end if;
      end if;
      result := GetFirstNodeID(pMessID, vmessid);

      select nvl(mc_an_subj.cfm_name, mc.sender)
      into result
      from mess_cfm mc
      left join mess_cfm_announce_subj mc_an_subj
      on (mc.mess_cfm_id = mc_an_subj.mess_cfm_id)
      where mc.mess_cfm_id = vmessid
      and mc.mess_type = 1;
    end if;

    return result;
  exception
    when no_data_found then
      return null;
  end;

  function GetMessReason(messreason   in number,
                         suspicreason in number,
                         messversion  varchar2) return number is
    result number := 0;
  begin
    case messversion
      when '52FF370C-8B35-42DA-9B9A-B48F44F10C6F' then
        result := messreason;
      when ('E5505800-A19B-47ED-AF5F-9A8BAF169E52') then
        if messreason = 1 then
          result := 1;
        elsif messreason = 2 then
          if suspicreason = 3 then
            result := 2;
          elsif suspicreason = 1 then
            result := 3;
          elsif suspicreason = 2 then
            result := 3;
          end if;
        end if;
      when 'C6EC3F8D-2BE1-46A9-841B-5CF1130F0A12' then
        if messreason = 1 then
          result := 1;
        elsif messreason = 2 then
          if suspicreason = 3 then
            result := 2;
          elsif suspicreason = 1 then
            result := 3;
          elsif suspicreason = 2 then
            result := 3;
          end if;
        end if;
      else
        null;
    end case;
    return result;
  end;

  function GetStatusDescription(pstatus in number,
                                pstage  in number,
                                ptype   in number) return nvarchar2 is
    vstatusname nvarchar2(120);
    vlangname   varchar2(30 char);
  begin
    vlangname := pkg_main.GetUserLangSettings;
    case vlangname
      when 'Russian' then
        vstatusname := GetStatusDescriptionRus(pstatus, pstage, ptype);

      when 'Kazakh' then
        vstatusname := GetStatusDescriptionKz(pstatus, pstage, ptype);
        /*when 'English' then
        select descr_en
          into vstatusname
          from messages_list_descr
         where tablename = vMessTAble
           and stagesid = pstage
           and statusid = pstatus
           and doctype = ptype;*/

      else
        vstatusname := GetStatusDescriptionRus(pstatus, pstage, ptype);
    end case;
    return vstatusname;
  exception
    when no_data_found then
      return null;

  end;
  function GetStatusDescriptionRus(pstatus in number,
                                   pstage  in number,
                                   ptype   in number) return varchar2 is
    vstatusname nvarchar2(120);
    vMessTAble  varchar2(15 char) := 'MESSAGES_CFM';

  begin
    select descr_rus
    into vstatusname
    from messages_list_descr
    where tablename = vMessTAble
    and stagesid = pstage
    and statusid = pstatus
    and doctype = ptype;
    return vstatusname;
  exception
    when no_data_found then
      return null;

  end;

  function GetStatusDescriptionKz(pstatus in number,
                                  pstage  in number,
                                  ptype   in number) return nvarchar2 is
    vstatusname nvarchar2(120);
    vMessTAble  varchar2(15 char) := 'MESSAGES_CFM';
  begin
    select descr_kaz
    into vstatusname
    from messages_list_descr
    where tablename = vMessTAble
    and stagesid = pstage
    and statusid = pstatus
    and doctype = ptype;
    return vstatusname;
  exception
    when no_data_found then

      return null;

  end;

  function GetStatusDescriptionByID(pMessID in number) return varchar2 is
    result varchar2(1000 char);
  begin
    select GetStatusDescription(status, stage, mess_type)
    into result
    from mess_cfm
    where mess_cfm_id = pMessID;
    return result;
  exception
    when no_data_found then
      return - 1000;
    when others then
      return - 1;
  end;

  function GetcountOfFounders(pMessID   number,
                              pmemberid number) return number is
    result number default 0;
  begin
    select count(*)
    into result
    from mess_cfm_announce_found mf
    where mf.mess_cfm_id = pMessID
    and mf.member_id = pmemberid;
    return result;
  end;

  procedure InsertEnchanceData(pMessID number) is
  begin
    insert into mess_cfm_exec
      (mess_cfm_id,
       cfm_code,
       oper_idtype,
       oper_idview,
       oper_number,
       oper_currency_code,
       oper_currency_amount,
       oper_tenge_amount,
       oper_doc_name,
       oper_doc_number,
       update_version,
       release_date,
       mess_number,
       mess_doctype,
       mess_reason,
       statusname,
       statusname_kz,
       oper_status,
       cfm_name)
      select mc.mess_cfm_id,
             pkg_messages_cfm.GetCFMCodeNumber(mc.mess_cfm_id),
             mc_an_oper.oper_idtype,
             mc_an_oper.oper_idview,
             pkg_messages_cfm.GetMessOperNumber(mc.mess_cfm_id),
             mc_an_oper.oper_currency_code,
             mc_an_oper.oper_currency_amount,
             mc_an_oper.oper_tenge_amount,
             mc_an_oper.oper_reason,
             mc_an_oper.oper_doc_date || ' №' || mc_an_oper.oper_doc_number,
             mc_up_info.update_version,
             mc_up_info.release_date,
             pkg_messages_cfm.GetMessNumber(mc.mess_cfm_id),
             mc_an_info.mess_type,
             pkg_messages_cfm.GetMessReason(mc_an_info.mess_reason_code, mc_an_info.mess_suspic_code, mc.mess_version),
             pkg_messages_cfm.GetStatusDescriptionRUS(mc.status, mc.stage, mc.mess_type),
             pkg_messages_cfm.GetStatusDescriptionKZ(mc.status, mc.stage, mc.mess_type),
             mc_an_info.mess_oper_status,
             null
      from mess_cfm mc
      left join mess_cfm_announce_info mc_an_info
      on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
      left join mess_cfm_announce_oper mc_an_oper
      on (mc.mess_cfm_id = mc_an_oper.mess_cfm_id)
      left join mess_cfm_update_info mc_up_info
      on (mc.mess_cfm_id = mc_up_info.mess_cfm_id)
      where mc.mess_cfm_id = pMessID;

  end;

  procedure UpdateEnchanceData(pMessID number) is
    pmess_cfm_exec_row mess_cfm_exec%rowtype default null;
  begin
    select mc.mess_cfm_id,
           pkg_messages_cfm.GetCFMCodeNumber(mc.mess_cfm_id),
           mc_an_oper.oper_idtype,
           mc_an_oper.oper_idview,
           pkg_messages_cfm.GetMessOperNumber(mc.mess_cfm_id),
           mc_an_oper.oper_currency_code,
           mc_an_oper.oper_currency_amount,
           mc_an_oper.oper_tenge_amount,
           mc_an_oper.oper_reason,
           mc_an_oper.oper_doc_date || ' №' || mc_an_oper.oper_doc_number,
           mc_up_info.update_version,
           mc_up_info.release_date,
           pkg_messages_cfm.GetMessNumber(mc.mess_cfm_id),
           mc_an_info.mess_type,
           pkg_messages_cfm.GetMessReason(mc_an_info.mess_reason_code, mc_an_info.mess_suspic_code, mc.mess_version),
           pkg_messages_cfm.GetStatusDescriptionRUS(mc.status, mc.stage, mc.mess_type),
           pkg_messages_cfm.GetStatusDescriptionKZ(mc.status, mc.stage, mc.mess_type),
           mc_an_info.mess_oper_status,
           null
    into pmess_cfm_exec_row
    from mess_cfm mc
    left join mess_cfm_announce_info mc_an_info
    on (mc.mess_cfm_id = mc_an_info.mess_cfm_id)
    left join mess_cfm_announce_oper mc_an_oper
    on (mc.mess_cfm_id = mc_an_oper.mess_cfm_id)
    left join mess_cfm_update_info mc_up_info
    on (mc.mess_cfm_id = mc_up_info.mess_cfm_id)
    where mc.mess_cfm_id = pMessID;

    update mess_cfm_exec
    set cfm_code              = pmess_cfm_exec_row.cfm_code,
        oper_idtype           = pmess_cfm_exec_row.oper_idtype,
        oper_idview           = pmess_cfm_exec_row.oper_idview,
        oper_number           = pmess_cfm_exec_row.oper_number,
        oper_currency_code   = pmess_cfm_exec_row.oper_currency_code,
        oper_currency_amount = pmess_cfm_exec_row.oper_currency_amount,
        oper_tenge_amount     = pmess_cfm_exec_row.oper_tenge_amount,
        oper_doc_name         = pmess_cfm_exec_row.oper_doc_name,
        oper_doc_number       = pmess_cfm_exec_row.oper_doc_number,
        update_version        = pmess_cfm_exec_row.update_version,
        release_date          = pmess_cfm_exec_row.release_date,
        mess_number           = pmess_cfm_exec_row.mess_number,
        mess_doctype          = pmess_cfm_exec_row.mess_doctype,
        mess_reason           = pmess_cfm_exec_row.mess_reason,
        statusname            = pmess_cfm_exec_row.statusname,
        statusname_kz         = pmess_cfm_exec_row.statusname_kz,
        cfm_name              = pmess_cfm_exec_row.cfm_name,
        oper_status           = pmess_cfm_exec_row.oper_status
    where mess_cfm_id = pMessID;
  end;

  procedure UpdateEnchanceStatusName(pMessID number) is
    pmess_cfm_exec_row_statusname mess_cfm_exec.statusname%type;
    Pstatusname_kz                mess_cfm_exec.statusname_kz%type;
  begin
    select pkg_messages_cfm.GetStatusDescriptionRUS(mc.status, mc.stage, mc.mess_type),
           pkg_messages_cfm.GetStatusDescriptionKz(mc.status, mc.stage, mc.mess_type)
    into pmess_cfm_exec_row_statusname,
         Pstatusname_kz
    from mess_cfm mc
    where mc.mess_cfm_id = pMessID;

    update mess_cfm_exec
    set statusname    = pmess_cfm_exec_row_statusname,
        statusname_kz = Pstatusname_kz
    where mess_cfm_id = pMessID;

  end;

  function GetOuterAnnounceXML_1(PXMLSCH xmltype) return xmltype is
    pXML    xmltype;
    pXMLOut xmltype;
  begin
    begin
      select updateXml(PXMLSCH,
                       'Root/PersonalData/OrganisationCode/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/PersonalData/OrganisationCode/text()'), 1005),
                       'Root/MessageInformation/IDViewOperation/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/IDViewOperation/text()'), 1004),
                       'Root/MessageInformation/IDTypeOperation/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/IDTypeOperation/text()'), 1017),
                       'Root/MessageInformation/CurrencyCode/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/CurrencyCode/text()'), 1018),
                       'Root/MessageInformation/SubmissionsBasises/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/SubmissionsBasises/text()'), 1011),
                       'Root/MessageInformation/SuspicionsCriterians/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/SuspicionsCriterians/text()'), 1012),
                       'Root/MessageInformation/ReportsType/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/ReportsType/text()'), 1009),
                       'Root/MessageInformation/OperationStatuses/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/OperationStatuses/text()'), 1010)
                       --  'Root/ParticipantsList/Participant[1]/ParticipantOperation/text()',
                       --        pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/ParticipantsList/Participant[1]/ParticipantOperation/text()'),1013)
                       )
      into pXML
      from dual;
    exception
      when others then
        pXML := PXMLSCH;
    end;
    pXMLOut := pXML;
    begin
      select updateXml(pXMLOut,
                       'Root/MessageInformation/SuspicionsCriterians/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/SuspicionsCriterians/text()'), 1012),
                       'Root/MessageInformation/SuspicionFirst/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/SuspicionFirst/text()'), 1008),
                       'Root/MessageInformation/SuspicionSecond/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/SuspicionSecond/text()'), 1008),
                       'Root/MessageInformation/SuspicionThird/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/SuspicionThird/text()'), 1008)
                       --  'Root/ParticipantsList/Participant[1]/ParticipantOperation/text()',
                       --        pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/ParticipantsList/Participant[1]/ParticipantOperation/text()'),1013)
                       )
      into pXML
      from dual;
    exception
      when others then
        pXML := pXMLOut;
    end;
    return pXML;
  end;

  function GetOuterRegistrationData_1(PXMLSCH xmltype) return xmltype is
    pXML    xmltype;
    pXMLOut xmltype;
    i       number;
  begin
    begin
      select updateXml(PXMLSCH,
                       'Root/OrganisationData/CfmCode/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/OrganisationData/CfmCode/text()'), 31005),
                       'Root/OrganisationData/OpfCode/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/OrganisationData/OpfCode/text()'), 31003),
                       'Root/OrganisationData/AdditionalAcData[@IsAc=''True'']/DocumentIdentity/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/OrganisationData/AdditionalAcData[@IsAc=''True'']/DocumentIdentity/text()'), 20100)
                       --  'Root/ParticipantsList/Participant[1]/ParticipantOperation/text()',
                       --        pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/ParticipantsList/Participant[1]/ParticipantOperation/text()'),1013)
                       )
      into pXML
      from dual;
    exception
      when others then
        pXML := PXMLSCH;
    end;
    pXMLOut := pXML;
    i       := 1;
    begin
      loop
        if (xmltype.existsNode(pxml, 'Root/OrganisationData/Founders/Founder[' || to_char(i) || ']') = 1) then
          select updateXml(pXMLOut,
                           'Root/OrganisationData/Founders/Founder[' || to_char(i) || ']/FounderType/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/OrganisationData/Founders/Founder[' || to_char(i) || ']/FounderType/text()'), 10),
                           'Root/OrganisationData/Founders/Founder[' || to_char(i) || ']/OpfCode/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/OrganisationData/Founders/Founder[' || to_char(i) || ']/OpfCode/text()'), 31003),
                           'Root/OrganisationData/Founders/Founder[' || to_char(i) || ']/ResidenceCode/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/OrganisationData/Founders/Founder[' || to_char(i) || ']/ResidenceCode/text()'), 21019))
          into pXML
          from dual;
        else
          exit;
        end if;
        pXMLOut := pxml;
        i       := i + 1;
      end loop;
    exception
      when others then
        pXML := pXMLOut;
    end;
    return pXML;
  end;
  --------------------------------------------------------------------------------
  --
  procedure Copy_Info(pMessID in number) as
    vUser     users%rowtype;
    vPassport passport_cfm%rowtype;
  begin
    select *
    into vUser
    from users u
    where u.userid = pkg_users.GetCurrentUserId;

    UPDATE mess_cfm_announce_cont
    SET contact_secondname = vUser.lastname,
        contact_firstname  = vUser.firstname,
        contact_middlename = vUser.middlename,
        contact_job        = vUser.jobname,
        contact_phone      = vUser.phones,
        contact_email      = vUser.emails
    WHERE MESS_CFM_ID = pMessID;

    select *
    into vPassport
    from passport_cfm;

    UPDATE mess_cfm_announce_subj
    SET CFM_CODE      = vPassport.CFMCODE,
        CFM_NAME      = vPassport.FULLNAME,
        CFM_TAXCODE   = vPassport.TAXCODE,
        CFM_MAINCODE  = vPassport.MAINCODE,
        CFM_SEAT_AREA = vPassport.REG_AREA,

        CFM_SEAT_REGION = vPassport.REG_DISTRICT,
        CFM_SEAT_SITY   = vPassport.REG_CITY,
        CFM_SEAT_STREET = vPassport.REG_STREET,
        CFM_SEAT_HOUSE  = vPassport.REG_HOUSE,
        CFM_SEAT_OFFICE = vPassport.REG_OFFICE,

        CFM_ISAC          = vPassport.PASSPORT_STATUS,
        CFM_SEAT_POSTCODE = vPassport.REG_POSTINDEX,
        CFM_DOC_TYPECODE  = vPassport.AC_DOC_TYPECODE,
        CFM_DOC_NUMBER    = vPassport.AC_DOC_NUMBER,
        CFM_DOC_SERIES    = vPassport.AC_DOC_SERIES,
        CFM_DOC_WHOM      = vPassport.AC_DOC_WHOM,

        CFM_DOC_DATE         = vPassport.AC_DOC_DATE,
        CFM_SEAT_AREA_CODE   = vPassport.REG_AREA_CODE,
        CFM_SEAT_REGION_CODE = vPassport.REG_DISTRICT_CODE,
        CFM_SEAT_SITY_CODE   = vPassport.REG_CITY_CODE,
        CFM_SEAT_STREET_CODE = vPassport.REG_STREET_CODE,

        CFM_SEAT_HOUSE_CODE  = vPassport.REG_HOUSE_CODE,
        CFM_SEAT_OFFICE_CODE = vPassport.REG_OFFICE_CODE,
        CFM_UR_OPF_CODE      = vPassport.ORGCODE,
        CFM_AC_FIRSTNAME     = vPassport.FIRSTNAME,
        CFM_AC_MIDDLENAME    = vPassport.MIDDLENAME,
        CFM_AC_SECONDNAME    = vPassport.SECONDNAME
    WHERE MESS_CFM_ID = pMessID;
  end;
  --
  --создает новый пустой документ и заполняет его константами
  function Prepare_Save(pMessID out number) return number as
    pMessXML CLOB;

    result          number default 0;
    vCount          number default 0;
    vRes            number default 0; -- Временный результат промежуточных проверок
    vMess_cfm       mess_cfm%rowtype; -- Строка ключевой информации
    vMessId         number; -- ID связанного сообщения
    vMessageVersion varchar2(50 char); -- Версия сообщения (из XML)
    vMessageGuid    varchar2(50 char); -- Guid сообщения (из XML)
    vCFMMessageDoc  varchar2(50 char); -- Версия оригинального сообщения (из XML)
    vXML            xmltype;
    vRootNode       clob; -- Сообщение без пакета
    pVersionId      number; -- ID версии сообщения
  begin
    --сбор сообщения
    pMessXML := PKG_MESS_CFM_2_1.mess_cfm_2_empty_xml().getclobval();
    --Распаковка из конверта
    result := pkg_messages_xml.Get_RootNodeFromXML(pMessXML, vRootNode);
    if result <> 0 then
      return result; -- -305 или -307 (not valid или узел не найден)
    end if;

    vXML := XMLTYPE.createxml(vRootNode); --Главная ветка

    --Преобразование, проверка и сохранение версии документа
    Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'Version', vMessageVersion);
    if Result <> 0 then
      return Result;
    end if;
    vres := pkg_common.GetFormattedGuid(vMessageVersion, vMess_cfm.Mess_Version);
    if vres <> 0 then
      return - 1301; -- Неверный формат идентификационного номера версии документа
    else
      begin
        select mv.mess_type,
               versionid
        into vMess_cfm.Mess_Type,
             pVersionId --Тип сообщения
        from messages_versions mv
        where mv.versioncode = vMess_cfm.Mess_Version;
      exception
        when others then
          return - 306; --Неверная версия сообщения. Сообщение не сохранено.
          vMess_cfm.Mess_Type := -1;
      end;
    end if;

    --Преобразование, проверка и сохранение GUID документа
    Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'DocumentUniqueIdentifier', vMess_cfm.Mess_Docid);
    if Result <> 0 then
      return Result;
    end if;
    vres := pkg_common.GetFormattedGuid(vMess_cfm.Mess_Docid, vMess_cfm.Mess_Form_Guid);
    if vres <> 0 then
      return - 1302; --  Неверный формат идентификационного номера документа
    else
      select count(*)
      into vcount
      from mess_cfm
      where Mess_Form_Guid = vMess_cfm.Mess_Form_Guid;
      if vcount > 0 then
        return - 1003; --Сообщение с данным уникальным идентификатором  уже находится в базе
      end if;
    end if;
    --Сохранение в основной таблице
    vMess_cfm.Status       := 1;
    vMess_cfm.Stage        := 1;
    vMess_cfm.Receive_Date := sysdate;
    vMess_cfm.Ext_Err_Code := -1;
    insert into mess_cfm
    values vMess_cfm
    returning mess_cfm_id into pMessID;
    insert into mess_cfm_xml
      (mess_cfm_id,
       mess_xml)
    values
      (pMessID,
       vRootNode);
    --commit;

    result := pkg_messages_cfm.ChangeStatus(pMessID, 1, 1);
    result := pkg_mess_cfm_2.parseAnnounceXML(pMessID, 3);
    pkg_messages_cfm.InsertEnchanceData(pMessID);

    Copy_Info(pMessID);
    return result;
  exception
    when others then
      pMessID := null;
      --dbms_output.put_line(sqlerrm);
      return - 2100; --Ошибка операции сохранения
  end;
  --отменяет создание нового документа удаляя документ
  function Cancel_Save(pMessID in number) return number as
  begin
    delete from mess_cfm_announce_info
    where mess_cfm_id = pMessID;
    delete from mess_cfm_announce_cont
    where mess_cfm_id = pMessID;
    delete from mess_cfm_announce_found
    where mess_cfm_id = pMessID;
    delete from mess_cfm_announce_memb
    where mess_cfm_id = pMessID;
    delete from mess_cfm_announce_oper
    where mess_cfm_id = pMessID;
    delete from mess_cfm_announce_subj
    where mess_cfm_id = pMessID;
    delete from mess_cfm_announce_accounts
    where mess_cfm_id = pMessID;
    delete from mess_cfm_xml
    where mess_cfm_id = pMessID;
    delete from mess_cfm_exec
    where mess_cfm_id = pMessID;
    delete from mess_cfm
    where mess_cfm_id = pMessID;

    return 0;

  exception
    when others then
      return - 2102; --Ошибка операции отмены создания документа
  end;
  --подготавливает редактирование нового документа, заполняя необходимые контснаты
  function Prepare_Update(pMessID in number) return number as
    pMessXML CLOB;

    Result          number default 0;
    vcount          number default 0;
    vRes            number default 0; -- Временный результат промежуточных проверок
    vMess_cfm       mess_cfm%rowtype; -- Строка ключевой информации
    vMessageVersion varchar2(50 char); -- Версия сообщения (из XML)
    vCFMMessageDoc  varchar2(50 char); -- Версия оригинального сообщения (из XML)
    vMessageGuid    varchar2(50 char); -- Guid сообщения (из XML)
    vMessGuid       varchar2(50 char); -- Guid сообщения (из БД)
    vXML            xmltype;
    vRootNode       clob; -- Сообщение без пакета
    vStage          number; -- Стадия обработки сообщения
    vStatus         number; -- Статус сообщения
    vMessType       number; -- Тип сообщения
    pversionid      number; -- ID версии сообщения

    l_mess_number varchar(255);

    vUser users%rowtype;
  begin
    select *
    into vUser
    from users u
    where u.userid = pkg_users.GetCurrentUserId;

    UPDATE mess_cfm_announce_cont
    SET contact_secondname = vUser.lastname,
        contact_firstname  = vUser.firstname,
        contact_middlename = vUser.middlename,
        contact_job        = vUser.jobname,
        contact_phone      = vUser.phones,
        contact_email      = vUser.emails
    WHERE MESS_CFM_ID = pMessID;

    Result := 0;

    update mess_cfm_announce_oper
    set oper_refers_count =
        (select count(*)
         from mess_cfm_refer
         where mess_cfm_id = pMessID)
    where mess_cfm_id = pMessID;

    select count(*)
    into vcount
    from mess_cfm
    where mess_cfm_id = pMessID;
    if vcount = 0 then
      return - 1000; --Сообщение не найдено
    end if;

    select mc.mess_type,
           mc.status,
           mc.stage,
           mc.mess_form_guid
    into vMessType,
         vStatus,
         vStage,
         vMessGuid
    from mess_cfm mc
    where mess_cfm_id = pMessID;

    --сбор сообщения
    pMessXML := PKG_MESS_CFM_2_1.mess_cfm_2_xml(pMessID).getclobval();
    --Распаковка из конверта
    result := pkg_messages_xml.Get_RootNodeFromXML(pMessXML, vRootNode);
    if result <> 0 then
      return result; -- -305 или -307 (not valid или узел не найден)
    end if;

    vXML := xmltype.createxml(vRootNode);

    --Преобразование, проверка и сохранение версии документа
    Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'Version', vMessageVersion);
    if Result <> 0 then
      return Result;
    end if;
    vres := pkg_common.GetFormattedGuid(vMessageVersion, vMess_cfm.Mess_Version);
    if vres <> 0 then
      return - 1301; -- Неверный формат идентификационного номера версии документа
    else
      begin
        select mv.mess_type,
               versionid
        into vMess_cfm.Mess_Type,
             pVersionId --Тип сообщения
        from messages_versions mv
        where mv.versioncode = vMess_cfm.Mess_Version;
      exception
        when others then
          return - 306; --Неверная версия сообщения. Сообщение не сохранено.
          vMess_cfm.Mess_Type := -1;
      end;
    end if;

    --Преобразование, проверка и сохранение GUID документа
    Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'DocumentUniqueIdentifier', vMess_cfm.Mess_Docid);
    if Result <> 0 then
      return Result;
    end if;
    vres := pkg_common.GetFormattedGuid(vMess_cfm.Mess_Docid, vMess_cfm.Mess_Form_Guid);
    if vres <> 0 then
      return - 1302; --  Неверный формат идентификационного номера документа
    else
      ---!!!!!!!!!!!!!!!!!!Если будет доп столбец, то проверять его!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

      if vMess_cfm.Mess_Form_Guid <> vMessGuid then
        return - 1011;
        --!!!!!!!!Оставить вторую ветку, если будет дополнительное поле
      end if;
    end if;

    update mess_cfm_xml
    set mess_xml = vRootNode
    where mess_cfm_id = pMessID;
    commit;

    pkg_messages_cfm.UpdateEnchanceData(pMessID);
    return result;

  exception
    when others then
      return - 2101;
  end;
  --сохраняет отредактированные данные
  function Update_Message(pMessID in number) return number as
    pMessXML CLOB;

    Result          number default 0;
    vcount          number default 0;
    vRes            number default 0; -- Временный результат промежуточных проверок
    vMess_cfm       mess_cfm%rowtype; -- Строка ключевой информации
    vMessageVersion varchar2(50 char); -- Версия сообщения (из XML)
    vCFMMessageDoc  varchar2(50 char); -- Версия оригинального сообщения (из XML)
    vMessageGuid    varchar2(50 char); -- Guid сообщения (из XML)
    vMessGuid       varchar2(50 char); -- Guid сообщения (из БД)
    vXML            xmltype;
    vRootNode       clob; -- Сообщение без пакета
    vStage          number; -- Стадия обработки сообщения
    vStatus         number; -- Статус сообщения
    vMessType       number; -- Тип сообщения
    pversionid      number; -- ID версии сообщения

    l_mess_number varchar(255);
  begin
    Result := 0;

    select mess_number
    into l_mess_number
    from mess_cfm_announce_info
    where mess_cfm_id = pMessID;

    if (l_mess_number is null) or (trim(l_mess_number) = '') then
      begin
        update mess_cfm_announce_info
        set mess_number = pkg_messages_cfm.GetTempMessNumb
        where mess_cfm_id = pMessID;
      end;
    end if;

    update mess_cfm_announce_oper
    set oper_refers_count =
        (select count(*)
         from mess_cfm_refer
         where mess_cfm_id = pMessID)
    where mess_cfm_id = pMessID;

    select count(*)
    into vcount
    from mess_cfm
    where mess_cfm_id = pMessID;
    if vcount = 0 then
      return - 1000; --Сообщение не найдено
    end if;

    select mc.mess_type,
           mc.status,
           mc.stage,
           mc.mess_form_guid
    into vMessType,
         vStatus,
         vStage,
         vMessGuid
    from mess_cfm mc
    where mess_cfm_id = pMessID;

    if (vStage >= 30) then
      return - 531;
    end if;
    --сбор сообщения
    pMessXML := PKG_MESS_CFM_2_1.mess_cfm_2_xml(pMessID).getclobval();
    --Распаковка из конверта
    result := pkg_messages_xml.Get_RootNodeFromXML(pMessXML, vRootNode);
    if result <> 0 then
      return result; -- -305 или -307 (not valid или узел не найден)
    end if;

    vXML := xmltype.createxml(vRootNode);

    --Преобразование, проверка и сохранение версии документа
    Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'Version', vMessageVersion);
    if Result <> 0 then
      return Result;
    end if;
    vres := pkg_common.GetFormattedGuid(vMessageVersion, vMess_cfm.Mess_Version);
    if vres <> 0 then
      return - 1301; -- Неверный формат идентификационного номера версии документа
    else
      begin
        select mv.mess_type,
               versionid
        into vMess_cfm.Mess_Type,
             pVersionId --Тип сообщения
        from messages_versions mv
        where mv.versioncode = vMess_cfm.Mess_Version;
      exception
        when others then
          return - 306; --Неверная версия сообщения. Сообщение не сохранено.
          vMess_cfm.Mess_Type := -1;
      end;
    end if;

    --Преобразование, проверка и сохранение GUID документа
    Result := pkg_messages_xml.Get_FieldFromXML(vXML, 'DocumentUniqueIdentifier', vMess_cfm.Mess_Docid);
    if Result <> 0 then
      return Result;
    end if;
    vres := pkg_common.GetFormattedGuid(vMess_cfm.Mess_Docid, vMess_cfm.Mess_Form_Guid);
    if vres <> 0 then
      return - 1302; --  Неверный формат идентификационного номера документа
    else
      ---!!!!!!!!!!!!!!!!!!Если будет доп столбец, то проверять его!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

      if vMess_cfm.Mess_Form_Guid <> vMessGuid then
        return - 1011;
        --!!!!!!!!Оставить вторую ветку, если будет дополнительное поле
      end if;
    end if;

    update mess_cfm_xml
    set mess_xml = vRootNode
    where mess_cfm_id = pMessID;
    commit;

    pkg_messages_cfm.UpdateEnchanceData(pMessID);
    return result;

  exception
    when others then
      return - 2101;
  end;
  --

  /* Roma */
  function CheckRNN(widget_value in varchar2) return number is
    result    number default 0;
    pSum      number default 0;
    pContr    number default 0;
    pWeight   number default 0;
    pCheckVal varchar2(12) DEFAULT '000000000000';
  begin
    if length(widget_value) <> 12 then
      return - 1;
    elsif widget_value = pCheckVal then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '1') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '2') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '3') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '4') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '5') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '6') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '7') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '8') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '9') then
      return - 2;

    end if;
    begin

      while (pWeight < 10) loop
        pSum := CAST(SUBSTR(widget_value, 1, 1) as int) * (mod(pWeight, 10) + 1) + CAST(SUBSTR(widget_value, 2, 1) as int) * (mod(pWeight + 1, 10) + 1) + CAST(SUBSTR(widget_value, 3, 1) as int) * (mod(pWeight + 2, 10) + 1) +
                CAST(SUBSTR(widget_value, 4, 1) as int) * (mod(pWeight + 3, 10) + 1) + CAST(SUBSTR(widget_value, 5, 1) as int) * (mod(pWeight + 4, 10) + 1) + CAST(SUBSTR(widget_value, 6, 1) as int) * (mod(pWeight + 5, 10) + 1) +
                CAST(SUBSTR(widget_value, 7, 1) as int) * (mod(pWeight + 6, 10) + 1) + CAST(SUBSTR(widget_value, 8, 1) as int) * (mod(pWeight + 7, 10) + 1) + CAST(SUBSTR(widget_value, 9, 1) as int) * (mod(pWeight + 8, 10) + 1) +
                CAST(SUBSTR(widget_value, 10, 1) as int) * (mod(pWeight + 9, 10) + 1) + CAST(SUBSTR(widget_value, 11, 1) as int) * (mod(pWeight + 10, 10) + 1);

        pContr := mod(pSum, 11);
        if Pcontr < 10 then
          IF Pcontr <> CAST(SUBSTR(widget_value, 12, 1) as int) then
            return - 4;
          else
            return 0;
          end if;
        else
          pWeight := pWeight + 1;
        end if;
      end loop;
      return - 5;
    exception
      when others then
        return - 3; --содержит запрещеные символы
    end;

    return result;
  end;
  --
  function checkBIC(widget_value in VARCHAR2) return number as
  begin
    if widget_value = '400' then
      return 1;
    end if;
    if widget_value = '500' then
      return 1;
    end if;
    if widget_value = '600' then
      return 1;
    end if;
    return 0;
  end;
  --
  function checkINN(widget_value in VARCHAR2) return number is
    result    number default 0;
    pSum      number default 0;
    pContr    number default 0;
    pWeight   number default 0;
    pCheckVal varchar2(12) DEFAULT '000000000000';
  begin
    if length(widget_value) <> 12 then
      return - 1;
    elsif widget_value = pCheckVal then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '1') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '2') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '3') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '4') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '5') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '6') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '7') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '8') then
      return - 2;
    elsif widget_value = REPLACE(pCheckVal, '0', '9') then
      return - 2;
    end if;

    begin
      while (pWeight <= 3) loop
        pSum   := CAST(SUBSTR(widget_value, 1, 1) as int) * (mod(pWeight, 11) + 1) + CAST(SUBSTR(widget_value, 2, 1) as int) * (mod(pWeight + 1, 11) + 1) + CAST(SUBSTR(widget_value, 3, 1) as int) * (mod(pWeight + 2, 11) + 1) +
                  CAST(SUBSTR(widget_value, 4, 1) as int) * (mod(pWeight + 3, 11) + 1) + CAST(SUBSTR(widget_value, 5, 1) as int) * (mod(pWeight + 4, 11) + 1) + CAST(SUBSTR(widget_value, 6, 1) as int) * (mod(pWeight + 5, 11) + 1) +
                  CAST(SUBSTR(widget_value, 7, 1) as int) * (mod(pWeight + 6, 11) + 1) + CAST(SUBSTR(widget_value, 8, 1) as int) * (mod(pWeight + 7, 11) + 1) + CAST(SUBSTR(widget_value, 9, 1) as int) * (mod(pWeight + 8, 11) + 1) +
                  CAST(SUBSTR(widget_value, 10, 1) as int) * (mod(pWeight + 9, 11) + 1) + CAST(SUBSTR(widget_value, 11, 1) as int) * (mod(pWeight + 10, 11) + 1);
        pContr := mod(pSum, 11);
        if Pcontr < 10 then
          IF Pcontr <> CAST(SUBSTR(widget_value, 12, 1) as int) then
            return - 4;
          else
            return 0;
          end if;
        else
          pWeight := pWeight + 2;
        end if;
      end loop;
      return - 5;
    exception
      when others then
        return - 3; --содержит запрещеные символы
    end;

    return result;
  end;
  /*Roma*/

FUNCTION CHECKREGION (widget_value IN VARCHAR2) RETURN NUMBER
as
  MESSAGE_COUNT          number default 0;
BEGIN
    BEGIN
        SELECT count(*) INTO MESSAGE_COUNT FROM KATO_REGION_VIEW
                WHERE teparent = widget_value or teparent in
                (select b.TE
                  from KATO b
                        where b.teparent = widget_value
                        group by b.TE);
        IF (MESSAGE_COUNT > 1) THEN RETURN 0; END IF ;
    EXCEPTION
    WHEN OTHERS THEN
        RETURN -1;
    END;
    RETURN -1;
END;

 FUNCTION CHECKCITY (widget_value IN VARCHAR2) RETURN NUMBER
as
  MESSAGE_COUNT          number default 0;
BEGIN
    BEGIN
        SELECT count(*) INTO MESSAGE_COUNT FROM KATO_CITY_VIEW
                WHERE teparent = widget_value or teparent in
                (select b.TE
                  from KATO b
                        where b.teparent = widget_value
                        group by b.TE);
        IF (MESSAGE_COUNT > 1) THEN RETURN 0; END IF ;
    EXCEPTION
    WHEN OTHERS THEN
        RETURN -1;
    END;
    RETURN -1;
END;
  --users
  --if user ol then return > 1 else return 0
  function check_user_ol(widget_value in VARCHAR2) return number as
    l_result number;
  begin
    select count(*)
    into l_result
    from user_roles
    where userid = (select userid
                    from users
                    where userid = pkg_users.GetCurrentUserId)
    and roleid = 4;

    return l_result;
  end;
  --
end PKG_MESSAGES_CFM;
/

CREATE OR REPLACE PACKAGE KFM."PKG_MESS_CFM_1" as
  function ExtractMessInSignedData(pXML      in clob,
                                   pExist    out number,
                                   pSender   out varchar2,
                                   pReceiver out varchar,
                                   pDate     out date) return number;
  function ExtractSignatureData(pXML       in clob,
                                pSignature out clob) return number;

  function ParseMessageInfo(pnode   xmldom.domnode,
                            pmessid in number) return number;
  function ParseCMFInfo(pnode   xmldom.domnode,
                        pmessid in number) return number;
  function ParseCFMContactInfo(pnode   xmldom.domnode,
                               pmessid in number) return number;
  function ParseOperationInfo(pnode   xmldom.domnode,
                              pmessid in number) return number;
  function ParseMemberInfo(pnode     xmldom.domnode,
                           pmessid   in number,
                           pmemberid in number) return number;
  function ParseMembersInfo(pnode   xmldom.domnode,
                            pmessid in number) return number;
  function ParseFounderInfo(pnode      xmldom.domnode,
                            pmessid    in number,
                            pmemberid  in number,
                            pfounderid in number) return number;
  function ParseFoundersInfo(pnode     xmldom.domnode,
                             pmessid   in number,
                             pmemberid in number) return number;

  function parseAnnounceXML(pmessid in number) return number;

  function parseCheckXML(pmessid in number) return number;
  function parseDopInfXML(pmessid in number) return number;
  function parseDopInfAnswXML(pmessid in number) return number;
  function parseUpdateRequestXML(pmessid in number) return number;
  function ParseUpdateInfoXML(pmessid in number) return number;
  function ParseUpdateXML(pmessid in number) return number;
  function SetErrorCode(pmessid  in number,
                        perrcode in number) return number;

end PKG_MESS_CFM_1;
/

CREATE OR REPLACE PACKAGE BODY KFM."PKG_MESS_CFM_1" as
  --length cursor is

  function ExtractMessInSignedData(pXML      in clob,
                                   pExist    out number,
                                   pSender   out varchar2,
                                   pReceiver out varchar,
                                   pDate     out date) return number is
    result number default 0;
    vXML   xmltype;
  begin
    begin
      vXML := xmltype.createxml(pXML);
    exception
      when others then
        return - 305; --Сообщение is not valid
    end;
    select existsNode(vXML, '//ExportData')
    into pExist
    from dual;
    if pExist is null then
      pExist := 0;
    end if;

    select extractvalue(vXML, '/ExportData/SignedData/Sender'),
           extractvalue(vXML, '/ExportData/SignedData/Receiver'),
           to_date(extractvalue(vXML, '/ExportData/SignedData/TimeStamp'), 'dd.mm.yyyy hh24:mi:ss')
    into pSender,
         pReceiver,
         pDate
    from dual;
    return result;
  exception
    when others then
      return - 315; --В сообщении отсутствует информация  об отправителе и получателе
  end;

  function ExtractSignatureData(pXML       in clob,
                                pSignature out clob) return number is
    result number default 0;
    vXML   xmltype;
    outXML xmltype;
  begin
    begin
      vXML := xmltype.createxml(pXML);
    exception
      when others then
        return - 305; --Сообщение is not valid
    end;
    /*  select extractvalue(vXML,'/ExportData/SignedData/Signature')
    into pSignature
    from dual;*/
    select extract(vXML, '/ExportData/SignedData/Signature/text()')
    into outXML
    from dual;

    if outXML is null then
      pSignature := null;
    else
      pSignature := outXml.getclobval();
    end if;

    return result;
  exception
    when others then
      return - 316; --В сообщении отсутствует информация  об отправителе и получателе
  end;

  /*
  function ExtractMessOutSignedData(pXML in clob, pSender out varchar2,pReceiver out varchar, pDate out date) return number
  is
   result number default 0;
   vXML xmltype;
  begin
    begin
        vXML:=xmltype.createxml(pXML);
    exception
     when others then
        return -305; --Сообщение is not valid
    end;

    select extractvalue(vXML,'/ExportData/SignedData/Sender'),
           extractvalue(vXML,'/ExportData/SignedData/Receiver'),
           to_date(extractvalue(vXML,'/ExportData/SignedData/TimeStamp'),'dd.mm.yyyy HH24:mi:ss')
      into pReceiver,
           pSender,
           pDate
      from dual;
   return result;
  exception
   when others then
    return -315;--В сообщении отсутствует информация  об отправителе и получателе
  end;
  */

  function ParseMessageInfo(pnode   xmldom.domnode,
                            pmessid in number) return number is
    result    number default 0;
    vMess     mess_cfm_announce_info%rowtype;
    pmessdate date;

  begin
    select send_date
    into pmessdate
    from mess_cfm
    where mess_cfm_id = pmessid; -- Пока нету в сообщении, затем изменить
    vMess.mess_cfm_id      := pmessid;
    vMess.mess_number      := pkg_messages_xml.getsingleval(pnode, 'MessageInformation/MessageNumber');
    vMess.mess_date        := to_date(pkg_messages_xml.getsingleval(pnode, 'MessageInformation/LastModifyDate'), 'yyyy-mm-dd'); --pmessdate; -- Выдергивать напрямую из XML
    vMess.mess_type        := pkg_messages_xml.getsingleval(pnode, 'MessageInformation/ReportsType');
    vMess.mess_oper_status := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/OperationStatuses');
    vMess.mess_reason_code := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/SubmissionsBasises');
    vMess.mess_suspic_code := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/SuspicionsCriterians');

    insert into mess_cfm_announce_info
    values vMess;
    return result;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      return - 1000; --Сообщение не найдено
    WHEN OTHERS THEN
      return - 3004; --- 6001; --  Ошибка экпорта данных о сообщении по причине их неверного формата

  end;

  function ParseCMFInfo(pnode   xmldom.domnode,
                        pmessid in number) return number is
    result number default 0;
    vCFM   mess_cfm_announce_subj%rowtype;
  begin
    vCFM.mess_cfm_id       := pmessid;
    vCFM.cfm_code          := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationCode');
    vCFM.cfm_name          := pkg_messages_xml.getsingleval(pnode, 'PersonalData/Organisation');
    vCFM.cfm_taxcode       := pkg_messages_xml.getsingleval(pnode, 'PersonalData/RNN');
    vCFM.cfm_maincode      := pkg_messages_xml.getsingleval(pnode, 'PersonalData/IINBIN');
    vCFM.cfm_seat_area     := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationArea');
    vCFM.cfm_seat_region   := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationDistrict');
    vCFM.cfm_seat_sity     := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationSity');
    vCFM.cfm_seat_street   := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationStreet');
    vCFM.cfm_seat_house    := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationHouse');
    vCFM.cfm_seat_office   := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationOffice');
    vCFM.cfm_seat_postcode := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationPostalIndex');
    vCFM.CFM_AC_FIRSTNAME  := pkg_messages_xml.getsingleval(pnode, 'PersonalData/HeadName');
    vCFM.CFM_AC_SECONDNAME := pkg_messages_xml.getsingleval(pnode, 'PersonalData/HeadSurname');
    vCFM.CFM_AC_MIDDLENAME := pkg_messages_xml.getsingleval(pnode, 'PersonalData/HeadMidleName');
    insert into mess_cfm_announce_subj
    values vcfm;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3001; ---6000; --Ошибка экпорта данных о субъекте, подающем отчет, по причине их неверного формата

  end;

  function ParseCFMContactInfo(pnode   xmldom.domnode,
                               pmessid in number) return number is
    result     number default 0;
    vCFMConact mess_cfm_announce_cont%rowtype;
  begin
    vCFMConact.mess_cfm_id        := pmessid;
    vCFMConact.contact_secondname := pkg_messages_xml.getsingleval(pnode, 'PersonalData/FirstName');
    vCFMConact.contact_firstname  := pkg_messages_xml.getsingleval(pnode, 'PersonalData/SecondName');
    vCFMConact.contact_middlename := pkg_messages_xml.getsingleval(pnode, 'PersonalData/MiddleName');
    vCFMConact.contact_job        := pkg_messages_xml.getsingleval(pnode, 'PersonalData/JobName');
    vCFMConact.contact_phone      := pkg_messages_xml.getsingleval(pnode, 'PersonalData/Phone');
    vCFMConact.contact_email      := pkg_messages_xml.getsingleval(pnode, 'PersonalData/Email');
    insert into mess_cfm_announce_cont
    values vcfmconact;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3002; ---6002; --Ошибка экпорта данных о контактном лице субъекта по причине их неверного формата
  end;

  function ParseOperationInfo(pnode   xmldom.domnode,
                              pmessid in number) return number is
    result     number default 0;
    vOperation mess_cfm_announce_oper%rowtype;
  begin
    vOperation.mess_cfm_id           := pmessid;
    vOperation.oper_number           := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/OperationNumber');
    vOperation.oper_idview           := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/IDViewOperation');
    vOperation.oper_idtype           := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/IDTypeOperation');
    vOperation.oper_members_count    := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/ParticipantCount');
    vOperation.oper_currency_code   := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/CurrencyCode');
    vOperation.oper_currency_amount := pkg_common.ConvertToNumber(pkg_messages_xml.getsingleval(pNode, 'MessageInformation/AmountCurrency'));
    vOperation.oper_tenge_amount     := pkg_common.ConvertToNumber(pkg_messages_xml.getsingleval(pNode, 'MessageInformation/AmountCurrencyTenge'));
    vOperation.oper_reason           := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/DocOperationName');
    vOperation.oper_doc_date         := to_date(pkg_messages_xml.getsingleval(pNode, 'MessageInformation/DocOperationDate'), 'yyyy-mm-dd');
    vOperation.oper_doc_number       := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/DocOperationNumber');
    vOperation.oper_susp_first       := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/SuspicionFirst');
    vOperation.oper_susp_second      := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/SuspicionSecond');
    vOperation.oper_susp_third       := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/SuspicionThird');
    vOperation.oper_difficulties     := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/DescriptionDifficulties');
    vOperation.oper_dopinfo          := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/MoreInformation');
    insert into mess_cfm_announce_oper
    values vOperation;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3000; ---6003; --Ошибка экпорта данных об операции причине их неверного формата
      return result;
  end;

  function ParseMemberInfo(pnode     xmldom.domnode,
                           pmessid   in number,
                           pmemberid in number) return number is
    result      number default 0;
    pMember     mess_cfm_announce_memb%rowtype;
    pAcInfoPath varchar2(50 char) := 'AdditionalPersonInfo/AdditionalInformationAc/';
    pIpInfoPath varchar2(50 char) := 'AdditionalPersonInfo/AdditionalInformationIp/';
    pUrInfoPath varchar2(50 char) := 'AdditionalPersonInfo/AdditionalInformationUr/';
    pInfoPath   varchar2(50 char);
  begin
    pMember.mess_cfm_id := pmessid;
    pMember.member_id   := pmemberid + 1;

    pMember.member_kind := pkg_messages_xml.getsingleval(pnode, 'ParticipantsView');
    pMember.member_role := pkg_messages_xml.getsingleval(pnode, 'ParticipantOperation');
    if (pkg_messages_xml.getsingleval(pnode, 'MemberCommunity') = 'true') then
      pMember.member_residence := 1;
    elsif (pkg_messages_xml.getsingleval(pnode, 'MemberCommunity') = 'false') then
      pMember.member_residence := 0;
    end if;
    pMember.member_residence_countrycode := pkg_messages_xml.getsingleval(pnode, 'MemberCommunitySityCode');
    pMember.member_type                  := to_number(pkg_messages_xml.getsingleval(pnode, 'ParticipantsType'));
    pMember.member_foreign               := pkg_messages_xml.getsingleval(pnode, 'ForeignPerson');
    pMember.member_foreign_add           := pkg_messages_xml.getsingleval(pnode, 'ForeignAdditionalField');

    pMember.member_bank_code        := pkg_messages_xml.getsingleval(pnode, 'BankCode');
    pMember.member_bank_city        := pkg_messages_xml.getsingleval(pnode, 'BankCity');
    pMember.MEMBER_BANK_OFFSHORE_ADDR    := pkg_messages_xml.getsingleval(pnode, 'BankOffshoreAddr');
    pMember.member_bank_name        := pkg_messages_xml.getsingleval(pnode, 'CorrespondentBankName');
    pMember.member_bank_account     := pkg_messages_xml.getsingleval(pnode, 'CorrespondentBankAccountNumber');
    pMember.member_bank_address     := pkg_messages_xml.getsingleval(pnode, 'CorrespondentBankAddress');
    pMember.member_taxcode          := pkg_messages_xml.getsingleval(pnode, 'RNN');
    pMember.member_okpo             := pkg_messages_xml.getsingleval(pnode, 'OKPO');
    pMember.member_oked             := pkg_messages_xml.getsingleval(pnode, 'OKED');
    pMember.member_maincode            := pkg_messages_xml.getsingleval(pnode, 'IndividualIssue');

    pMember.member_phone    := to_number(pkg_messages_xml.getsingleval(pnode, 'PhoneNumber'));
    pMember.member_email    := pkg_messages_xml.getsingleval(pnode, 'Email');
    pMember.member_comments := pkg_messages_xml.getsingleval(pnode, 'AdditionalInformation');

    case pMember.member_type
      when 1 then
        pInfoPath := pUrInfoPath;
      when 2 then
        pInfoPath := pAcInfoPath;
      when 3 then
        pInfoPath := pIpInfoPath;
      else
        return - 3007; ---6010; --Неправильный код тип участника
    end case;

    pMember.member_reg_counrycode  := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Country');
    pMember.member_reg_area        := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Area');
    pMember.member_reg_region      := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/District');
    pMember.member_reg_sity        := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Town');
    pMember.member_reg_street      := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Street');
    pMember.member_reg_house       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/HomeNumber');
    pMember.member_reg_office      := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/OfficeNumber');
    pMember.member_reg_postcode    := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/PostalCode');
    pMember.member_seat_counrycode := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Country');
    pMember.member_seat_area       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Area');
    pMember.member_seat_region     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/District');
    pMember.member_seat_sity       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Town');
    pMember.member_seat_street     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Street');
    pMember.member_seat_house      := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/HomeNumber');
    pMember.member_seat_office     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/OfficeNumber');
    pMember.member_seat_postcode   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/PostalCode');

    pMember.member_ur_name          := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FullName');
    pMember.member_ur_fisthead_name := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FirstHead');

    pMember.member_ac_secondname   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FirstName');
    pMember.member_ac_firstname    := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'SecondName');
    pMember.member_ac_middlename   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'MiddleName');
    pMember.member_ac_doc_typecode := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DocumentIdentity');
    pMember.member_ac_doc_number   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'NumberDocIdentity');
    pMember.member_ac_doc_series   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'SeriesDocIdentity');
    pMember.member_ac_doc_whom     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'IssuedDocument');
    pMember.member_ac_doc_date     := to_date(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DateIssuance'), 'yyyy-mm-dd');
    pMember.member_ac_birth_date   := to_date(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DateBirdth'), 'yyyy-mm-dd');
    pMember.member_ac_birth_place  := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'PlaceBirdth');

    insert into mess_cfm_announce_memb
    values pMember;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3003; ---6004; --Ошибка экпорта данных об участнике операции по причине их неверного формата
      return result;
  end;

  function ParseFounderInfo(pnode      xmldom.domnode,
                            pmessid    in number,
                            pmemberid  in number,
                            pfounderid in number) return number is
    result      number default 0;
    pFounnder   mess_cfm_announce_found%rowtype;
    pAcInfoPath varchar2(50 char) := 'FounderAC/';

    pUrInfoPath varchar2(50 char) := 'founderUR/';
    pInfoPath   varchar2(50 char);
  begin
    pFounnder.Founder_Id   := pfounderid + 1;
    pFounnder.mess_cfm_id  := pmessid;
    pFounnder.member_id    := pmemberid + 1;
    pFounnder.founder_type := pkg_messages_xml.GetSingleVal(pnode, 'PersonType');
    case pFounnder.founder_type
      when 1 then
        pInfoPath := pAcInfoPath;
      when 2 then
        pInfoPath := pUrInfoPath;
      else
        return - 3006; ---6011; --неправильно указан код типа учредителя
    end case;
    pFounnder.founder_maincode        := nvl(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'BIN'), pkg_messages_xml.getsingleval(pnode, pInfoPath || 'IIN'));
    pFounnder.founder_reg_counrycode  := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Country');
    pFounnder.founder_reg_area        := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Area');
    pFounnder.founder_reg_region      := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/District');
    pFounnder.founder_reg_sity        := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Town');
    pFounnder.founder_reg_street      := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Street');
    pFounnder.founder_reg_house       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/HomeNumber');
    pFounnder.founder_reg_office      := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/OfficeNumber');
    pFounnder.founder_reg_postcode    := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/PostalCode');
    pFounnder.founder_seat_counrycode := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Country');
    pFounnder.founder_seat_area       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Area');
    pFounnder.founder_seat_region     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/District');
    pFounnder.founder_seat_sity       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Town');
    pFounnder.founder_seat_street     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Street');
    pFounnder.founder_seat_house      := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/HomeNumber');
    pFounnder.founder_seat_office     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/OfficeNumber');
    pFounnder.founder_seat_postcode   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/PostalCode');
    pFounnder.founder_ur_name         := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FounderName');

    if (pkg_messages_xml.getsingleval(pnode, pInfoPath || 'Residence') = 'true') then
      pFounnder.founder_ur_residence := 1;
    elsif (pkg_messages_xml.getsingleval(pnode, pInfoPath || 'Residence') = 'false') then
      pFounnder.founder_ur_residence := 0;
    end if;

    pFounnder.founder_ur_residence_c_code := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ResidenceSity');
    pFounnder.founder_ur_reg_whom         := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'Authority');
    pFounnder.founder_ur_reg_number       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'RegistrationNumber');
    pFounnder.founder_ur_reg_date         := to_date(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'RegistrationDate'), 'yyyy-mm-dd');
    pFounnder.founder_ur_taxcode          := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'RNN');
    pFounnder.founder_ac_secondname       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FirstName');
    pFounnder.founder_ac_firstname        := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'SecondName');
    pFounnder.founder_ac_middlename       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'MiddleName');
    pFounnder.founder_ac_birth_date       := to_date(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DateBirdth'), 'yyyy-mm-dd');
    pFounnder.founder_ac_reg_number       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'PassportNumber');
    pFounnder.founder_ac_reg_series       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'PassportSeries');
    pFounnder.founder_ac_reg_whom         := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'IssuedDocument');
    pFounnder.founder_ac_reg_date         := to_date(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DateIssuance'), 'yyyy-mm-dd');

    insert into mess_cfm_announce_found
    values pFounnder;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3005; ---6004; --Ошибка экпорта данных об участнике операции по причине их неверного формата
      return result;
  end;

  function ParseFoundersInfo(pnode     xmldom.domnode,
                             pmessid   in number,
                             pmemberid in number) return number is
    result    number default 0;
    vNodeList xmldom.domnodelist;
    vnode     xmldom.domnode;

  begin
    vNodeList := pkg_messages_xml.GetNodesList(pnode, 'FoundersList/Founder');
    for i in 0 .. xmldom.getLength(vNodeList) - 1 loop
      vnode  := xmldom.item(vNodeList, i);
      result := ParseFounderInfo(vnode, pmessid, pmemberid, i);
      if result <> 0 then
        return result;
      end if;
    end loop;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3005; --Ошибка экпорта данных об учредителе участнике операции по причине их неверного формата
      return result;
  end;

  function ParseMembersInfo(pnode   xmldom.domnode,
                            pmessid in number) return number is
    result    number default 0;
    vNodeList xmldom.domnodelist;
    vnode     xmldom.domnode;

  begin
    vNodeList := pkg_messages_xml.GetNodesList(pnode, 'ParticipantsList/Participant');
    for i in 0 .. xmldom.getLength(vNodeList) - 1 loop
      vnode  := xmldom.item(vNodeList, i);
      result := ParseMemberInfo(vnode, pmessid, i);
      if result <> 0 then
        return result;
      end if;
      result := ParseFoundersInfo(vnode, pmessid, i);
      if result <> 0 then
        return result;
      end if;
    end loop;
    ------
    return result;
  end;

  function parseAnnounceXML(pmessid in number) return number is
    result   number default 0;
    vres     number default 0;
    vnode    xmldom.domnode;
    pxmlclob clob;
    tempres  number default 0;

  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;

    vnode  := pkg_messages_xml.GetParsedXML(pxmlclob);
    result := ParseMessageInfo(vnode, pmessid);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    result := ParseCmfInfo(vnode, pmessid);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    result := ParseCfmcontactInfo(vnode, pmessid);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    result := ParseOperationInfo(vnode, pmessid);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    result := ParseMembersInfo(vnode, pmessid);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    if tempres = 0 then
      vres := SetErrorCode(pmessid, 0);
      return vres;
    end if;
    return tempres;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      return - 305; --Неверный XML документ  -- изменть
      return result;
  end;

  function parseCheckXML(pmessid in number) return number is
    result   number default 0;
    vnode    xmldom.domnode;
    pxmlclob clob;

    vCheck mess_cfm_check%rowtype;
  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vCheck.Mess_Cfm_Id := pmessid;

    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);

    vCheck.Errorcode := pkg_messages_xml.getsingleval(vnode, 'ErrorCode');
    vCheck.ErrorName := pkg_messages_xml.getsingleval(vnode, 'ErrorName');
    insert into mess_cfm_check
    values vcheck;

    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3008);
      return - 3008; --Неверный формат данных в квитанции
      return result;
  end;

  function parseDopInfXML(pmessid in number) return number is
    result   number default 0;
    vnode    xmldom.domnode;
    pxmlclob clob;

    vDopInf mess_cfm_dopinf%rowtype;
  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vDopInf.Mess_Cfm_Id := pmessid;

    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);

    vDopInf.Description := pkg_messages_xml.getsingleval(vnode, 'Description');
    vDopInf.Days_Count  := pkg_messages_xml.getsingleval(vnode, 'CountDays');
    insert into mess_cfm_dopinf
    values vDopInf;

    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3009);
      return - 3009; --Неверный формат данных в ответе на дополнительную информацию
      return result;
  end;

  function parseDopInfAnswXML(pmessid in number) return number is
    result    number default 0;
    vnode     xmldom.domnode;
    pnode     xmldom.domnode;
    vNodeList xmldom.domnodelist;
    pxmlclob  clob;

    vDopInfAnsw mess_cfm_dopinf_answ%rowtype;
  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vDopInfAnsw.Mess_Cfm_Id := pmessid;

    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);

    vNodeList := pkg_messages_xml.GetNodesList(pnode, 'Attachments/Attachment');
    for i in 0 .. xmldom.getLength(vNodeList) - 1 loop
      vnode                     := xmldom.item(vNodeList, i);
      vDopInfAnsw.Attach_Id     := i;
      vDopInfAnsw.Attach_Name   := pkg_messages_xml.getsingleval(vnode, 'FileName');
      vDopInfAnsw.Attach_Length := pkg_messages_xml.getsingleval(vnode, 'Length');
      insert into mess_cfm_dopinf_answ
      values vDopInfansw;
    end loop;

    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3010); -- Неверный формат данных в ответе на дополнительную информацию
      return - 3010; --Неверный XML документ
      return result;
  end;

  function parseUpdateRequestXML(pmessid in number) return number --Запрос на обновление
   is
    result number default 0;
    vnode  xmldom.domnode;

    pxmlclob clob;

    vUpdate mess_cfm_update_info%rowtype;
  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vUpdate.Mess_Cfm_Id := pmessid;

    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);

    vUpdate.Update_Version := pkg_messages_xml.getsingleval(vnode, 'RequestedVersion');
    -- vUpdate.Release_Date:=to_date(pkg_messages_xml.getsingleval(vnode,'ReleaseDate'),'yyyy-mm-dd');

    insert into mess_cfm_update_info
    values vupdate;
    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3013); --Неверный формат данных в запросе на обновление
      return - 3013; --Неверный XML документ
      return result;
  end;

  function ParseUpdateInfoXML(pmessid in number) return number is
    result     number default 0;
    vnode      xmldom.domnode;
    pnode      xmldom.domnode;
    pnode1     xmldom.domnode;
    vNodeList  xmldom.domnodelist;
    vNodeList1 xmldom.domnodelist;
    pxmlclob   clob;

    vUpdateVersion varchar2(300);
    vDateRelease   date;
    vmodulename    varchar2(100 char);

  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);

    --Головное обновление
    vUpdateVersion := pkg_messages_xml.getsingleval(vnode, 'UpdateVersion');
    vDateRelease   := to_date(pkg_messages_xml.getsingleval(vnode, 'ReleaseDate'), 'yyyy-mm-dd');
    insert into mess_cfm_update_info
      (mess_cfm_id,
       update_version,
       release_date)
    values
      (pmessid,
       vupdateversion,
       vDateRelease);

    if pkg_updates_cfm.existsInHisory(vUpdateVersion, vDateRelease) = 0 then
      insert into updates_cfm_hist
        (messid,
         version,
         daterelease)
      values
        (pmessid,
         vUpdateVersion,
         vDateRelease);

      --Используемые модули
      vNodeList := pkg_messages_xml.GetNodesList(vnode, 'Using/Use');
      for i in 0 .. xmldom.getLength(vnodelist) - 1 loop
        pnode       := xmldom.item(vnodelist, i);
        vmodulename := xslprocessor.valueOf(pnode, 'text()');
        insert into updates_cfm_hist_mod
          (version,
           modulename,
           messid)
        values
          (vUpdateVersion,
           vmodulename,
           pmessid);
      end loop;
    end if;

    --История версий обновлений
    vNodeList := pkg_messages_xml.GetNodesList(vnode, 'Histories/History');
    for i in 0 .. xmldom.getLength(vnodelist) - 1 loop
      pnode          := xmldom.item(vnodelist, i);
      vUpdateVersion := pkg_messages_xml.getsingleval(pnode, 'Version');
      vDateRelease   := to_date(pkg_messages_xml.getsingleval(pnode, 'ReleaseDate'), 'yyyy-mm-dd');

      if pkg_updates_cfm.existsInHisory(vUpdateVersion, vDateRelease) = 0 then
        insert into updates_cfm_hist
          (messid,
           version,
           daterelease)
        values
          (pmessid,
           vUpdateVersion,
           vDateRelease);

        --Используемые модули
        vnodelist1 := pkg_messages_xml.GetNodesList(pnode, 'Using/Use');
        for j in 0 .. xmldom.getLength(vnodelist1) - 1 loop
          pnode1      := xmldom.item(vnodelist1, j);
          vmodulename := xslprocessor.valueOf(pnode1, 'text()');
          insert into updates_cfm_hist_mod
            (version,
             modulename,
             messid)
          values
            (vUpdateVersion,
             vmodulename,
             pmessid);
        end loop;
      end if;
    end loop;

    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3011); --Неверный формат данных в информационнном сообщении об обновлении
      return - 3011; --Неверный XML документ
      return result;
  end;

  function ParseUpdateXML(pmessid in number) return number is
    result    number default 0;
    vnode     xmldom.domnode;
    vNodeList xmldom.domnodelist;
    pxmlclob  clob;

    vUpdateVersion varchar2(300);
    vDateRelease   date;
    vmodulename    varchar2(100 char);
    cursor moduleCur is
      select distinct modulename
      from updates_cfm_modulenames;

  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vnode          := pkg_messages_xml.GetParsedXML(pxmlclob);
    vUpdateVersion := pkg_messages_xml.getsingleval(vnode, 'UpdateVersion');
    vDateRelease   := to_date(pkg_messages_xml.getsingleval(vnode, 'ReleaseDate'), 'yyyy-mm-dd');
    insert into mess_cfm_update_info
      (mess_cfm_id,
       update_version,
       release_date)
    values
      (pmessid,
       vupdateversion,
       vDateRelease);

    insert into updates_cfm_hist
      (messid,
       version,
       daterelease)
    values
      (pmessid,
       vUpdateVersion,
       vDateRelease);

    --Используемые модули
    vnodelist := xslprocessor.selectNodes(vnode, 'UpdateInformations/UpdateInformation/Using/Use/ModuleName');
    for i in 0 .. xmldom.getLength(vnodelist) - 1 loop
      vnode       := xmldom.item(vnodelist, i);
      vmodulename := xslprocessor.valueOf(vnode, 'text()');
      insert into updates_cfm_modulenames
        (modulename)
      values
        (vmodulename);
    end loop;

    for modulerow in moduleCur loop
      insert into updates_cfm_hist_mod
        (version,
         modulename,
         messid)
      values
        (vUpdateVersion,
         modulerow.modulename,
         pmessid);
    end loop;

    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3012); --Неверный формат данных в информационнном сообщении собновлением
      return - 3012; --Неверный XML документ
      return result;
  end;

  function SetErrorCode(pmessid  in number,
                        perrcode in number) return number is
  begin
    update mess_cfm
    set int_err_code = perrcode
    where mess_cfm_id = pmessid;
    return 0;

  exception
    when no_data_found then
      return - 1000;
  end;

  function getcolumn_length(p_table_name in varchar2,
                            p_name       in varchar2,
                            p_length     out number) return number is
    result number default 0;
  begin

    select data_length
    into p_length
    from USER_TAB_COLUMNS
    where table_name = upper(p_table_name)
    and column_name = upper(p_name);
    return result;

  exception
    when others then
      return - 2099;

  end;

--function GetNoDateVal()

end PKG_MESS_CFM_1;
/

CREATE OR REPLACE PACKAGE KFM."PKG_MESS_CFM_2" as
  function ExtractMessInSignedData(pXML      in clob,
                                   pExist    out number,
                                   pSender   out varchar2,
                                   pReceiver out varchar,
                                   pDate     out date) return number;
  function ExtractSignatureData(pXML       in clob,
                                pSignature out varchar2) return number;

  function ParseMessageInfo(pnode       xmldom.domnode,
                            pmessid     in number,
                            pversion_id number) return number;
  function ParseCMFInfo(pnode       xmldom.domnode,
                        pmessid     in number,
                        pversion_id number) return number;
  function ParseCFMContactInfo(pnode       xmldom.domnode,
                               pmessid     in number,
                               pversion_id number) return number;
  function ParseOperationInfo(pnode       xmldom.domnode,
                              pmessid     in number,
                              pversion_id number) return number;
  function ParseMemberInfo(pnode       xmldom.domnode,
                           pmessid     in number,
                           pmemberid   in number,
                           pversion_id number) return number;
  function ParseMembersInfo(pnode       xmldom.domnode,
                            pmessid     in number,
                            pversion_id number) return number;

  function ParseRefersInfo(pnode   xmldom.domnode,
                           pmessid in number) return number;
  function ParseReferInfo(pnode    xmldom.domnode,
                          pmessid  in number,
                          preferid in number) return number;

  function ParseFounderInfo(pnode       xmldom.domnode,
                            pmessid     in number,
                            pmemberid   in number,
                            pfounderid  in number,
                            pversion_id number) return number;
  function ParseFoundersInfo(pnode       xmldom.domnode,
                             pmessid     in number,
                             pmemberid   in number,
                             pversion_id number) return number;

  function parseAnnounceXML(pmessid     in number,
                            pversion_id number) return number;

  function parseCheckXML(pmessid in number) return number;
  function parseDopInfXML(pmessid in number) return number;
  function parseDopInfAnswXML(pmessid in number) return number;
  function parseUpdateRequestXML(pmessid in number) return number;
  function ParseUpdateInfoXML(pmessid in number) return number;
  function ParseUpdateXML(pmessid in number) return number;
  function SetErrorCode(pmessid  in number,
                        perrcode in number) return number;
  function GetOuterAnnounceXML(PXMLSCH1 xmltype,
                               pversion number) return xmltype;

end PKG_MESS_CFM_2;
/

CREATE OR REPLACE PACKAGE BODY KFM."PKG_MESS_CFM_2" as

  function ExtractMessInSignedData(pXML      in clob,
                                   pExist    out number,
                                   pSender   out varchar2,
                                   pReceiver out varchar,
                                   pDate     out date) return number is
    result number default 0;
    vXML   xmltype;
  begin
    begin
      vXML := xmltype.createxml(pXML);
    exception
      when others then
        return - 305; --Сообщение is not valid
    end;
    select existsNode(vXML, '//ExportData')
    into pExist
    from dual;
    if pExist is null then
      pExist := 0;
    end if;

    select extractvalue(vXML, '/ExportData/SignedData/Sender'),
           extractvalue(vXML, '/ExportData/SignedData/Receiver'),
           to_date(extractvalue(vXML, '/ExportData/SignedData/TimeStamp'), 'dd.mm.yyyy hh24:mi:ss')
    into pSender,
         pReceiver,
         pDate
    from dual;
    return result;
  exception
    when others then
      return - 315; --В сообщении отсутствует информация  об отправителе и получателе
  end;

  function ExtractSignatureData(pXML       in clob,
                                pSignature out varchar2) return number is
    result number default 0;
    vXML   xmltype;
  begin
    begin
      vXML := xmltype.createxml(pXML);
    exception
      when others then
        return - 305; --Сообщение is not valid
    end;
    select extractvalue(vXML, '/ExportData/SignedData/Signature')
    into pSignature
    from dual;

    return result;
  exception
    when others then
      return - 316; --В сообщении отсутствует информация  об отправителе и получателе
  end;

  function ParseMessageInfo(pnode       xmldom.domnode,
                            pmessid     in number,
                            pversion_id number) return number is
    result    number default 0;
    vMess     mess_cfm_announce_info%rowtype;
    pmessdate date;

  begin
    select send_date
    into pmessdate
    from mess_cfm
    where mess_cfm_id = pmessid; -- Пока нету в сообщении, затем изменить
    vMess.mess_cfm_id      := pmessid;
    vMess.mess_number      := pkg_messages_xml.getsingleval(pnode, 'MessageInformation/MessageNumber');
    vMess.mess_date        := to_date(pkg_messages_xml.getsingleval(pnode, 'MessageInformation/LastModifyDate'), 'dd.mm.yyyy'); --pmessdate; -- Выдергивать напрямую из XML
    vMess.mess_type        := pkg_messages_xml.getsingleval(pnode, 'MessageInformation/DocumentType');
    vMess.mess_oper_status := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/OperationStatusId');
    vMess.mess_reason_code := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/ReasonFilingId');
    vMess.mess_suspic_code := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/SuspicionsCriterians');

    vMess.Mess_Trans_Date := to_date(pkg_messages_xml.getsingleval(pNode, 'MessageInformation/MessTransDate'), 'dd.mm.yyyy hh24:mi:ss');
    insert into mess_cfm_announce_info
    values vMess;
    return result;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      return - 1000; --Сообщение не найдено
    WHEN OTHERS THEN
      return - 3004; --- 6001; --  Ошибка экпорта данных о сообщении по причине их неверного формата

  end;

  function ParseCMFInfo(pnode       xmldom.domnode,
                        pmessid     in number,
                        pversion_id number) return number is
    result number default 0;
    vCFM   mess_cfm_announce_subj%rowtype;
  begin
    vCFM.mess_cfm_id       := pmessid;
    vCFM.cfm_code          := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationCode');
    vCFM.cfm_name          := pkg_messages_xml.getsingleval(pnode, 'PersonalData/Organisation');
    vCFM.cfm_taxcode       := pkg_messages_xml.getsingleval(pnode, 'PersonalData/RNN');
    vCFM.cfm_maincode      := pkg_messages_xml.getsingleval(pnode, 'PersonalData/IINBIN');
    vCFM.cfm_seat_area     := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationArea');
    vCFM.cfm_seat_region   := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationDistrict');
    vCFM.cfm_seat_sity     := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationCity');
    vCFM.cfm_seat_street   := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationStreet');
    vCFM.cfm_seat_house    := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationHouse');
    vCFM.cfm_seat_office   := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationOffice');
    vCFM.cfm_seat_postcode := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationPostalIndex');
    vCFM.Cfm_Isac          := pkg_common.BoolToNumber(pkg_messages_xml.getsingleval(pnode, 'PersonalData/AdditionalAcData/@IsAc'));
    --алексей 2012.10.23
    --if vCFM.Cfm_Isac=1 then
    vCFM.Cfm_Doc_Typecode  := pkg_messages_xml.getsingleval(pnode, 'PersonalData/AdditionalAcData/DocumentIdentity');
    vCFM.Cfm_Doc_Number    := pkg_messages_xml.getsingleval(pnode, 'PersonalData/AdditionalAcData/NumberDocIdentity');
    vCFM.Cfm_Doc_Series    := pkg_messages_xml.getsingleval(pnode, 'PersonalData/AdditionalAcData/SeriesDocIdentity');
    vCFM.Cfm_Doc_Whom      := pkg_messages_xml.getsingleval(pnode, 'PersonalData/AdditionalAcData/DocumentIssued');
    vCFM.Cfm_Doc_Date      := to_date(pkg_messages_xml.getsingleval(pnode, 'PersonalData/AdditionalAcData/DateIssuance'), 'dd.mm.yyyy');
    vCFM.CFM_AC_FIRSTNAME  := pkg_messages_xml.getsingleval(pnode, 'PersonalData/HeadName');
    vCFM.CFM_AC_SECONDNAME := pkg_messages_xml.getsingleval(pnode, 'PersonalData/HeadSurname');
    vCFM.CFM_AC_MIDDLENAME := pkg_messages_xml.getsingleval(pnode, 'PersonalData/HeadMidleName');
    --алексей 2012.10.23
    --end if;
    ---Только для версии 3 (Код ОПФ + Страны согласно справочнику ИС АР)------------------------------
    if pversion_id >= 3 then
      vcfm.cfm_ur_opf_code      := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationOPF');
      vcfm.cfm_seat_area_code   := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationArea/@Code');
      vcfm.cfm_seat_region_code := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationDistrict/@Code');
      vcfm.cfm_seat_sity_code   := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationCity/@Code');
      vcfm.cfm_seat_street_code := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationStreet/@Code');
      vcfm.cfm_seat_house_code  := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationHouse/@Code');
      vcfm.cfm_seat_office_code := pkg_messages_xml.getsingleval(pnode, 'PersonalData/OrganisationOffice/@Code');
    end if;
    ---Только для версии 3 (Код ОПФ + Страны согласно справочнику ИС АР)------------------------------
    insert into mess_cfm_announce_subj
    values vcfm;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3001; ---6000; --Ошибка экпорта данных о субъекте, подающем отчет, по причине их неверного формата

  end;

  function ParseCFMContactInfo(pnode       xmldom.domnode,
                               pmessid     in number,
                               pversion_id number) return number is
    result     number default 0;
    vCFMConact mess_cfm_announce_cont%rowtype;
  begin
    vCFMConact.mess_cfm_id        := pmessid;
    vCFMConact.contact_secondname := pkg_messages_xml.getsingleval(pnode, 'PersonalData/FirstName');
    vCFMConact.contact_firstname  := pkg_messages_xml.getsingleval(pnode, 'PersonalData/SecondName');
    vCFMConact.contact_middlename := pkg_messages_xml.getsingleval(pnode, 'PersonalData/MiddleName');
    vCFMConact.contact_job        := pkg_messages_xml.getsingleval(pnode, 'PersonalData/JobName');
    vCFMConact.contact_phone      := pkg_messages_xml.getsingleval(pnode, 'PersonalData/Phone');
    vCFMConact.contact_email      := pkg_messages_xml.getsingleval(pnode, 'PersonalData/Email');
    insert into mess_cfm_announce_cont
    values vcfmconact;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3002; ---6002; --Ошибка экпорта данных о контактном лице субъекта по причине их неверного формата
  end;

  function ParseOperationInfo(pnode       xmldom.domnode,
                              pmessid     in number,
                              pversion_id number) return number is
    result     number default 0;
    vOperation mess_cfm_announce_oper%rowtype;
  begin
    vOperation.mess_cfm_id       := pmessid;
    vOperation.oper_number       := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/OperationNumber');
    vOperation.oper_idview       := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/ViewOperationId');
    vOperation.oper_idtype       := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/EknpId');
    vOperation.Oper_IsNotIDTyped := pkg_common.BoolToNumber(pkg_messages_xml.getsingleval(pNode, 'MessageInformation/EknpId/@IsEknpNotSetup'));
    vOperation.Oper_Trans_Date   := to_date(pkg_messages_xml.getsingleval(pNode, 'MessageInformation/TransactionDate'), 'dd.mm.yyyy hh24:mi:ss');
    --IsEknpNotSetup

    vOperation.oper_members_count    := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/ParticipantCount');
    vOperation.oper_currency_code   := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/CurrencyCodeId');
    vOperation.oper_currency_amount := pkg_common.ConvertToNumber(pkg_messages_xml.getsingleval(pNode, 'MessageInformation/AmountCurrency'));
    vOperation.oper_tenge_amount     := pkg_common.ConvertToNumber(pkg_messages_xml.getsingleval(pNode, 'MessageInformation/AmountCurrencyTenge'));
    vOperation.oper_reason           := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/DocOperationReason');
    vOperation.oper_doc_date         := to_date(pkg_messages_xml.getsingleval(pNode, 'MessageInformation/DocOperationDate'), 'dd.mm.yyyy');
    vOperation.oper_doc_number       := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/DocOperationNumber');
    vOperation.oper_susp_first       := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/SuspicionFirst');
    vOperation.oper_susp_second      := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/SuspicionSecond');
    vOperation.oper_susp_third       := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/SuspicionThird');
    vOperation.oper_difficulties     := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/DescriptionDifficulties');
    vOperation.oper_dopinfo          := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/MoreInformation');

    vOperation.oper_merch_types   := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/MerchTypes');
    vOperation.oper_merch_reginfo := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/MerchReginfo');
    vOperation.oper_refers_count  := pkg_messages_xml.getsingleval(pNode, 'MessageInformation/ReferCount');

    insert into mess_cfm_announce_oper
    values vOperation;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3000; ---6003; --Ошибка экпорта данных об операции причине их неверного формата
      return result;
  end;

  function ParseMemberInfo(pnode       xmldom.domnode,
                           pmessid     in number,
                           pmemberid   in number,
                           pversion_id number) return number is
    result      number default 0;
    pMember     mess_cfm_announce_memb%rowtype;
    pAcInfoPath varchar2(50 char) := 'AdditionalPersonInfo/AdditionalInformationAc/';
    pIpInfoPath varchar2(50 char) := 'AdditionalPersonInfo/AdditionalInformationIp/';
    pUrInfoPath varchar2(50 char) := 'AdditionalPersonInfo/AdditionalInformationUr/';
    pInfoPath   varchar2(50 char);
  begin
    pMember.mess_cfm_id := pmessid;
    pMember.member_id   := pmemberid + 1;

    pMember.member_kind       := pkg_messages_xml.getsingleval(pnode, 'ParticipantsView');
    pMember.member_membercode := pkg_messages_xml.getsingleval(pnode, 'MemberId'); --участник (4.1)
    pMember.member_isclient   := pkg_messages_xml.getsingleval(pnode, 'IsClientSubject');
    --  pMember.member_residence  :=BoolToNumber(pkg_messages_xml.getsingleval(pnode,'MemberCommunityCityCode/@IsMemberCommunity'));

    pMember.member_residence_countrycode := pkg_messages_xml.getsingleval(pnode, 'MemberCommunityCityCode'); --pkg_messages_xml.getsingleval(pnode,'MemberCommunitySityCode');
    pMember.member_type                  := to_number(pkg_messages_xml.getsingleval(pnode, 'ParticipantsType'));
    pMember.member_foreign               := pkg_messages_xml.getsingleval(pnode, 'ForeignPerson');
    -- pMember.member_foreign_add := pkg_messages_xml.getsingleval(pnode,'ForeignAdditionalField');

    pMember.member_bank_code    := pkg_messages_xml.getsingleval(pnode, 'CorrespondentBank/Code');
    pMember.member_bank_city    := pkg_messages_xml.getsingleval(pnode, 'CorrespondentBank/BankCity');
    pMember.member_bank_name    := pkg_messages_xml.getsingleval(pnode, 'CorrespondentBank/Name');
    pMember.member_bank_account := pkg_messages_xml.getsingleval(pnode, 'CorrespondentBank/AccountNumber');
    pMember.member_bank_address := pkg_messages_xml.getsingleval(pnode, 'CorrespondentBank/BankAddress');
    pMember.MEMBER_BANK_OFFSHORE_ADDR := pkg_messages_xml.getsingleval(pnode, 'CorrespondentBank/BankOffshoreAddr');
    pMember.member_taxcode      := pkg_messages_xml.getsingleval(pnode, 'RNN');
    --  pMember.member_okpo         := pkg_messages_xml.getsingleval(pnode,'OKPO');
    pMember.member_oked     := pkg_messages_xml.getsingleval(pnode, 'OKED');
    pMember.member_maincode := pkg_messages_xml.getsingleval(pnode, 'IndividualIssue');

    pMember.member_phone    := to_number(pkg_messages_xml.getsingleval(pnode, 'PhoneNumber'));
    pMember.member_email    := pkg_messages_xml.getsingleval(pnode, 'Email');
    pMember.member_comments := pkg_messages_xml.getsingleval(pnode, 'AdditionalInformation');
    --не было
    pMember.money_trans_sys := pkg_messages_xml.getsingleval(pnode, 'MoneyTransSys');
    if pMember.member_type is null then
      pMember.member_type := 1;
    end if;
    case pMember.member_type
      when 1 then
        pInfoPath := pUrInfoPath;

        pMember.member_ur_name    := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FullName');
        pMember.Member_IsNotNamed := pkg_common.BoolToNumber(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FullName/@IsFullNameSetup'));
        --IsFullNameSetup
        if pversion_id = 2 then
          --Для версии 2--------------------------- (ФИО)------------------------------
          pMember.member_ur_fisthead_name := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FirstHead');
        elsif pversion_id >= 3 then
          ---Только для версии 3 (Код ОПФ + разбиение ФИО)------------------------------
          pMember.Member_Ur_Opf_Code            := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ParticipantOPF');
          pMember.Member_Ur_Fisthead_Firstname  := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FirstHead/FirstName');
          pMember.Member_Ur_Fisthead_Secondname := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FirstHead/SecondName');
          pMember.Member_Ur_Fisthead_Middlename := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FirstHead/MiddleName');
          ---Только для версии 3 (Код ОПФ + разбиение ФИО)------------------------------
        end if;

      when 2 then
        pInfoPath := pAcInfoPath;

        --IsFioNotSetup
        pMember.member_ac_birth_date   := to_date(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DateBirdth'), 'dd.mm.yyyy');
        pMember.member_ac_birth_place  := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'PlaceBirdth');
        pMember.member_ac_doc_typecode := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DocumentIdentity');
        pMember.member_ac_doc_number   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'NumberDocIdentity');
        pMember.member_ac_doc_series   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'SeriesDocIdentity');
        pMember.member_ac_doc_whom     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DocumentIssued');
        pMember.member_ac_doc_date     := to_date(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DateIssuance'), 'dd.mm.yyyy');
        pMember.Member_IsNotNamed      := pkg_common.BoolToNumber(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FIO/@IsFioNotSetup'));
        if pversion_id = 2 then
          --Для версии 2------- (ФИО)------------------------------
          pMember.member_ur_name := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FIO');
        elsif pversion_id >= 3 then
          ---Только для версии 3 (ФИО)------------------------------
          if pMember.Member_IsNotNamed = 0 then
            pMember.Member_Ac_Firstname  := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FIO/FirstName');
            pMember.Member_Ac_Secondname := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FIO/SecondName');
            pMember.Member_Ac_Middlename := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FIO/MiddleName');
          end if;
          ---Только для версии 3 (ФИО)------------------------------
        end if;

      when 3 then
        pInfoPath := pIpInfoPath;

        --IsFioNotSetup
        pMember.member_ac_birth_date   := to_date(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DateBirdth'), 'dd.mm.yyyy');
        pMember.member_ac_birth_place  := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'PlaceBirdth');
        pMember.member_ac_doc_typecode := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DocumentIdentity');
        pMember.member_ac_doc_number   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'NumberDocIdentity');
        pMember.member_ac_doc_series   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'SeriesDocIdentity');
        pMember.member_ac_doc_whom     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DocumentIssued');
        pMember.member_ac_doc_date     := to_date(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'DateIssuance'), 'dd.mm.yyyy');
        pMember.Member_IsNotNamed      := pkg_common.BoolToNumber(pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FIO/@IsFioNotSetup'));
        if pversion_id = 2 then
          --Для версии 2------- (ФИО)------------------------------
          pMember.member_ur_name := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FIO');
        elsif pversion_id >= 3 then
          ---Только для версии 3 (ФИО)------------------------------
          if pMember.Member_IsNotNamed = 0 then
            pMember.Member_Ac_Firstname  := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FIO/FirstName');
            pMember.Member_Ac_Secondname := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FIO/SecondName');
            pMember.Member_Ac_Middlename := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'FIO/MiddleName');
          end if;
          ---Только для версии 3 (ФИО)------------------------------
        end if;
      else
        return - 3007; ---6010; --Неправильный код тип участника
    end case;

    pMember.member_reg_counrycode := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Country');
    pMember.member_reg_area       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Area');
    pMember.member_reg_region     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/District');
    pMember.member_reg_sity       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Town');
    pMember.member_reg_street     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Street');
    pMember.member_reg_house      := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/HomeNumber');
    pMember.member_reg_office     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/OfficeNumber');
    pMember.member_reg_postcode   := pkg_messages_xml.getsingleval(pnode,pInfoPath||'URAddress/PostalCode');
    pMember.member_seat_counrycode := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Country');
    pMember.member_seat_area       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Area');
    pMember.member_seat_region     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/District');
    pMember.member_seat_sity       := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Town');
    pMember.member_seat_street     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Street');
    pMember.member_seat_house      := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/HomeNumber');
    pMember.member_seat_office     := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/OfficeNumber');
    pMember.member_seat_postcode  := pkg_messages_xml.getsingleval(pnode,pInfoPath||'ACAddress/PostalCode');

    ---Только для версии 3 (Страны согласно справочнику ИС АР)------------------------------
    if pversion_id >= 3 then
        pMember.member_reg_area_code   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Area/@Code');
        pMember.member_reg_region_code := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/District/@Code');
        pMember.member_reg_sity_code   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Town/@Code');
        pMember.member_reg_street_code := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/Street/@Code');
        pMember.member_reg_house_code  := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/HomeNumber/@Code');
        pMember.member_reg_office_code := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'URAddress/OfficeNumber/@Code');

        pMember.member_seat_area_code   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Area/@Code');
        pMember.member_seat_region_code := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/District/@Code');
        pMember.member_seat_sity_code   := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Town/@Code');
        pMember.member_seat_street_code := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/Street/@Code');
        pMember.member_seat_house_code  := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/HomeNumber/@Code');
        pMember.member_seat_office_code := pkg_messages_xml.getsingleval(pnode, pInfoPath || 'ACAddress/OfficeNumber/@Code');
    end if;
    ---Только для версии 3  (Страны согласно справочнику ИС АР)------------------------------

    insert into mess_cfm_announce_memb
    values pMember;

    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3003; ---6004; --Ошибка экпорта данных об участнике операции по причине их неверного формата
      return result;
  end;

  function ParseReferInfo(pnode    xmldom.domnode,
                          pmessid  in number,
                          preferid in number) return number is
    result number default 0;
    pRefer mess_cfm_refer%rowtype;
  begin
    pRefer.mess_cfm_id := pmessid;
    pRefer.referid     := preferid + 1;

    pRefer.refer_doc_oper := pkg_messages_xml.getsingleval(pnode, 'ReferenceOperationNumber');
    pRefer.refer_doc_date := to_date(pkg_messages_xml.getsingleval(pnode, 'ReferenceDocOperationDate'), 'dd.mm.yyyy');
    pRefer.refer_doc_num  := pkg_messages_xml.getsingleval(pnode, 'ReferencerDocOperationNumber');

    insert into mess_cfm_refer
    values pRefer;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3003; ---6004; --Ошибка экпорта данных об участнике операции по причине их неверного формата
      return result;
  end;

  function ParseFounderInfo(pnode       xmldom.domnode,
                            pmessid     in number,
                            pmemberid   in number,
                            pfounderid  in number,
                            pversion_id number) return number is
    result    number default 0;
    pFounnder mess_cfm_announce_found%rowtype;

  begin
    pFounnder.Founder_Id  := pfounderid + 1;
    pFounnder.mess_cfm_id := pmessid;
    pFounnder.member_id   := pmemberid + 1;
    if pversion_id = 2 then
      pFounnder.founder_ur_name := pkg_messages_xml.getsingleval(pnode, 'Name');
    elsif pversion_id >= 3 then
      pFounnder.Founder_Type := pkg_messages_xml.getsingleval(pnode, 'FounderType');
      case pFounnder.Founder_Type
        when 1 then
          pFounnder.Founder_Ur_Opf_Code := pkg_messages_xml.getsingleval(pnode, 'FounderOPF');
          pFounnder.founder_ur_name     := pkg_messages_xml.getsingleval(pnode, 'Name');
        when 2 then
          pFounnder.Founder_Ac_Firstname  := pkg_messages_xml.getsingleval(pnode, 'FirstName');
          pFounnder.Founder_Ac_Secondname := pkg_messages_xml.getsingleval(pnode, 'SecondName');
          pFounnder.Founder_Ac_Middlename := pkg_messages_xml.getsingleval(pnode, 'MiddleName');
        when 3 then
          pFounnder.Founder_Ac_Firstname  := pkg_messages_xml.getsingleval(pnode, 'FirstName');
          pFounnder.Founder_Ac_Secondname := pkg_messages_xml.getsingleval(pnode, 'SecondName');
          pFounnder.Founder_Ac_Middlename := pkg_messages_xml.getsingleval(pnode, 'MiddleName');
        else
          return - 3006;
      end case;
    end if;
    pFounnder.founder_ur_residence_c_code := pkg_messages_xml.getsingleval(pnode, 'MemberCommunityCityCode');
    insert into mess_cfm_announce_found
    values pFounnder;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3005; ---6004; --Ошибка экпорта данных об участнике операции по причине их неверного формата
      return result;
  end;

  function ParseFoundersInfo(pnode       xmldom.domnode,
                             pmessid     in number,
                             pmemberid   in number,
                             pversion_id number) return number is
    result    number default 0;
    vNodeList xmldom.domnodelist;
    vnode     xmldom.domnode;

  begin
    vNodeList := pkg_messages_xml.GetNodesList(pnode, 'Founders/Founder');
    for i in 0 .. xmldom.getLength(vNodeList) - 1 loop
      vnode  := xmldom.item(vNodeList, i);
      result := ParseFounderInfo(vnode, pmessid, pmemberid, i, pversion_id);
      if result <> 0 then
        return result;
      end if;
    end loop;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3005; --Ошибка экпорта данных об учредителе участнике операции по причине их неверного формата
      return result;
  end;

  function ParseAccountInfo(pnode       xmldom.domnode,
                            pmessid     in number,
                            pmemberid   in number,
                            paccountid  in number,
                            pversion_id number) return number is
    result   number default 0;
    pAccount mess_cfm_announce_accounts%rowtype;

  begin
    pAccount.accountId   := paccountid + 1;
    pAccount.mess_cfm_id := pmessid;
    pAccount.memberid    := pmemberid + 1;

    pAccount.Accountnumber := pkg_messages_xml.getsingleval(pnode, 'AccountNumber');
    pAccount.Bankname      := pkg_messages_xml.getsingleval(pnode, 'BankName');
    pAccount.Bankcode      := pkg_messages_xml.getsingleval(pnode, 'BankCode');
    pAccount.Bankaddress   := pkg_messages_xml.getsingleval(pnode, 'BankAddress');

    insert into mess_cfm_announce_accounts
    values pAccount;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3014; -- Неверный формат данных в информации о корреспондентских счетах
      return result;
  end;

  function ParseAccountsInfo(pnode       xmldom.domnode,
                             pmessid     in number,
                             pmemberid   in number,
                             pversion_id number) return number is
    result    number default 0;
    vNodeList xmldom.domnodelist;
    vnode     xmldom.domnode;

  begin
    vNodeList := pkg_messages_xml.GetNodesList(pnode, 'CorrespondentBank/CorrespondentsInformations/CorrespondentInformation');
    for i in 0 .. xmldom.getLength(vNodeList) - 1 loop
      vnode  := xmldom.item(vNodeList, i);
      result := ParseAccountInfo(vnode, pmessid, pmemberid, i, pversion_id);
      if result <> 0 then
        return result;
      end if;
    end loop;
    return result;
  EXCEPTION
    WHEN OTHERS THEN
      return - 3014; --Неверный формат данных в информации о корреспондентских счетах
      return result;
  end;

  function ParseMembersInfo(pnode       xmldom.domnode,
                            pmessid     in number,
                            pversion_id number) return number is
    result    number default 0;
    vNodeList xmldom.domnodelist;
    vnode     xmldom.domnode;
    ptemperr  number;
  begin
    vNodeList := pkg_messages_xml.GetNodesList(pnode, 'Participants/Participant');
    for i in 0 .. xmldom.getLength(vNodeList) - 1 loop
      vnode  := xmldom.item(vNodeList, i);
      result := ParseMemberInfo(vnode, pmessid, i, pversion_id);
      if result <> 0 then
        return result;
      end if;
      result := ParseAccountsInfo(vnode, pmessid, i, pversion_id);
      if result <> 0 then
        ptemperr := result;
      end if;
      result := ParseFoundersInfo(vnode, pmessid, i, pversion_id);
      if result <> 0 then
        return result;
      elsif ptemperr <> 0 then
        return ptemperr;
      end if;
    end loop;
    ------
    return result;
  end;

  function ParseRefersInfo(pnode   xmldom.domnode,
                           pmessid in number) return number is
    result    number default 0;
    vNodeList xmldom.domnodelist;
    vnode     xmldom.domnode;
    ptemperr  number;
  begin
    vNodeList := pkg_messages_xml.GetNodesList(pnode, 'References/Reference');
    for i in 0 .. xmldom.getLength(vNodeList) - 1 loop
      vnode  := xmldom.item(vNodeList, i);
      result := ParseReferInfo(vnode, pmessid, i);
      if result <> 0 then
        return result;
      end if;
    end loop;
    return result;
  end;

  function parseAnnounceXML(pmessid     in number,
                            pversion_id number) return number is
    result   number default 0;
    vres     number default 0;
    vnode    xmldom.domnode;
    pxmlclob clob;
    tempres  number default 0;

  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;

    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);
    /* result:=ParseMessageInfo(vnode,pmessid);
      if result<>0 then vres:=SetErrorCode(pmessid,result); end if;
     result:=ParseCmfInfo(vnode,pmessid);
      if result<>0 then vres:=SetErrorCode(pmessid,result); end if;
     result:=ParseCfmcontactInfo(vnode,pmessid);
      if result<>0 then vres:=SetErrorCode(pmessid,result); end if;
     result:=ParseOperationInfo(vnode,pmessid);
      if result<>0 then vres:=SetErrorCode(pmessid,result); end if;
     result:=ParseMembersInfo(vnode,pmessid);
      if result<>0 then vres:=SetErrorCode(pmessid,result); end if;
    */

    result := ParseMessageInfo(vnode, pmessid, pversion_id);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    result := ParseCmfInfo(vnode, pmessid, pversion_id);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    result := ParseCfmcontactInfo(vnode, pmessid, pversion_id);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    result := ParseOperationInfo(vnode, pmessid, pversion_id);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    result := ParseMembersInfo(vnode, pmessid, pversion_id);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    result := ParseRefersInfo(vnode, pmessid);

    if result <> 0 then
      vres    := SetErrorCode(pmessid, result);
      tempres := result;
    end if;
    if tempres = 0 then
      vres := SetErrorCode(pmessid, 0);
      return vres;
    end if;
    return tempres;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      return - 305; --Неверный XML документ  -- изменть
      return result;
  end;

  function parseCheckXML(pmessid in number) return number is
    result   number default 0;
    vnode    xmldom.domnode;
    pxmlclob clob;

    vCheck mess_cfm_check%rowtype;
  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vCheck.Mess_Cfm_Id := pmessid;

    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);

    vCheck.Errorcode := pkg_messages_xml.getsingleval(vnode, 'ErrorCode');
    vCheck.ErrorName := pkg_messages_xml.getsingleval(vnode, 'ErrorName');
    insert into mess_cfm_check
    values vcheck;

    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3008);
      return - 3008; --Неверный формат данных в квитанции
      return result;
  end;

  function parseDopInfXML(pmessid in number) return number is
    result   number default 0;
    vnode    xmldom.domnode;
    pxmlclob clob;

    vDopInf mess_cfm_dopinf%rowtype;
  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vDopInf.Mess_Cfm_Id := pmessid;

    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);

    vDopInf.Description := pkg_messages_xml.getsingleval(vnode, 'Description');
    vDopInf.Days_Count  := pkg_messages_xml.getsingleval(vnode, 'CountDays');
    insert into mess_cfm_dopinf
    values vDopInf;

    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3009);
      return - 3009; --Неверный формат данных в ответе на дополнительную информацию
      return result;
  end;

  function parseDopInfAnswXML(pmessid in number) return number is
    result    number default 0;
    vnode     xmldom.domnode;
    pnode     xmldom.domnode;
    vNodeList xmldom.domnodelist;
    pxmlclob  clob;

    vDopInfAnsw mess_cfm_dopinf_answ%rowtype;
  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vDopInfAnsw.Mess_Cfm_Id := pmessid;

    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);

    vNodeList := pkg_messages_xml.GetNodesList(pnode, 'Attachments/Attachment');
    for i in 0 .. xmldom.getLength(vNodeList) - 1 loop
      vnode                     := xmldom.item(vNodeList, i);
      vDopInfAnsw.Attach_Id     := i;
      vDopInfAnsw.Attach_Name   := pkg_messages_xml.getsingleval(vnode, 'FileName');
      vDopInfAnsw.Attach_Length := pkg_messages_xml.getsingleval(vnode, 'Length');
      insert into mess_cfm_dopinf_answ
      values vDopInfansw;
    end loop;

    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3010); -- Неверный формат данных в ответе на дополнительную информацию
      return - 3010; --Неверный XML документ
      return result;
  end;

  function parseUpdateRequestXML(pmessid in number) return number --Запрос на обновление
   is
    result number default 0;
    vnode  xmldom.domnode;

    pxmlclob clob;

    vUpdate mess_cfm_update_info%rowtype;
  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vUpdate.Mess_Cfm_Id := pmessid;

    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);

    vUpdate.Update_Version := pkg_messages_xml.getsingleval(vnode, 'RequestedVersion');
    -- vUpdate.Release_Date:=to_date(pkg_messages_xml.getsingleval(vnode,'ReleaseDate'),'yyyy-mm-dd');

    insert into mess_cfm_update_info
    values vupdate;
    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3013); --Неверный формат данных в запросе на обновление
      return - 3013; --Неверный XML документ
      return result;
  end;

  function ParseUpdateInfoXML(pmessid in number) return number is
    result     number default 0;
    vnode      xmldom.domnode;
    pnode      xmldom.domnode;
    pnode1     xmldom.domnode;
    vNodeList  xmldom.domnodelist;
    vNodeList1 xmldom.domnodelist;
    pxmlclob   clob;

    vUpdateVersion varchar2(300);
    vDateRelease   date;
    vmodulename    varchar2(100 char);

  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vnode := pkg_messages_xml.GetParsedXML(pxmlclob);

    --Головное обновление
    vUpdateVersion := pkg_messages_xml.getsingleval(vnode, 'UpdateVersion');
    vDateRelease   := to_date(pkg_messages_xml.getsingleval(vnode, 'ReleaseDate'), 'yyyy-mm-dd');
    insert into mess_cfm_update_info
      (mess_cfm_id,
       update_version,
       release_date)
    values
      (pmessid,
       vupdateversion,
       vDateRelease);

    if pkg_updates_cfm.existsInHisory(vUpdateVersion, vDateRelease) = 0 then
      insert into updates_cfm_hist
        (messid,
         version,
         daterelease)
      values
        (pmessid,
         vUpdateVersion,
         vDateRelease);

      --Используемые модули
      vNodeList := pkg_messages_xml.GetNodesList(vnode, 'Using/Use');
      for i in 0 .. xmldom.getLength(vnodelist) - 1 loop
        pnode       := xmldom.item(vnodelist, i);
        vmodulename := xslprocessor.valueOf(pnode, 'text()');
        insert into updates_cfm_hist_mod
          (version,
           modulename,
           messid)
        values
          (vUpdateVersion,
           vmodulename,
           pmessid);
      end loop;
    end if;

    --История версий обновлений
    vNodeList := pkg_messages_xml.GetNodesList(vnode, 'Histories/History');
    for i in 0 .. xmldom.getLength(vnodelist) - 1 loop
      pnode          := xmldom.item(vnodelist, i);
      vUpdateVersion := pkg_messages_xml.getsingleval(pnode, 'Version');
      vDateRelease   := to_date(pkg_messages_xml.getsingleval(pnode, 'ReleaseDate'), 'yyyy-mm-dd');

      if pkg_updates_cfm.existsInHisory(vUpdateVersion, vDateRelease) = 0 then
        insert into updates_cfm_hist
          (messid,
           version,
           daterelease)
        values
          (pmessid,
           vUpdateVersion,
           vDateRelease);

        --Используемые модули
        vnodelist1 := pkg_messages_xml.GetNodesList(pnode, 'Using/Use');
        for j in 0 .. xmldom.getLength(vnodelist1) - 1 loop
          pnode1      := xmldom.item(vnodelist1, j);
          vmodulename := xslprocessor.valueOf(pnode1, 'text()');
          insert into updates_cfm_hist_mod
            (version,
             modulename,
             messid)
          values
            (vUpdateVersion,
             vmodulename,
             pmessid);
        end loop;
      end if;
    end loop;

    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3011); --Неверный формат данных в информационнном сообщении об обновлении
      return - 3011; --Неверный XML документ
      return result;
  end;

  function ParseUpdateXML(pmessid in number) return number is
    result    number default 0;
    vnode     xmldom.domnode;
    vNodeList xmldom.domnodelist;
    pxmlclob  clob;

    vUpdateVersion varchar2(300);
    vDateRelease   date;
    vmodulename    varchar2(100 char);
    cursor moduleCur is
      select distinct modulename
      from updates_cfm_modulenames;

  begin
    select mess_xml
    into pxmlclob
    from mess_cfm_xml
    where mess_cfm_id = pmessid;
    vnode          := pkg_messages_xml.GetParsedXML(pxmlclob);
    vUpdateVersion := pkg_messages_xml.getsingleval(vnode, 'UpdateVersion');
    vDateRelease   := to_date(pkg_messages_xml.getsingleval(vnode, 'ReleaseDate'), 'yyyy-mm-dd');
    insert into mess_cfm_update_info
      (mess_cfm_id,
       update_version,
       release_date)
    values
      (pmessid,
       vupdateversion,
       vDateRelease);

    insert into updates_cfm_hist
      (messid,
       version,
       daterelease)
    values
      (pmessid,
       vUpdateVersion,
       vDateRelease);

    --Используемые модули
    vnodelist := xslprocessor.selectNodes(vnode, 'UpdateInformations/UpdateInformation/Using/Use/ModuleName');
    for i in 0 .. xmldom.getLength(vnodelist) - 1 loop
      vnode       := xmldom.item(vnodelist, i);
      vmodulename := xslprocessor.valueOf(vnode, 'text()');
      insert into updates_cfm_modulenames
        (modulename)
      values
        (vmodulename);
    end loop;

    for modulerow in moduleCur loop
      insert into updates_cfm_hist_mod
        (version,
         modulename,
         messid)
      values
        (vUpdateVersion,
         modulerow.modulename,
         pmessid);
    end loop;

    return result;
  EXCEPTION
    WHEN no_data_found THEN
      return - 1000;
    WHEN OTHERS THEN
      result := SetErrorCode(pmessid, -3012); --Неверный формат данных в информационнном сообщении собновлением
      return - 3012; --Неверный XML документ
      return result;
  end;

  function SetErrorCode(pmessid  in number,
                        perrcode in number) return number is
  begin
    update mess_cfm
    set int_err_code = perrcode
    where mess_cfm_id = pmessid;
    return 0;

  exception
    when no_data_found then
      return - 1000;
  end;

  function getcolumn_length(p_table_name in varchar2,
                            p_name       in varchar2,
                            p_length     out number) return number is
    result number default 0;
  begin

    select data_length
    into p_length
    from USER_TAB_COLUMNS
    where table_name = upper(p_table_name)
    and column_name = upper(p_name);
    return result;

  exception
    when others then
      return - 2099;

  end;

  function GetOuterAnnounceXML_2(PXMLSCH1 xmltype) return xmltype is
    pXML    xmltype;
    PXMLSCH xmltype;
    i       number default 1;
    j       number default 1;
    --i number
  begin
    begin
      select updateXml(PXMLSCH1,
                       --     'Root/PersonalData/OrganisationCode/text()',
                       --       pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/PersonalData/OrganisationCode/text()'),1005),
                       --     'Root/MessageInformation/ViewOperationId/text()',
                       --       pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/MessageInformation/ViewOperationId/text()'),21004),
                       --     'Root/MessageInformation/EknpId/text()',
                       --       pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/MessageInformation/EknpId/text()'),21017),
                       --     'Root/MessageInformation/CurrencyCodeId/text()',
                       --       pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/MessageInformation/CurrencyCodeId/text()'),21018),
                       --     'Root/MessageInformation/ReasonFilingId/text()',
                       --       pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/MessageInformation/ReasonFilingId/text()'),21011),
                       'Root/MessageInformation/SuspicionsCriterians/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH1, 'Root/MessageInformation/SuspicionsCriterians/text()'), 21012),
                       'Root/MessageInformation/DocumentType/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH1, 'Root/MessageInformation/DocumentType/text()'), 21009),
                       'Root/MessageInformation/OperationStatusId/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH1, 'Root/MessageInformation/OperationStatusId/text()'), 21010),
                       'Root/MessageInformation/SuspicionFirst/text()',
                       pkg_analytic.GetShortDescription(extractvalue(PXMLSCH1, 'Root/MessageInformation/SuspicionFirst/text()'), 21008),
                       'Root/MessageInformation/SuspicionSecond/text()',
                       pkg_analytic.GetShortDescription(extractvalue(PXMLSCH1, 'Root/MessageInformation/SuspicionSecond/text()'), 21008),
                       'Root/MessageInformation/SuspicionThird/text()',
                       pkg_analytic.GetShortDescription(extractvalue(PXMLSCH1, 'Root/MessageInformation/SuspicionThird/text()'), 21008))
      into pXML
      from dual;
      PXMLSCH := pxml;

      select appendChildXML(PXMLSCH, 'Root/MessageInformation/ReasonFilingId', XMLType('<Descr>' || pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/MessageInformation/ReasonFilingId/text()'), 21011) || '</Descr>'))
      into pxml
      from dual;
    exception
      when others then
        pXML := PXMLSCH1;
    end;

    PXMLSCH := pxml;

    begin
      loop
        if (xmltype.existsNode(pxml, 'Root/Participants/Participant[' || to_char(i) || ']') = 1) then
          select updateXml(PXMLSCH,
                           'Root/Participants/Participant[' || to_char(i) || ']/MemberId/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/MemberId/text()'), 21013),
                           'Root/Participants/Participant[' || to_char(i) || ']/ParticipantsView/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/ParticipantsView/text()'), 21006),
                           --     'Root/Participants/Participant['||to_char(i)||']/ParticipantsType/text()',
                           --       pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/Participants/Participant['||to_char(i)||']/ParticipantsType/text()'),10),
                           'Root/Participants/Participant[' || to_char(i) || ']/IsClientSubject/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/IsClientSubject/text()'), 21020),
                           'Root/Participants/Participant[' || to_char(i) || ']/MemberCommunityCityCode/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/MemberCommunityCityCode/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/ForeignPerson/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/ForeignPerson/text()'), 21014),
                           'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/BankAddress/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/BankAddress/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationAc/URAddress/Country/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationAc/URAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationAc/ACAddress/Country/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationAc/ACAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationIp/URAddress/Country/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationIp/URAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationIp/ACAddress/Country/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationIp/ACAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationUr/URAddress/Country/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationUr/URAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationUr/ACAddress/Country/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationUr/ACAddress/Country/text()'), 21019)
                           --     'Root/Participants/Participant['||to_char(i)||']/AdditionalPersonInfo/AdditionalInformationAc/DocumentIdentity/text()',
                           --       pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/Participants/Participant['||to_char(i)||']/AdditionalPersonInfo/AdditionalInformationAc/DocumentIdentity/text()'),20100) ,
                           --     'Root/Participants/Participant['||to_char(i)||']/AdditionalPersonInfo/AdditionalInformationIp/DocumentIdentity/text()',
                           --       pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/Participants/Participant['||to_char(i)||']/AdditionalPersonInfo/AdditionalInformationIp/DocumentIdentity/text()'),20100)

                           )
          into pXML
          from dual;
          PXMLSCH := pxml;
          select appendChildXML(PXMLSCH,
                                'Root/Participants/Participant[' || to_char(i) || ']/ParticipantsType',
                                XMLType('<Descr>' || pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/ParticipantsType/text()'), 10) || '</Descr>'))
          into pxml
          from dual;

          PXMLSCH := pxml;
          j       := 1;
          loop
            if (xmltype.existsNode(pxml, 'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/CorrespondentsInformations/CorrespondentInformation[' || to_char(j) || ']') = 1) then
              select updateXml(PXMLSCH,
                               'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/CorrespondentsInformations/CorrespondentInformation[' || to_char(j) || ']/BankAddress/text()',
                               pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/CorrespondentsInformations/CorrespondentInformation[' || to_char(j) || ']/BankAddress/text()'),
                                                           21019))
              into pXML
              from dual;
            else
              exit;
            end if;
            PXMLSCH := pxml;
            j       := j + 1;
          end loop;
          j := 1;
          loop
            if (xmltype.existsNode(pxml, 'Root/Participants/Participant[' || to_char(i) || ']/Founders/Founder[' || to_char(j) || ']') = 1) then
              select updateXml(PXMLSCH,
                               'Root/Participants/Participant[' || to_char(i) || ']/Founders/Founder[' || to_char(j) || ']/MemberCommunityCityCode/text()',
                               pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/Participants/Participant[' || to_char(i) || ']/Founders/Founder[' || to_char(j) || ']/MemberCommunityCityCode/text()'), 21019))
              into pXML
              from dual;
            else
              exit;

            end if;
            PXMLSCH := pxml;
            j       := j + 1;
          end loop;
        else
          exit;
        end if;
        i := i + 1;
      end loop;
    exception
      when others then
        pXML := PXMLSCH;
    end;
    return pxml;
  end;

  function getouterannouncexml_3(pxmlsch1 xmltype) return xmltype is
    pxml    xmltype;
    pxmlsch xmltype;
    i       number default 1;
    j       number default 1;
    --i number
  begin
    begin
      select updatexml(pxmlsch1,
                       'Root/PersonalData/OrganisationOPF/text()',
                       pkg_analytic.getdescription(extractvalue(pxmlsch1, 'Root/PersonalData/OrganisationOPF/text()'), 31003),
                       'Root/MessageInformation/SuspicionsCriterians/text()',
                       pkg_analytic.getdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/SuspicionsCriterians/text()'), 41012),
                       'Root/MessageInformation/DocumentType/text()',
                       pkg_analytic.getdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/DocumentType/text()'), 21009),
                       'Root/MessageInformation/OperationStatusId/text()',
                       pkg_analytic.getdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/OperationStatusId/text()'), 21010),
                       'Root/MessageInformation/SuspicionFirst/text()',
                       pkg_analytic.getshortdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/SuspicionFirst/text()'), 41008),
                       'Root/MessageInformation/SuspicionSecond/text()',
                       pkg_analytic.getshortdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/SuspicionSecond/text()'), 41008),
                       'Root/MessageInformation/SuspicionThird/text()',
                       pkg_analytic.getshortdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/SuspicionThird/text()'), 41008) --
                       )
      into pxml
      from dual;
      pxmlsch := pxml;
      select appendchildxml(pxmlsch, 'Root/MessageInformation/ReasonFilingId', xmltype('<Descr>' || pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/MessageInformation/ReasonFilingId/text()'), 21011) || '</Descr>')) --
      into pxml
      from dual;
    exception
      when others then
        pxml := pxmlsch1;
    end;
    pxmlsch := pxml;
    begin
      loop
        if (xmltype.existsnode(pxml, 'Root/Participants/Participant[' || to_char(i) || ']') = 1) then
          select updatexml(pxmlsch,
                           'Root/Participants/Participant[' || to_char(i) || ']/MemberId/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/MemberId/text()'), 21013),
                           'Root/Participants/Participant[' || to_char(i) || ']/ParticipantsView/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/ParticipantsView/text()'), 41006),
                           'Root/Participants/Participant[' || to_char(i) || ']/IsClientSubject/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/IsClientSubject/text()'), 21020),
                           'Root/Participants/Participant[' || to_char(i) || ']/MemberCommunityCityCode/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/MemberCommunityCityCode/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/ForeignPerson/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/ForeignPerson/text()'), 21014),
                           'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/BankAddress/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/BankAddress/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationAc/URAddress/Country/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationAc/URAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationAc/ACAddress/Country/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationAc/ACAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationIp/URAddress/Country/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationIp/URAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationIp/ACAddress/Country/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationIp/ACAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationUr/URAddress/Country/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationUr/URAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationUr/ACAddress/Country/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationUr/ACAddress/Country/text()'), 21019),
                           'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationUr/ParticipantOPF/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/AdditionalPersonInfo/AdditionalInformationUr/ParticipantOPF/text()'), 31003)
                           --     'Root/Participants/Participant['||to_char(i)||']/AdditionalPersonInfo/AdditionalInformationAc/DocumentIdentity/text()',
                           --       pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/Participants/Participant['||to_char(i)||']/AdditionalPersonInfo/AdditionalInformationAc/DocumentIdentity/text()'),20100) ,
                           --     'Root/Participants/Participant['||to_char(i)||']/AdditionalPersonInfo/AdditionalInformationIp/DocumentIdentity/text()',
                           --       pkg_analytic.GetDescription(extractvalue(PXMLSCH,'Root/Participants/Participant['||to_char(i)||']/AdditionalPersonInfo/AdditionalInformationIp/DocumentIdentity/text()'),20100)
                           )
          into pxml
          from dual;
          pxmlsch := pxml;
          select appendchildxml(pxmlsch,
                                'Root/Participants/Participant[' || to_char(i) || ']/ParticipantsType',
                                xmltype('<Descr>' || pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/ParticipantsType/text()'), 10) || '</Descr>'))
          into pxml
          from dual;
          pxmlsch := pxml;
          j       := 1;
          loop
            if (xmltype.existsnode(pxml, 'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/CorrespondentsInformations/CorrespondentInformation[' || to_char(j) || ']') = 1) then
              select updatexml(pxmlsch,
                               'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/CorrespondentsInformations/CorrespondentInformation[' || to_char(j) || ']/BankAddress/text()',
                               pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/CorrespondentsInformations/CorrespondentInformation[' || to_char(j) || ']/BankAddress/text()'),
                                                           21019))
              into pxml
              from dual;
            else
              exit;
            end if;
            pxmlsch := pxml;
            j       := j + 1;
          end loop;
          j := 1;
          loop
            if (xmltype.existsnode(pxml, 'Root/Participants/Participant[' || to_char(i) || ']/Founders/Founder[' || to_char(j) || ']') = 1) then
              select updatexml(pxmlsch,
                               'Root/Participants/Participant[' || to_char(i) || ']/Founders/Founder[' || to_char(j) || ']/MemberCommunityCityCode/text()',
                               pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/Founders/Founder[' || to_char(j) || ']/MemberCommunityCityCode/text()'), 21019),
                               'Root/Participants/Participant[' || to_char(i) || ']/Founders/Founder[' || to_char(j) || ']/FounderOPF/text()',
                               pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/Founders/Founder[' || to_char(j) || ']/FounderOPF/text()'), 31003))
              into pxml
              from dual;
            else
              exit;
            end if;
            pxmlsch := pxml;
            j       := j + 1;
          end loop;
        else
          exit;
        end if;
        i := i + 1;
      end loop;
    exception
      when others then
        pxml := pxmlsch;
    end;
    return pxml;
  end;

  function GetOuterAnnounceXML(PXMLSCH1 xmltype,
                               pversion number) return xmltype is
  begin
    case pversion
      when 2 then
        return GetOuterAnnounceXML_2(PXMLSCH1);
      else
        return GetOuterAnnounceXML_3(PXMLSCH1);
    end case;
  end;

end PKG_MESS_CFM_2;
/
 

CREATE OR REPLACE PACKAGE KFM."PKG_MESS_CFM_2_1" AS
  --
  function mess_cfm_2_empty_xml return xmltype;
  --
  function mess_cfm_2_xml(p_MESS_CFM_ID in NUMBER) return xmltype;
  --данные из таблиц mess_cfm
  function personal_data_2_xml_v2(p_MESS_CFM_ID in NUMBER) return xmltype;
  --данные о паспорте из таблицы mess_cfm, данные о пользователе из таблицы users
  function personal_data_2_xml_v3(p_MESS_CFM_ID in NUMBER) return xmltype;
  --
  function message_information_2_xml_v1 return xmltype;
  --
  function message_information_2_xml_v2(p_MESS_CFM_ID in NUMBER) return xmltype;
  --
  function refers_2_xml(p_MESS_CFM_ID in NUMBER) return xmltype;
  --
  function participants_2_xml(p_MESS_CFM_ID in NUMBER) return xmltype;
  --
  function correspondents_info_2_xml(p_MESS_CFM_ID in NUMBER,
                                     p_MEMBER_ID   in NUMBER) return xmltype;
  --
  function founders_2_xml(p_MESS_CFM_ID in NUMBER,
                          p_MEMBER_ID   in NUMBER) return xmltype;
  --
  function additional_person_info_2_xml(p_MESS_CFM_ID in NUMBER,
                                        p_MEMBER_ID   in NUMBER) return xmltype;
  --
END PKG_MESS_CFM_2_1;
/

CREATE OR REPLACE PACKAGE BODY KFM."PKG_MESS_CFM_2_1" AS
  --экспорт данных в xml согласно версии 3
  --
  function mess_cfm_2_empty_xml return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("Root",
                      XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi", 'http://www.w3.org/2001/XMLSchema' as "xmlns:xsd"),
                      pkg_rqst_cfm.rqst_personal_data,
                      message_information_2_xml_v1,
                      XMLElement("Version", 'C6EC3F8D-2BE1-46A9-841B-5CF1130F0A12'),
                      XMLElement("DocumentUniqueIdentifier", sys_guid()))
    INTO v_result
    FROM dual;

    return v_result;
  end;
  --
  function mess_cfm_2_xml(p_MESS_CFM_ID in NUMBER) return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("Root",
                      XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi", 'http://www.w3.org/2001/XMLSchema' as "xmlns:xsd"),
                      personal_data_2_xml_v3(p_MESS_CFM_ID),
                      message_information_2_xml_v2(p_MESS_CFM_ID),
                      refers_2_xml(p_MESS_CFM_ID),
                      participants_2_xml(p_MESS_CFM_ID),
                      XMLElement("Version", 'C6EC3F8D-2BE1-46A9-841B-5CF1130F0A12'),
                      XMLElement("DocumentUniqueIdentifier", ta.mess_form_guid))
    INTO v_result
    FROM mess_cfm ta
    WHERE ta.MESS_CFM_ID = p_MESS_CFM_ID;

    return v_result;
  end;
  --
  function personal_data_2_xml_v2(p_MESS_CFM_ID in NUMBER) return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("PersonalData",
                      XMLElement("FirstName", tb.contact_secondname),
                      XMLElement("SecondName", tb.contact_firstname),
                      XMLElement("MiddleName", tb.contact_middlename),
                      XMLElement("JobName", tb.contact_job),
                      XMLElement("Phone", tb.contact_phone),
                      XMLElement("Email", tb.contact_email),
                      --
                      XMLElement("HeadName", ta.cfm_ac_firstname),
                      XMLElement("HeadSurname", ta.cfm_ac_secondname),
                      XMLElement("HeadMidleName", ta.cfm_ac_middlename),
                      --
                      nvl2(ta.cfm_code, XMLElement("OrganisationCode", ta.cfm_code), XMLElement("OrganisationCode", XMLATTRIBUTES('true' as "xsi:nil"))),
                      XMLElement("Organisation", ta.cfm_name),
                      XMLElement("OrganisationOPF", ta.cfm_ur_opf_code),
                      XMLElement("OrganisationArea", XMLATTRIBUTES(ta.cfm_seat_area_code as "Code"), ta.cfm_seat_area),
                      XMLElement("OrganisationCity", XMLATTRIBUTES(ta.cfm_seat_sity_code as "Code"), ta.cfm_seat_sity),
                      XMLElement("OrganisationDistrict", XMLATTRIBUTES(ta.cfm_seat_region_code as "Code"), ta.cfm_seat_region),
                      XMLElement("OrganisationStreet", XMLATTRIBUTES(ta.cfm_seat_street_code as "Code"), ta.cfm_seat_street),
                      XMLElement("OrganisationHouse", XMLATTRIBUTES(ta.cfm_seat_house_code as "Code"), ta.cfm_seat_house),
                      XMLElement("OrganisationOffice", XMLATTRIBUTES(ta.cfm_seat_office_code as "Code"), ta.cfm_seat_office),
                      XMLElement("OrganisationPostalIndex", ta.cfm_seat_postcode),
                      XMLElement("RNN", ta.cfm_taxcode),
                      XMLElement("IINBIN", ta.cfm_maincode),
                      CASE ta.Cfm_Isac
                        WHEN 1 THEN
                         XMLElement("AdditionalAcData",
                                    XMLATTRIBUTES('True' as "IsAc"),
                                    XMLElement("DocumentIdentity", ta.Cfm_Doc_Typecode),
                                    XMLElement("SeriesDocIdentity", ta.Cfm_Doc_Series),
                                    XMLElement("NumberDocIdentity", ta.Cfm_Doc_Number),
                                    XMLElement("DateIssuance", to_char(ta.Cfm_Doc_Date, 'dd.mm.yyyy')),
                                    XMLElement("DocumentIssued", ta.Cfm_Doc_Whom))
                        ELSE
                         XMLElement("AdditionalAcData",
                                    XMLATTRIBUTES('False' as "IsAc"),
                                    XMLElement("DocumentIdentity", ta.Cfm_Doc_Typecode),
                                    XMLElement("SeriesDocIdentity", ta.Cfm_Doc_Series),
                                    XMLElement("NumberDocIdentity", ta.Cfm_Doc_Number),
                                    XMLElement("DateIssuance", to_char(ta.Cfm_Doc_Date, 'dd.mm.yyyy')),
                                    XMLElement("DocumentIssued", ta.Cfm_Doc_Whom))
                      END) AS xmltype
    INTO v_result
    FROM mess_cfm_announce_subj ta
    LEFT OUTER JOIN mess_cfm_announce_cont tb
    ON ta.MESS_CFM_ID = tb.MESS_CFM_ID
    WHERE ta.MESS_CFM_ID = p_MESS_CFM_ID;

    return v_result;
  end;
  --
  function personal_data_2_xml_v3(p_MESS_CFM_ID in NUMBER) return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("PersonalData",
                      XMLElement("FirstName", tb.lastname),
                      XMLElement("SecondName", tb.firstname),
                      XMLElement("MiddleName", tb.middlename),
                      XMLElement("JobName", tb.jobname),
                      XMLElement("Phone", tb.phones),
                      XMLElement("Email", tb.emails),
                      --
                      XMLElement("HeadName", ta.cfm_ac_firstname),
                      XMLElement("HeadSurname", ta.cfm_ac_secondname),
                      XMLElement("HeadMidleName", ta.cfm_ac_middlename),
                      --
                      nvl2(ta.cfm_code, XMLElement("OrganisationCode", ta.cfm_code), XMLElement("OrganisationCode", XMLATTRIBUTES('true' as "xsi:nil"))),
                      XMLElement("Organisation", ta.cfm_name),
                      XMLElement("OrganisationOPF", ta.cfm_ur_opf_code),
                      XMLElement("OrganisationArea", XMLATTRIBUTES(ta.cfm_seat_area_code as "Code"), ta.cfm_seat_area),
                      XMLElement("OrganisationCity", XMLATTRIBUTES(ta.cfm_seat_sity_code as "Code"), ta.cfm_seat_sity),
                      XMLElement("OrganisationDistrict", XMLATTRIBUTES(ta.cfm_seat_region_code as "Code"), ta.cfm_seat_region),
                      XMLElement("OrganisationStreet", XMLATTRIBUTES(ta.cfm_seat_street_code as "Code"), ta.cfm_seat_street),
                      XMLElement("OrganisationHouse", XMLATTRIBUTES(ta.cfm_seat_house_code as "Code"), ta.cfm_seat_house),
                      XMLElement("OrganisationOffice", XMLATTRIBUTES(ta.cfm_seat_office_code as "Code"), ta.cfm_seat_office),
                      XMLElement("OrganisationPostalIndex", ta.cfm_seat_postcode),
                      XMLElement("RNN", ta.cfm_taxcode),
                      XMLElement("IINBIN", ta.cfm_maincode),
                      CASE ta.Cfm_Isac
                        WHEN 1 THEN
                         XMLElement("AdditionalAcData",
                                    XMLATTRIBUTES('True' as "IsAc"),
                                    XMLElement("DocumentIdentity", ta.Cfm_Doc_Typecode),
                                    XMLElement("SeriesDocIdentity", ta.Cfm_Doc_Series),
                                    XMLElement("NumberDocIdentity", ta.Cfm_Doc_Number),
                                    XMLElement("DateIssuance", to_char(ta.Cfm_Doc_Date, 'dd.mm.yyyy')),
                                    XMLElement("DocumentIssued", ta.Cfm_Doc_Whom))
                        ELSE
                         XMLElement("AdditionalAcData",
                                    XMLATTRIBUTES('False' as "IsAc"),
                                    XMLElement("DocumentIdentity", ta.Cfm_Doc_Typecode),
                                    XMLElement("SeriesDocIdentity", ta.Cfm_Doc_Series),
                                    XMLElement("NumberDocIdentity", ta.Cfm_Doc_Number),
                                    XMLElement("DateIssuance", to_char(ta.Cfm_Doc_Date, 'dd.mm.yyyy')),
                                    XMLElement("DocumentIssued", ta.Cfm_Doc_Whom))
                      END) AS xmltype
    INTO v_result
    FROM mess_cfm_announce_subj ta,
         users                  tb
    WHERE ta.MESS_CFM_ID = p_MESS_CFM_ID
    AND tb.userid = pkg_users.GetCurrentUserId; ---- исправить

    return v_result;
  end;
  --
  function message_information_2_xml_v1 return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("MessageInformation",
                      XMLElement("DocumentType", 1),
                      --XMLElement("MessageNumber", null),
                      XMLElement("MessageNumber", pkg_messages_cfm.GetTempMessNumb),
                      XMLElement("LastModifyDate", to_char(sysdate, 'dd.mm.yyyy')),
                      XMLElement("TransactionDate", null),
                      XMLElement("MessTransDate", null),
                      XMLElement("ViewOperationId", null),
                      XMLElement("EknpId", XMLATTRIBUTES('False' as "IsEknpNotSetup"), null),
                      XMLElement("OperationNumber", null),
                      XMLElement("DocOperationReason", null),
                      XMLElement("DocOperationDate", null),
                      XMLElement("DocOperationNumber", null),
                      XMLElement("CurrencyCodeId", null),
                      XMLElement("AmountCurrency", null),
                      XMLElement("AmountCurrencyTenge", null),
                      XMLElement("OperationStatusId", null),
                      XMLElement("ReasonFilingId", null),
                      XMLElement("SuspicionsCriterians", null),
                      XMLElement("SuspicionFirst", null),
                      XMLElement("SuspicionSecond", null),
                      XMLElement("SuspicionThird", null),
                      XMLElement("DescriptionDifficulties", null),
                      XMLElement("MoreInformation", null),
                      XMLElement("ParticipantCount", null),
                      XMLElement("MerchTypes", null),
                      XMLElement("MerchReginfo", null),
                      XMLElement("ReferCount", null)) AS xmltype
    INTO v_result
    FROM dual;

    return v_result;
  end;
  --
  function message_information_2_xml_v2(p_MESS_CFM_ID in NUMBER) return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("MessageInformation",
                      XMLElement("DocumentType", ta.mess_type),
                      XMLElement("MessageNumber", ta.mess_number),
                      XMLElement("LastModifyDate", to_char(ta.mess_date, 'dd.mm.yyyy')),
                      XMLElement("TransactionDate", to_char(nvl(tb.Oper_Trans_Date, ta.mess_Trans_Date), 'dd.mm.yyyy hh24:mi:ss')),
                      XMLElement("MessTransDate", to_char(nvl(tb.Oper_Trans_Date, ta.mess_Trans_Date), 'dd.mm.yyyy hh24:mi:ss')),
                      XMLElement("ViewOperationId", tb.oper_idview),
                      XMLElement("EknpId", XMLATTRIBUTES(pkg_common.getbool(tb.oper_isnotidtyped) as "IsEknpNotSetup"), tb.oper_idtype),
                      XMLElement("OperationNumber", tb.oper_number),
                      XMLElement("DocOperationReason", tb.oper_reason),
                      XMLElement("DocOperationDate", to_char(tb.oper_doc_date, 'dd.mm.yyyy')),
                      XMLElement("DocOperationNumber", tb.oper_doc_number),
                      XMLElement("CurrencyCodeId", tb.oper_currency_code),
                      XMLElement("AmountCurrency", tb.oper_currency_amount),
                      XMLElement("AmountCurrencyTenge", tb.oper_tenge_amount),
                      XMLElement("OperationStatusId", ta.mess_oper_status),
                      XMLElement("ReasonFilingId", ta.mess_reason_code),
                      XMLElement("SuspicionsCriterians", ta.mess_suspic_code),
                      XMLElement("SuspicionFirst", tb.oper_susp_first),
                      XMLElement("SuspicionSecond", tb.oper_susp_second),
                      XMLElement("SuspicionThird", tb.oper_susp_third),
                      XMLElement("DescriptionDifficulties", tb.oper_difficulties),
                      XMLElement("MoreInformation", tb.oper_dopinfo),
                      XMLElement("ParticipantCount", tb.oper_members_count),
                      XMLElement("MerchTypes", tb.oper_merch_types),
                      XMLElement("MerchReginfo", tb.oper_merch_reginfo),
                      XMLElement("ReferCount", tb.oper_refers_count)) AS xmltype
    INTO v_result
    FROM mess_cfm_announce_info ta
    LEFT OUTER JOIN mess_cfm_announce_oper tb
    ON ta.MESS_CFM_ID = tb.MESS_CFM_ID
    WHERE ta.MESS_CFM_ID = p_MESS_CFM_ID;

    return v_result;
  end;
  --
  function refers_2_xml(p_MESS_CFM_ID in NUMBER) return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("References",
                      XMLAgg(XMLElement("Reference",
                                        XMLElement("ReferenceId", ta.referid),
                                        XMLElement("ReferenceOperationNumber", ta.refer_doc_oper),
                                        XMLElement("ReferenceDocOperationDate", to_char(ta.refer_doc_date, 'dd.mm.yyyy')),
                                        XMLElement("ReferencerDocOperationNumber", ta.refer_doc_num)))) AS xmltype
    INTO v_result
    FROM mess_cfm_refer ta
    WHERE ta.MESS_CFM_ID = p_MESS_CFM_ID;

    return v_result;
  end;
  --
  function participants_2_xml(p_MESS_CFM_ID in NUMBER) return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("Participants",
                      XMLAgg(XMLElement("Participant",
                                        XMLElement("MemberId", ta.member_membercode),
                                        XMLElement("ParticipantsView", ta.member_kind),
                                        XMLElement("ParticipantsType", ta.member_type),
                                        XMLElement("IsClientSubject", ta.member_isclient),
                                        XMLElement("MemberCommunityCityCode", ta.member_residence_countrycode),
                                        XMLElement("ForeignPerson", ta.member_foreign),
                                        XMLElement("CorrespondentBank",
                                                   XMLElement("AccountNumber", ta.member_bank_account),
                                                   XMLElement("Name", ta.member_bank_name),
                                                   XMLElement("Code", ta.member_bank_code),
                                                   XMLElement("BankCity", ta.member_bank_city),
                                                   XMLElement("BankAddress", ta.member_bank_address),
                                                   XMLElement("BankOffshoreAddr", ta.MEMBER_BANK_OFFSHORE_ADDR),
                                                   correspondents_info_2_xml(p_MESS_CFM_ID, ta.member_id)),
                                        XMLElement("RNN", ta.member_taxcode),
                                        XMLElement("OKED", ta.member_oked),
                                        XMLElement("IndividualIssue", ta.member_maincode),
                                        XMLElement("PhoneNumber", ta.member_phone),
                                        XMLElement("Email", ta.member_email),
                                        XMLElement("AdditionalInformation", ta.member_comments),
                                        XMLElement("MoneyTransSys", ta.money_trans_sys),
                                        founders_2_xml(p_MESS_CFM_ID, ta.member_id),
                                        additional_person_info_2_xml(p_MESS_CFM_ID, ta.member_id)))) AS xmltype
    INTO v_result
    FROM mess_cfm_announce_memb ta
    WHERE ta.MESS_CFM_ID = p_MESS_CFM_ID;

    return v_result;
  end;
  --
  function correspondents_info_2_xml(p_MESS_CFM_ID in NUMBER,
                                     p_MEMBER_ID   in NUMBER) return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("CorrespondentsInformations",
                      XMLAgg(XMLElement("CorrespondentInformation", XMLElement("AccountNumber", ta.accountnumber), XMLElement("BankName", ta.bankname), XMLElement("BankCode", ta.bankcode), XMLElement("BankAddress", ta.bankaddress)))) AS xmltype
    INTO v_result
    FROM mess_cfm_announce_accounts ta
    WHERE ta.MESS_CFM_ID = p_MESS_CFM_ID
    and ta.MEMBERID = p_MEMBER_ID;

    return v_result;
  end;
  --
  function founders_2_xml(p_MESS_CFM_ID in NUMBER,
                          p_MEMBER_ID   in NUMBER) return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("Founders",
                      XMLAgg(CASE ta.founder_type
                               WHEN 1 THEN
                                XMLElement("Founder",
                                           XMLElement("FounderType", ta.founder_type),
                                           XMLElement("FounderOPF", ta.founder_ur_opf_code),
                                           XMLElement("Name", ta.founder_ur_name),
                                           XMLElement("FirstName", null),
                                           XMLElement("SecondName", null),
                                           XMLElement("MiddleName", null),
                                           XMLElement("MemberCommunityCityCode", ta.founder_ur_residence_c_code))
                               WHEN 2 THEN
                                XMLElement("Founder",
                                           XMLElement("FounderType", ta.founder_type),
                                           XMLElement("FounderOPF", null),
                                           XMLElement("Name", null),
                                           XMLElement("FirstName", ta.founder_ac_firstname),
                                           XMLElement("SecondName", ta.founder_ac_secondname),
                                           XMLElement("MiddleName", ta.founder_ac_middlename),
                                           XMLElement("MemberCommunityCityCode", ta.founder_ur_residence_c_code))
                               WHEN 3 THEN
                                XMLElement("Founder",
                                           XMLElement("FounderType", ta.founder_type),
                                           XMLElement("FounderOPF", null),
                                           XMLElement("Name", null),
                                           XMLElement("FirstName", ta.founder_ac_firstname),
                                           XMLElement("SecondName", ta.founder_ac_secondname),
                                           XMLElement("MiddleName", ta.founder_ac_middlename),
                                           XMLElement("MemberCommunityCityCode", null))
                             END)) AS xmltype
    INTO v_result
    FROM mess_cfm_announce_found ta
    WHERE ta.MESS_CFM_ID = p_MESS_CFM_ID
    and ta.MEMBER_ID = p_MEMBER_ID;

    return v_result;
  end;
  --
  function additional_person_info_2_xml(p_MESS_CFM_ID in NUMBER,
                                        p_MEMBER_ID   in NUMBER) return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT CASE ta.member_type
             WHEN 1 THEN
              XMLElement("AdditionalPersonInfo",
                         XMLElement("PersonType", 1),
                         XMLElement("AdditionalInformationUr",

                                       XMLElement("URAddress",
                                                  XMLElement("Country", member_reg_counrycode),
                                                  XMLElement("Area", XMLATTRIBUTES(ta.member_reg_area_code as "Code"), ta.member_reg_area),
                                                  XMLElement("District", XMLATTRIBUTES(ta.member_reg_region_code as "Code"), ta.member_reg_region),
                                                  XMLElement("Town", XMLATTRIBUTES(ta.member_reg_sity_code as "Code"), ta.member_reg_sity),
                                                  XMLElement("Street", XMLATTRIBUTES(ta.member_reg_street_code as "Code"), ta.member_reg_street),
                                                  XMLElement("HomeNumber", XMLATTRIBUTES(ta.member_reg_house_code as "Code"), ta.member_reg_house),
                                                  XMLElement("OfficeNumber", XMLATTRIBUTES(ta.member_reg_office_code as "Code"), ta.member_reg_office),
                                                  XMLElement("PostalCode", ta.member_reg_postcode)),

                                       XMLElement("ACAddress",
                                                  XMLElement("Country", ta.member_seat_counrycode),
                                                  XMLElement("Area", XMLATTRIBUTES(ta.member_seat_area_code as "Code"), ta.member_seat_area),
                                                  XMLElement("District", XMLATTRIBUTES(ta.member_seat_region_code as "Code"), ta.member_seat_region),
                                                  XMLElement("Town", XMLATTRIBUTES(ta.member_seat_sity_code as "Code"), ta.member_seat_sity),
                                                  XMLElement("Street", XMLATTRIBUTES(ta.member_seat_street_code as "Code"), ta.member_seat_street),
                                                  XMLElement("HomeNumber", XMLATTRIBUTES(ta.member_seat_house_code as "Code"), ta.member_seat_house),
                                                  XMLElement("OfficeNumber", XMLATTRIBUTES(ta.member_seat_office_code as "Code"), ta.member_seat_office),
                                                  XMLElement("PostalCode", ta.member_seat_postcode)),

                                    XMLElement("FullName", XMLATTRIBUTES(pkg_common.GetBool(ta.member_isnotnamed) as "IsFullNameSetup"), ta.member_ur_name),
                                    XMLElement("FirstHead", XMLElement("FirstName", ta.member_ur_fisthead_firstname), XMLElement("SecondName", ta.member_ur_fisthead_secondname), XMLElement("MiddleName", ta.member_ur_fisthead_middlename)),
                                    XMLElement("ParticipantOPF", ta.member_ur_opf_code)))
             WHEN 2 THEN
              XMLElement("AdditionalPersonInfo",
                         XMLElement("PersonType", 2),
                         XMLElement("AdditionalInformationAc",

                                       XMLElement("URAddress",
                                                  XMLElement("Country", member_reg_counrycode),
                                                  XMLElement("Area", XMLATTRIBUTES(ta.member_reg_area_code as "Code"), ta.member_reg_area),
                                                  XMLElement("District", XMLATTRIBUTES(ta.member_reg_region_code as "Code"), ta.member_reg_region),
                                                  XMLElement("Town", XMLATTRIBUTES(ta.member_reg_sity_code as "Code"), ta.member_reg_sity),
                                                  XMLElement("Street", XMLATTRIBUTES(ta.member_reg_street_code as "Code"), ta.member_reg_street),
                                                  XMLElement("HomeNumber", XMLATTRIBUTES(ta.member_reg_house_code as "Code"), ta.member_reg_house),
                                                  XMLElement("OfficeNumber", XMLATTRIBUTES(ta.member_reg_office_code as "Code"), ta.member_reg_office),
                                                  XMLElement("PostalCode", ta.member_reg_postcode)),

                                       XMLElement("ACAddress",
                                                  XMLElement("Country", ta.member_seat_counrycode),
                                                  XMLElement("Area", XMLATTRIBUTES(ta.member_seat_area_code as "Code"), ta.member_seat_area),
                                                  XMLElement("District", XMLATTRIBUTES(ta.member_seat_region_code as "Code"), ta.member_seat_region),
                                                  XMLElement("Town", XMLATTRIBUTES(ta.member_seat_sity_code as "Code"), ta.member_seat_sity),
                                                  XMLElement("Street", XMLATTRIBUTES(ta.member_seat_street_code as "Code"), ta.member_seat_street),
                                                  XMLElement("HomeNumber", XMLATTRIBUTES(ta.member_seat_house_code as "Code"), ta.member_seat_house),
                                                  XMLElement("OfficeNumber", XMLATTRIBUTES(ta.member_seat_office_code as "Code"), ta.member_seat_office),
                                                  XMLElement("PostalCode", ta.member_seat_postcode)),

                                    XMLElement("FIO",
                                               XMLATTRIBUTES(pkg_common.GetBool(ta.member_isnotnamed) as "IsFioNotSetup"),
                                               XMLElement("FirstName", ta.member_ac_firstname),
                                               XMLElement("SecondName", ta.member_ac_secondname),
                                               XMLElement("MiddleName", ta.member_ac_middlename)),
                                    XMLElement("PlaceBirdth", ta.member_ac_birth_place),
                                    XMLElement("DateBirdth", to_char(ta.member_ac_birth_date, 'dd.mm.yyyy')),
                                    XMLElement("DocumentIdentity", ta.member_ac_doc_typecode),
                                    XMLElement("SeriesDocIdentity", ta.member_ac_doc_series),
                                    XMLElement("NumberDocIdentity", ta.member_ac_doc_number),
                                    XMLElement("DocumentIssued", ta.member_ac_doc_whom),
                                    XMLElement("DateIssuance", to_char(ta.member_ac_doc_date, 'dd.mm.yyyy'))))
             WHEN 3 THEN
              XMLElement("AdditionalPersonInfo",
                         XMLElement("PersonType", 3),
                         XMLElement("AdditionalInformationIp",

                                       XMLElement("URAddress",
                                                  XMLElement("Country", member_reg_counrycode),
                                                  XMLElement("Area", XMLATTRIBUTES(ta.member_reg_area_code as "Code"), ta.member_reg_area),
                                                  XMLElement("District", XMLATTRIBUTES(ta.member_reg_region_code as "Code"), ta.member_reg_region),
                                                  XMLElement("Town", XMLATTRIBUTES(ta.member_reg_sity_code as "Code"), ta.member_reg_sity),
                                                  XMLElement("Street", XMLATTRIBUTES(ta.member_reg_street_code as "Code"), ta.member_reg_street),
                                                  XMLElement("HomeNumber", XMLATTRIBUTES(ta.member_reg_house_code as "Code"), ta.member_reg_house),
                                                  XMLElement("OfficeNumber", XMLATTRIBUTES(ta.member_reg_office_code as "Code"), ta.member_reg_office),
                                                  XMLElement("PostalCode", ta.member_reg_postcode)),

                                       XMLElement("ACAddress",
                                                  XMLElement("Country", ta.member_seat_counrycode),
                                                  XMLElement("Area", XMLATTRIBUTES(ta.member_seat_area_code as "Code"), ta.member_seat_area),
                                                  XMLElement("District", XMLATTRIBUTES(ta.member_seat_region_code as "Code"), ta.member_seat_region),
                                                  XMLElement("Town", XMLATTRIBUTES(ta.member_seat_sity_code as "Code"), ta.member_seat_sity),
                                                  XMLElement("Street", XMLATTRIBUTES(ta.member_seat_street_code as "Code"), ta.member_seat_street),
                                                  XMLElement("HomeNumber", XMLATTRIBUTES(ta.member_seat_house_code as "Code"), ta.member_seat_house),
                                                  XMLElement("OfficeNumber", XMLATTRIBUTES(ta.member_seat_office_code as "Code"), ta.member_seat_office),
                                                  XMLElement("PostalCode", ta.member_seat_postcode)),

                                    XMLElement("FIO",
                                               XMLATTRIBUTES(pkg_common.GetBool(ta.member_isnotnamed) as "IsFioNotSetup"),
                                               XMLElement("FirstName", ta.member_ac_firstname),
                                               XMLElement("SecondName", ta.member_ac_secondname),
                                               XMLElement("MiddleName", ta.member_ac_middlename)),
                                    XMLElement("ParticipantOPF", ta.member_ur_opf_code),
                                    XMLElement("PlaceBirdth", ta.member_ac_birth_place),
                                    XMLElement("DateBirdth", to_char(ta.member_ac_birth_date, 'dd.mm.yyyy')),
                                    XMLElement("DocumentIdentity", ta.member_ac_doc_typecode),
                                    XMLElement("SeriesDocIdentity", ta.member_ac_doc_series),
                                    XMLElement("NumberDocIdentity", ta.member_ac_doc_number),
                                    XMLElement("DocumentIssued", ta.member_ac_doc_whom),
                                    XMLElement("DateIssuance", to_char(ta.member_ac_doc_date, 'dd.mm.yyyy'))))
           END AS xmltype
    INTO v_result
    FROM mess_cfm_announce_memb ta
    WHERE ta.MESS_CFM_ID = p_MESS_CFM_ID
    and ta.MEMBER_ID = p_MEMBER_ID;

    return v_result;
  end;
  --
END PKG_MESS_CFM_2_1;
/

CREATE OR REPLACE PACKAGE KFM."PKG_REPORTS" as
  function GetOperationsInfoForPeriod(pBeginDate     in date,
                                      pEndDate       in date,
                                      pOperationsCur out sys_refcursor)
    return number;
  function GetNoFirstList(pMessagesCur out sys_refcursor) return number;
  /* Получить отчет по отправленным сообщениям, по которым не пришло ответа за предыдущие сутки
    pMessagesCur - курсор структуры
     -- Name                 Type            Nullable           Comments
     -- MESSID               NUMBER                             ID сообщения
     -- RECEIVE_DATE         DATE                               Дата отправки/получения
     -- MESSNUMBER           NUMBER          Y                  Номер сообщения
     -- MESSDATE             DATE            Y                  Дата сообщения
     -- OPERATIONNUMBER      NUMBER          Y                  Внутренний номер операции СФМ
     -- OPERATIONSTATUS      NUMBER          Y                  состояние операции
     -- REASON               NUMBER          Y                  Основание для подачи сообщения
     -- IDTYPEOPERATION      NUMBER          Y                  Код типа операции
     -- IDVIEWOPERATION      NUMBER          Y                  Код вида операции
     -- REGISTRYTYPE         varchar2(100 char)   Y                  Тип реестра
     -- MEMBERSCOUNT         NUMBER          Y                  Количество участников операции
     -- CURRENCYCODE         NUMBER          Y                  Код валюты операци
     -- AMOUNTCURRENCY       varchar2(100 char)   Y                  Сумма операции в валюте ее проведения
     -- AMOUNTCURRENCYTENGE  varchar2(100 char)   Y                  Сумма операции в  тенге
     -- DOCOPERATIONNAME     varchar2(100 char)   Y                  Наименование документа, на основании которого произведена операция
     -- DOCOPERATIONNUMBER   varchar2(100 char)   Y                  Номер документа, на основании которого произведена операция
     -- DOCOPERATIONDATE     DATE            Y                  Дата документа, на основании которого произведена операция
     -- FISRTCODE            NUMBER          Y                  1-ый код признака подозрительности  операции
     -- SECONDCODE           NUMBER          Y                  2-ой код подозрительности признака операции
     -- THIRDCODE            NUMBER          Y                  3-ий код подозрительности признака операции
     -- TRUBLEDESCRIPTION    varchar2(3000 char)  Y                  Описание возникших затруднений квалификации операции как подозрительной
     -- DOPINFO              varchar2(3000 char)  Y                  Дополнительная информация по операции
  */

  function GetFirstList(pMessagesCur out sys_refcursor) return number;
  /*
     Отчет по отправленным  сообщениям за предыдыщие сутки, не прошедшим структурно-логический контроль
       pMessagesCur - курсор структуры
     -- Name                 Type            Nullable           Comments
     -- MESSID               NUMBER                             ID сообщения
     -- RECEIVE_DATE         DATE                               Дата отправки/получения
     -- MESSNUMBER           NUMBER          Y                  Номер сообщения
     -- MESSDATE             DATE            Y                  Дата сообщения
     -- OPERATIONNUMBER      NUMBER          Y                  Внутренний номер операции СФМ
     -- OPERATIONSTATUS      NUMBER          Y                  состояние операции 1010
     -- REASON               NUMBER          Y                  Основание для подачи сообщения 1011
     -- IDTYPEOPERATION      NUMBER          Y                  Код типа операции 1017
     -- IDVIEWOPERATION      NUMBER          Y                  Код вида операции 1004
     -- REGISTRYTYPE         varchar2(100 char)   Y                  Тип реестра 1016
     -- MEMBERSCOUNT         NUMBER          Y                  Количество участников операции
     -- CURRENCYCODE         NUMBER          Y                  Код валюты операци 1018
     -- AMOUNTCURRENCY       varchar2(100 char)   Y                  Сумма операции в валюте ее проведения
     -- AMOUNTCURRENCYTENGE  varchar2(100 char)   Y                  Сумма операции в  тенге
     -- DOCOPERATIONNAME     varchar2(100 char)   Y                  Наименование документа, на основании которого произведена операция 1015
     -- DOCOPERATIONNUMBER   varchar2(100 char)   Y                  Номер документа, на основании которого произведена операция
     -- DOCOPERATIONDATE     DATE            Y                  Дата документа, на основании которого произведена операция
     -- FISRTCODE            NUMBER          Y                  1-ый код признака подозрительности  операции 1008
     -- SECONDCODE           NUMBER          Y                  2-ой код подозрительности признака операции 1008
     -- THIRDCODE            NUMBER          Y                  3-ий код подозрительности признака операции 1008
     -- TRUBLEDESCRIPTION    varchar2(3000 char)  Y                  Описание возникших затруднений квалификации операции как подозрительной
     -- DOPINFO              varchar2(3000 char)  Y                  Дополнительная информация по операции
  */

  function GetSecondList(pMessagesCur out sys_refcursor) return number;
  /*
     Отчет по ранее отвергнутым и не исправленным в установленный срок (1 день) сообщениям за предыдыщие сутки
    pMessagesCur - курсор структуры
     -- Name                 Type            Nullable           Comments
     -- MESSID               NUMBER                             ID сообщения
     -- RECEIVE_DATE         DATE                               Дата отправки/получения
     -- MESSNUMBER           NUMBER          Y                  Номер сообщения
     -- MESSDATE             DATE            Y                  Дата сообщения
     -- OPERATIONNUMBER      NUMBER          Y                  Внутренний номер операции СФМ
     -- OPERATIONSTATUS      NUMBER          Y                  состояние операции
     -- REASON               NUMBER          Y                  Основание для подачи сообщения
     -- IDTYPEOPERATION      NUMBER          Y                  Код типа операции
     -- IDVIEWOPERATION      NUMBER          Y                  Код вида операции
     -- REGISTRYTYPE         varchar2(100 char)   Y                  Тип реестра
     -- MEMBERSCOUNT         NUMBER          Y                  Количество участников операции
     -- CURRENCYCODE         NUMBER          Y                  Код валюты операци
     -- AMOUNTCURRENCY       varchar2(100 char)   Y                  Сумма операции в валюте ее проведения
     -- AMOUNTCURRENCYTENGE  varchar2(100 char)   Y                  Сумма операции в  тенге
     -- DOCOPERATIONNAME     varchar2(100 char)   Y                  Наименование документа, на основании которого произведена операция
     -- DOCOPERATIONNUMBER   varchar2(100 char)   Y                  Номер документа, на основании которого произведена операция
     -- DOCOPERATIONDATE     DATE            Y                  Дата документа, на основании которого произведена операция
     -- FISRTCODE            NUMBER          Y                  1-ый код признака подозрительности  операции
     -- SECONDCODE           NUMBER          Y                  2-ой код подозрительности признака операции
     -- THIRDCODE            NUMBER          Y                  3-ий код подозрительности признака операции
     -- TRUBLEDESCRIPTION    varchar2(3000 char)  Y                  Описание возникших затруднений квалификации операции как подозрительной
     -- DOPINFO              varchar2(3000 char)  Y                  Дополнительная информация по операции
  */

  function GetThirdList(pMessagesCur out sys_refcursor) return number;
  /*
     Отчет по отправленным  сообщениям за текущие сутки
       pMessagesCur - курсор структуры
     -- Name                 Type            Nullable           Comments
     -- MESSID               NUMBER                             ID сообщения
     -- RECEIVE_DATE         DATE                               Дата отправки/получения
     -- MESSNUMBER           NUMBER          Y                  Номер сообщения
     -- MESSDATE             DATE            Y                  Дата сообщения
     -- OPERATIONNUMBER      NUMBER          Y                  Внутренний номер операции СФМ
     -- OPERATIONSTATUS      NUMBER          Y                  состояние операции 1010
     -- REASON               NUMBER          Y                  Основание для подачи сообщения 1011
     -- IDTYPEOPERATION      NUMBER          Y                  Код типа операции 1017
     -- IDVIEWOPERATION      NUMBER          Y                  Код вида операции 1004
     -- REGISTRYTYPE         varchar2(100 char)   Y                  Тип реестра 1016
     -- MEMBERSCOUNT         NUMBER          Y                  Количество участников операции
     -- CURRENCYCODE         NUMBER          Y                  Код валюты операци 1018
     -- AMOUNTCURRENCY       varchar2(100 char)   Y                  Сумма операции в валюте ее проведения
     -- AMOUNTCURRENCYTENGE  varchar2(100 char)   Y                  Сумма операции в  тенге
     -- DOCOPERATIONNAME     varchar2(100 char)   Y                  Наименование документа, на основании которого произведена операция 1015
     -- DOCOPERATIONNUMBER   varchar2(100 char)   Y                  Номер документа, на основании которого произведена операция
     -- DOCOPERATIONDATE     DATE            Y                  Дата документа, на основании которого произведена операция
     -- FISRTCODE            NUMBER          Y                  1-ый код признака подозрительности  операции 1008
     -- SECONDCODE           NUMBER          Y                  2-ой код подозрительности признака операции 1008
     -- THIRDCODE            NUMBER          Y                  3-ий код подозрительности признака операции 1008
     -- TRUBLEDESCRIPTION    varchar2(3000 char)  Y                  Описание возникших затруднений квалификации операции как подозрительной
     -- DOPINFO              varchar2(3000 char)  Y                  Дополнительная информация по операции
  */

  function GetPitaOrgListHTML2(pReportName  in varchar2,
                               pMessagesCur out clob) return number;
  /* Отчет по участникам операций, успешно идентифицированным в списке организаций,
  осуществляющих террористическую деятельность */

  function GetPitaPersListHTML(pReportName  in varchar2,
                               pMessagesCur out clob) return number;
  /* Отчет по участникам операций, успешно идентифицированным в списке лиц,
  осуществляющих террористическую деятельность */

  function GetFirstOrSecondListHTML2(pReportName   in varchar2,
                                     pMessagesCur  in sys_refcursor,
                                     pMessagesHTML out clob) return number;
  /* отчет */

  function GetReportNames(ReportNamesCur out sys_refcursor) return number;
  /* Наименования всех отчетов для СФМ*
  ReportNamesCur - курсор структуры

  -- REPORTNUMBER  NUMBER       - Номер отчета
    -- REPORTNAME    varchar2(1000 char)  -Наименование отчета */

  function GetReportName(pReportNumber in number, pReportName out varchar2)
    return number;
  /*   Наименование отдельного отчета для СФМ*
  Входной параметр:\
     pReportNumber NUMBER - номер отчета
  Выходной параметр:
     pReportName  varchar2(1000 char) - имя отчета
  */

  function MakeReport(pReportNumber in number, pReportBody out clob)
    return number;
  /* Получить отчет
   Входной параметр:\
     pReportNumber NUMBER - номер отчета
     1 - Отчет по отправленным  сообщениям за предыдыщие сутки,
         не прошедшим структурно-логический контроль
     2 - Отчет по отправленным сообщениям,
         по которым не пришло ответа за предыдущие сутки
     3 - Отчет по ранее отвергнутым и не исправленным в установленный срок
         (1 день) сообщениям за предыдыщие сутки
     4 - Отчет по участникам операций,
         успешно идентифицированным в списке организаций,
         осуществляющих террористическую деятельность
     5 - Отчет по участникам операций,
         успешно идентифицированным в списке лиц,
         осуществляющих террористическую деятельность
     6 - Отчет по отправленным  сообщениям за текущие сутки
  Выходной параметр:
     pReportBody  clob - отчет в форме html
  Результат:
     0 --успех
     -2203; --Формирование данного отчета не предусмотрено
     -2202; --Ошибка при формировании отчета
  */

end PKG_Reports;
/

CREATE OR REPLACE PACKAGE BODY KFM."PKG_REPORTS" as

  --GetOperationsInfoForPeriod
  function GetOperationsInfoForPeriod(pBeginDate     in date,
                                      pEndDate       in date,
                                      pOperationsCur out sys_refcursor)
    return number is
    result number default 0;
  begin
    open pOperationsCur for
      select mcai.MESS_OPER_STATUS,
             mcao.MESS_CFM_ID,
             mcao.OPER_NUMBER,
             mcao.OPER_IDTYPE,
             mcao.OPER_IDVIEW,
             mcao.OPER_MEMBERS_COUNT,
             mcao.OPER_CURRENCY_CODE,
             mcao.OPER_CURRENCY_AMOUNT,
             mcao.OPER_TENGE_AMOUNT,
             mcao.OPER_REASON,
             mcao.OPER_DOC_NUMBER,
             mcao.OPER_DOC_DATE,
             mcao.OPER_SUSP_FIRST,
             mcao.OPER_SUSP_SECOND,
             mcao.OPER_SUSP_THIRD,
             mcao.OPER_DIFFICULTIES,
             mcao.OPER_DOPINFO
        from mess_cfm_announce_oper mcao
        left join mess_cfm_announce_info mcai
          on mcao.mess_cfm_id = mcai.mess_cfm_id
       where mcao.MESS_CFM_ID in
             (select mc.MESS_CFM_ID
                from mess_cfm mc
               where mc.receive_date between pBeginDate and pEndDate);
    return result;
  exception
    when others then
      return - 1;
  end GetOperationsInfoForPeriod;

  --Отчет по отправленным сообщениям, по которым не пришло ответа за предыдущие сутки
  function GetNoFirstList(pMessagesCur out sys_refcursor) return number is
    result number default 0;
  begin
    open pMessagesCur for
      select mc.mess_cfm_id,
             mc.receive_date,
             mc.send_date,
             mcai.mess_number,
             mcai.mess_type,
             mcai.mess_oper_status,
             mcai.mess_suspic_code,
             mcai.mess_reason_code,
             mcao.OPER_NUMBER,
             mcao.OPER_IDTYPE,
             mcao.OPER_IDVIEW,
             mcao.OPER_MEMBERS_COUNT,
             mcao.OPER_CURRENCY_CODE,
             mcao.OPER_CURRENCY_AMOUNT,
             mcao.OPER_TENGE_AMOUNT,
             mcao.OPER_REASON,
             mcao.OPER_DOC_NUMBER,
             mcao.OPER_DOC_DATE,
             mcao.OPER_SUSP_FIRST,
             mcao.OPER_SUSP_SECOND,
             mcao.OPER_SUSP_THIRD,
             mcao.OPER_DIFFICULTIES,
             mcao.OPER_DOPINFO,
             mv.versionid
        from mess_cfm mc
        left join mess_cfm_announce_oper mcao
          on mc.mess_cfm_id = mcao.mess_cfm_id
        left join mess_cfm_announce_info mcai
          on mcai.mess_cfm_id = mcao.mess_cfm_id
        left join messages_versions mv
          on mv.versioncode = mc.mess_version
       where mc.mess_type = 1
         and (mc.stage = 30 or mc.stage = 40)
         and mc.send_date between trunc(sysdate) - 1 and trunc(sysdate)
         and
            -- не имеется никакой квитанции
             not exists
       (select mcChecks.mess_cfm_id
                from mess_cfm mcChecks
               where mcChecks.Mess_Parentid = mc.Mess_Parentid
                 and (mcChecks.Mess_Type = 3 or mcChecks.Mess_Type = 2));
    return result;
  exception
    when others then
      return - 1;
  end GetNoFirstList;

  --Отчет по отправленным  сообщениям за предыдущие сутки, не прошедшим структурно-логический контроль
  function GetFirstList(pMessagesCur out sys_refcursor) return number is
    result number default 0;
  begin
    open pMessagesCur for
      select mc.mess_cfm_id,
             mc.receive_date,
             mc.send_date,
             mcai.mess_number,
             mcai.mess_type,
             mcai.mess_oper_status,
             mcai.mess_suspic_code,
             mcai.mess_reason_code,
             mcao.OPER_NUMBER,
             mcao.OPER_IDTYPE,
             mcao.OPER_IDVIEW,
             mcao.OPER_MEMBERS_COUNT,
             mcao.OPER_CURRENCY_CODE,
             mcao.OPER_CURRENCY_AMOUNT,
             mcao.OPER_TENGE_AMOUNT,
             mcao.OPER_REASON,
             mcao.OPER_DOC_NUMBER,
             mcao.OPER_DOC_DATE,
             mcao.OPER_SUSP_FIRST,
             mcao.OPER_SUSP_SECOND,
             mcao.OPER_SUSP_THIRD,
             mcao.OPER_DIFFICULTIES,
             mcao.OPER_DOPINFO,
             mv.versionid
        from mess_cfm mc
        left join mess_cfm_announce_oper mcao
          on mc.mess_cfm_id = mcao.mess_cfm_id
        left join mess_cfm_announce_info mcai
          on mcai.mess_cfm_id = mcao.mess_cfm_id
        left join messages_versions mv
          on mv.versioncode = mc.mess_version
       where mc.mess_type = 1
         and (mc.stage = 30 or mc.stage = 40)
         and mc.send_date between trunc(sysdate) - 1 and trunc(sysdate)
         and
            -- имеется квитанция об отказе
             exists (select mcChecks.mess_cfm_id
                from mess_cfm mcChecks
               where mcChecks.Mess_Parentid = mc.mess_cfm_id
                 and mcChecks.Mess_Type = 3);

    return result;
  end GetFirstList;

  --Отчет по ранее отвергнутым и неисправленным в установленный срок (1 день) сообщениям за предыдущие сутки
  function GetSecondList(pMessagesCur out sys_refcursor) return number is
    result number default 0;
  begin
    open pMessagesCur for
      select mc.mess_cfm_id,
             mc.receive_date,
             mc.send_date,
             mcai.mess_number,
             mcai.mess_type,
             mcai.mess_oper_status,
             mcai.mess_suspic_code,
             mcai.mess_reason_code,
             mcao.OPER_NUMBER,
             mcao.OPER_IDTYPE,
             mcao.OPER_IDVIEW,
             mcao.OPER_MEMBERS_COUNT,
             mcao.OPER_CURRENCY_CODE,
             mcao.OPER_CURRENCY_AMOUNT,
             mcao.OPER_TENGE_AMOUNT,
             mcao.OPER_REASON,
             mcao.OPER_DOC_NUMBER,
             mcao.OPER_DOC_DATE,
             mcao.OPER_SUSP_FIRST,
             mcao.OPER_SUSP_SECOND,
             mcao.OPER_SUSP_THIRD,
             mcao.OPER_DIFFICULTIES,
             mcao.OPER_DOPINFO,
             mv.versionid
        from mess_cfm mc
        left join mess_cfm_announce_oper mcao
          on mc.mess_cfm_id = mcao.mess_cfm_id
        left join mess_cfm_announce_info mcai
          on mcai.mess_cfm_id = mcao.mess_cfm_id
        left join messages_versions mv
          on mv.versioncode = mc.mess_version
       where mc.mess_type = 1
         and (mc.stage = 30 or mc.stage = 40)
         and mc.send_date between trunc(sysdate) - 1 and trunc(sysdate)
         and
            -- имеется квитанция об отказе
             exists
       (select mcChecks.mess_cfm_id
                from mess_cfm mcChecks
               where mcChecks.Mess_Parentid = mc.mess_cfm_id
                 and mcChecks.mess_type = 3
                 and not exists
               (select mcRetry.mess_cfm_id
                        from mess_cfm mcRetry
                       inner join mess_cfm_announce_info mcaiRetry
                          on mcaiRetry.mess_cfm_id = mcRetry.Mess_Cfm_Id
                       where mcRetry.Mess_Parentid = mc.mess_cfm_id
                         and mcRetry.mess_type = 1
                         and mcaiRetry.mess_type = 2
                         and --исправление
                             mcRetry.Receive_Date < mcChecks.receive_date + 1));
    --               exists (select mcChecks2.mess_cfm_id
    --                        from mess_cfm mcChecks2
    --                        where mcChecks2.Parentmessid=mc.mess_cfm_id and
    --                        mcChecks2.messtype=2))

    return result;
  end GetSecondList;

  -- Отправлено за текущие сутки
  function GetThirdList(pMessagesCur out sys_refcursor) return number is
    result number default 0;
  begin
    open pMessagesCur for
      select mc.mess_cfm_id,
             mc.receive_date,
             mc.send_date,
             mcai.mess_number,
             mcai.mess_type,
             mcai.mess_oper_status,
             mcai.mess_suspic_code,
             mcai.mess_reason_code,
             mcao.OPER_NUMBER,
             mcao.OPER_IDTYPE,
             mcao.OPER_IDVIEW,
             mcao.OPER_MEMBERS_COUNT,
             mcao.OPER_CURRENCY_CODE,
             mcao.OPER_CURRENCY_AMOUNT,
             mcao.OPER_TENGE_AMOUNT,
             mcao.OPER_REASON,
             mcao.OPER_DOC_NUMBER,
             mcao.OPER_DOC_DATE,
             mcao.OPER_SUSP_FIRST,
             mcao.OPER_SUSP_SECOND,
             mcao.OPER_SUSP_THIRD,
             mcao.OPER_DIFFICULTIES,
             mcao.OPER_DOPINFO,
             mv.versionid
        from mess_cfm mc
        left join mess_cfm_announce_oper mcao
          on mc.mess_cfm_id = mcao.mess_cfm_id
        left join mess_cfm_announce_info mcai
          on mcai.mess_cfm_id = mcao.mess_cfm_id
        left join messages_versions mv
          on mv.versioncode = mc.mess_version
       where mc.mess_type = 1
         and (mc.stage = 30 or mc.stage = 40)
         and mc.receive_date between trunc(sysdate) and sysdate;
    return result;
  end GetThirdList;

  --GetFirstOrSecondListHTML2
  function GetFirstOrSecondListHTML2(pReportName   in varchar2,
                                     pMessagesCur  in sys_refcursor,
                                     pMessagesHTML out clob) return number is
    TAG_STYLED_TR    constant varchar2(31) := '<tr style="background:#cccccc">';
    TAG_END_TR       constant varchar2(5 char) := '</tr>';
    TAG_END_TD       constant varchar2(5 char) := '</td>';
    TAG_TD           constant varchar2(4) := '<td>';
    TAG_END_B_END_TD constant varchar2(9) := '</b></td>';
    TAG_TD_B         constant varchar2(7) := '<td><b>';
    TAG_TR           constant varchar2(4) := '<tr>';
    TAG_TABLE_END    constant varchar2(8) := '</table>';
    TAG_TABLE_BEGIN  constant varchar2(110) := '<table cellpadding="4" border="1" bordercolor=#000000 style="border-collapse:collapse" width="100%">';
    result number default 0;

    vMESSID       mess_cfm.mess_cfm_id%TYPE;
    vRECEIVE_DATE mess_cfm.receive_date%TYPE;
    vSEND_DATE    mess_cfm.send_date%TYPE;

    vMESSNUMBER      mess_cfm_announce_info.mess_number%TYPE;
    vMESSDOCTYPE     mess_cfm_announce_info.mess_type%TYPE;
    vOPERATIONSTATUS mess_cfm_announce_info.mess_oper_status%TYPE;
    vREASONCRITERY   mess_cfm_announce_info.mess_suspic_code%TYPE;
    vREASON          mess_cfm_announce_info.mess_reason_code%TYPE;

    vOPERATIONNUMBER     mess_cfm_announce_oper.oper_number%TYPE;
    vIDTYPEOPERATION     mess_cfm_announce_oper.oper_idtype%TYPE;
    vIDVIEWOPERATION     mess_cfm_announce_oper.oper_idview%TYPE;
    vMEMBERSCOUNT        mess_cfm_announce_oper.oper_members_count%TYPE;
    vCURRENCYCODE        mess_cfm_announce_oper.oper_currency_code%TYPE;
    vAMOUNTCURRENCY      mess_cfm_announce_oper.oper_currency_amount%TYPE;
    vAMOUNTCURRENCYTENGE mess_cfm_announce_oper.oper_tenge_amount%TYPE;

    vDOCOPERATIONNAME   mess_cfm_announce_oper.oper_reason%TYPE;
    vDOCOPERATIONNUMBER mess_cfm_announce_oper.oper_doc_number%TYPE;
    vDOCOPERATIONDATE   mess_cfm_announce_oper.oper_doc_date%TYPE;
    vFISRTCODE          mess_cfm_announce_oper.oper_susp_first%TYPE;
    vSECONDCODE         mess_cfm_announce_oper.oper_susp_second%TYPE;
    vTHIRDCODE          mess_cfm_announce_oper.oper_susp_third%TYPE;
    vTRUBLEDESCRIPTION  mess_cfm_announce_oper.oper_difficulties%TYPE;
    vDOPINFO            mess_cfm_announce_oper.oper_dopinfo%TYPE;
    vVersion            number;

    i                number default 1;
    vStrHeader       VARCHAR2(10000) := '<div align="center"><h3>' ||
                                        pReportName ||
                                        '</h3></div></br></br>';
    vHtmlHeader      varchar2(1000 char) := '<html xmlns="http://www.w3.org/1999/xhtml">' ||
                                       '<head><style type="text/css"> body { background-color: #f0ffff; font-family:Verdana; font-size:10px;  }' ||
                                       '#main_container table tr { border-width: 1px; border-style: solid; font-size:10px; }' ||
                                       '</style> </head> <body> <div id="main_container">';
    vHtmlEnd         varchar2(100 char) := '</div> </body> </html>';
    vTableBeginFirst varchar2(100 char) := '<h3>Документ ';
    vEmptyReport     varchar2(100 char) := '<font>Данные успешно обработаны, соответствующих записей не найдено</font></br></br>';
    tmpClob          clob;
  begin
    pMessagesHTML := vHtmlHeader;
    dbms_lob.append(pMessagesHTML, vStrHeader);
    if pMessagesCur is not null then
      begin
        loop
          fetch pMessagesCur
            into vMESSID,
                 vRECEIVE_DATE,
                 vSEND_DATE,
                 vMESSNUMBER,
                 vMESSDOCTYPE,
                 vOPERATIONSTATUS,
                 vREASONCRITERY,
                 vREASON,
                 vOPERATIONNUMBER,
                 vIDTYPEOPERATION,
                 vIDVIEWOPERATION,
                 vMEMBERSCOUNT,
                 vCURRENCYCODE,
                 vAMOUNTCURRENCY,
                 vAMOUNTCURRENCYTENGE,
                 vDOCOPERATIONNAME,
                 vDOCOPERATIONNUMBER,
                 vDOCOPERATIONDATE,
                 vFISRTCODE,
                 vSECONDCODE,
                 vTHIRDCODE,
                 vTRUBLEDESCRIPTION,
                 vDOPINFO,
                 vVersion;
          exit when pMessagesCur%NOTFOUND;

          tmpClob := vTableBeginFirst || to_char(i) || '</h3>' ||

                     TAG_TABLE_BEGIN || TAG_STYLED_TR ||
                     '<td colspan="4"><b>' || 'Информация о сообщении' ||
                     TAG_END_B_END_TD || TAG_END_TR || TAG_TR || TAG_TD_B ||
                     'Номер сообщения:' || TAG_END_B_END_TD || TAG_TD ||
                     nvl(to_char(vMESSNUMBER), '-') || TAG_END_TD ||
                     TAG_TD_B || 'Дата отправки/получения:' ||
                     TAG_END_B_END_TD || TAG_TD ||
                     nvl(to_char(vRECEIVE_DATE, 'DD.MM.YYYY'), '-') ||
                     TAG_END_TD || TAG_END_TR || TAG_TR || TAG_TD_B ||
                     'Основание для подачи сообщения:' || TAG_END_B_END_TD ||
                     TAG_TD || nvl(pkg_analytic.GetCodeDescription(vREASON,
                                                                   1011,
                                                                   vversion),
                                   '-') || TAG_END_TD || TAG_TD_B ||

                     'Критерий подозрительности операции:' ||
                     TAG_END_B_END_TD || TAG_TD ||
                     nvl(pkg_analytic.GetCodeDescription(vREASONCRITERY,
                                                         1012,
                                                         vversion),
                         '-') || TAG_END_TD || TAG_END_TR || TAG_TABLE_END ||
                     TAG_TABLE_BEGIN || TAG_STYLED_TR ||
                     '<td colspan="10"><b>' || 'Информация об операции' ||
                     TAG_END_B_END_TD || TAG_END_TR || TAG_TR ||
                     '<td colspan="2" rowspan="2"><b>' ||
                     'Внутренний номер операции СФМ:' || TAG_END_B_END_TD ||
                     '<td rowspan="2">' || nvl(vOPERATIONNUMBER, '-') ||
                     TAG_END_TD || '<td rowspan="2"><b>' ||
                     'Количество участников:' || TAG_END_B_END_TD ||
                     '<td rowspan="2">' || nvl(to_char(vMEMBERSCOUNT), '-') ||
                     TAG_END_TD || '<td rowspan="2"><b>' || 'Сумма:' ||
                     TAG_END_B_END_TD || TAG_TD || vAMOUNTCURRENCY ||
                     TAG_END_TD || TAG_TD ||
                     pkg_analytic.GetCodeDescription(vCURRENCYCODE,
                                                     1018,
                                                     vversion) ||
                     TAG_END_TD || '<td rowspan="2"><b>' || 'Состояние:' ||
                     TAG_END_B_END_TD || '<td rowspan="2">' ||
                     nvl(pkg_analytic.GetCodeDescription(vOPERATIONSTATUS,
                                                         1010,
                                                         vversion),
                         '-') || TAG_END_TD || TAG_END_TR || TAG_TR ||
                     TAG_TD || vAMOUNTCURRENCYTENGE || TAG_END_TD || TAG_TD ||
                     'KZT - Тенге' || TAG_END_TD || TAG_END_TR || TAG_TR ||
                     '<td><b>' || 'Код типа:' || TAG_END_B_END_TD ||
                     '<td colspan="9">' || nvl(pkg_analytic.GetCodeDescription(vIDTYPEOPERATION,
                                                                               1017,
                                                                               vversion),
                                               '-') || TAG_END_TD ||
                     TAG_END_TR || TAG_TR || TAG_TD_B || 'Код вида:' ||
                     TAG_END_B_END_TD || '<td colspan="9">' ||
                     nvl(pkg_analytic.GetCodeDescription(vIDVIEWOPERATION,
                                                         1004,
                                                         vversion),
                         '-') || TAG_END_TD || TAG_END_TR || TAG_TABLE_END ||
                     TAG_TABLE_BEGIN || TAG_STYLED_TR ||
                     '<td colspan="6"><b>' ||
                     'Документ, на основании которого произведена операция' ||
                     TAG_END_B_END_TD || TAG_END_TR || TAG_TR || '<td><b>' ||
                     'Основание совершения операции:' || '</b></td>' ||
                     '<td>' || nvl(vDOCOPERATIONNAME, '-') || '</td>' ||
                     '<td><b>' || 'Номер:' || '</b></td>' || '<td>' ||
                     vDOCOPERATIONNUMBER || '</td>' || '<td><b>' ||
                     'Дата выдачи:' || '</b></td>' || '<td>' ||
                     nvl(to_char(vDOCOPERATIONDATE, 'DD.MM.YYYY'), '-') ||
                     '</td>' || TAG_END_TR || TAG_TABLE_END ||
                     TAG_TABLE_BEGIN || TAG_STYLED_TR ||
                     '<td colspan="6"><b>' ||
                     'Коды признака подозрительности  операции:' ||
                     '</b></td>' || TAG_END_TR || TAG_TR || '<td><b>' ||
                     '1-ый:' || '</b></td>' || '<td>' ||
                     nvl(pkg_analytic.GetShortCodeDescription(vFISRTCODE,
                                                              1008,
                                                              vversion),
                         '-') || '</td>' || '<td>' ||
                     nvl(pkg_analytic.GetCodeDescription(vFISRTCODE,
                                                         1008,
                                                         vversion),
                         '-') || '</td>' || TAG_END_TR || TAG_TR ||
                     '<td><b>' || '2-ой:' || '</b></td>' || '<td>' ||
                     nvl(pkg_analytic.GetShortDescription(vSECONDCODE, 1008),
                         '-') || '</td>' || '<td>' ||
                     nvl(pkg_analytic.GetCodeDescription(vSECONDCODE,
                                                         1008,
                                                         vversion),
                         '-') || '</td>' || TAG_END_TR || TAG_TR ||
                     '<td><b>' || '3-ий:' || '</b></td>' || '<td>' ||
                     nvl(pkg_analytic.GetShortCodeDescription(vTHIRDCODE,
                                                              1008,
                                                              vversion),
                         '-') || '</td>' || '<td>' ||
                     nvl(pkg_analytic.GetCodeDescription(vTHIRDCODE,
                                                         1008,
                                                         vversion),
                         '-') || '</td>' || TAG_END_TR || TAG_TABLE_END ||
                     TAG_TABLE_BEGIN || TAG_STYLED_TR || '<td><b>' ||
                     'Описание возникших затруднений квалификации операции как подозрительной:' ||
                     '</b></td>' || TAG_END_TR || TAG_TR || '<td>' ||
                     nvl(vTRUBLEDESCRIPTION, '-') || '</td>' || TAG_END_TR ||
                     TAG_STYLED_TR || '<td><b>' ||
                     'Дополнительная информация по операции:' ||
                     '</b></td>' || TAG_END_TR || TAG_TR || '<td>' ||
                     nvl(vDOPINFO, '-') || '</td>' || TAG_END_TR ||
                     TAG_TABLE_END ||

                     '<hr />';
          dbms_lob.append(pMessagesHTML, tmpClob);
          i := i + 1;
        end loop;
      end;
    end if;
    if i = 1 then
      dbms_lob.append(pMessagesHTML, vEmptyReport);
    end if;
    dbms_lob.append(pMessagesHTML, vHtmlEnd);
    return result;
  exception
    when others then
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  'PKG_Reports.GetFirstOrSecondListHTML2');
      return - 1;
  end GetFirstOrSecondListHTML2;

  --GetPitaOrgListHTML2
  function GetPitaOrgListHTML2(pReportName  in varchar2,
                               pMessagesCur out clob) return number is
    TAG_TABLE_END   constant varchar2(8) := '</table>';
    TAG_TABLE_BEGIN constant varchar2(110) := '<table cellpadding="4" border="1" bordercolor=#000000 style="border-collapse:collapse" width="100%">';

    result       number default 0;
    vHtmlHeader  varchar2(1000 char) := '<html xmlns="http://www.w3.org/1999/xhtml">' ||
                                   '<head><style type="text/css"> body { background-color: #f0ffff; font-family:Verdana; font-size:10px;  }' ||
                                   '#main_container table tr { border-width: 1px; border-style: solid; font-size:10px; }' ||
                                   '</style> </head> <body> <div id="main_container">';
    vHtmlEnd     varchar2(100 char) := '</div> </body> </html>';
    vStrHeader   VARCHAR2(10000) := '<div align="center"><h3>' ||
                                    pReportName || '</h3></div></br></br>';
    vEmptyReport varchar2(100 char) := '<font>Данные успешно обработаны, соответствующих записей не найдено</font></br></br>';
    vTmpLob      clob;
    i            number default 1;
  begin
    pMessagesCur := vHtmlHeader;
    dbms_lob.append(pMessagesCur, vStrHeader);

    FOR vListInfo IN (SELECT m.mess_number as messnumber,
                             m.mess_date as messdate,
                             m.mess_type as messdoctype,
                             ent.MEMBER_TYPE,
                             decode(ent.MEMBER_RESIDENCE,
                                    1,
                                    'Да',
                                    0,
                                    'Нет',
                                    '-') as isResident,
                             ent.MEMBER_RESIDENCE_COUNTRYCODE,
                             ent.MEMBER_UR_NAME,
                             ent.MEMBER_UR_FISTHEAD_NAME,
                             ent.MEMBER_FOREIGN,
                             ent.MEMBER_FOREIGN_ADD,
                             (select o.oper_number
                                from mess_cfm_announce_oper o
                               where o.mess_cfm_id = ent.mess_cfm_id) as opernumber,
                             ent.MEMBER_ROLE,
                             ent.MEMBER_KIND,
                             ent.MEMBER_TAXCODE,
                             ent.MEMBER_OKPO,
                             ent.MEMBER_OKED,
                             ent.MEMBER_MAINCODE,
                             ent.MEMBER_BANK_NAME,
                             ent.MEMBER_BANK_ACCOUNT,
                             ent.MEMBER_BANK_ADDRESS,
                             ent.MEMBER_BANK_CODE,
                             pkg_analytic.GetCodeDescription(ent.MEMBER_REG_COUNRYCODE,
                                                             1019,
                                                             mv.VersionId) || ', ' ||
                             ent.MEMBER_REG_AREA || ', ' ||
                             ent.MEMBER_REG_REGION || ', ' ||
                             ent.MEMBER_REG_SITY || ', ' ||
                             ent.MEMBER_REG_STREET || ', ' ||
                             ent.MEMBER_REG_HOUSE || ', ' ||
                             ent.MEMBER_REG_OFFICE || ', ' ||
                             ent.MEMBER_REG_POSTCODE as regaddress,
                             pkg_analytic.GetCodeDescription(ent.MEMBER_SEAT_COUNRYCODE,
                                                             1019,
                                                             mv.VersionId) || ', ' ||
                             ent.MEMBER_SEAT_AREA || ', ' ||
                             ent.MEMBER_SEAT_REGION || ', ' ||
                             ent.MEMBER_SEAT_SITY || ', ' ||
                             ent.MEMBER_SEAT_STREET || ', ' ||
                             ent.MEMBER_SEAT_HOUSE || ', ' ||
                             ent.MEMBER_SEAT_OFFICE || ', ' ||
                             ent.MEMBER_SEAT_POSTCODE as seataddress,
                             ent.MEMBER_COMMENTS,
                             ent.MEMBER_PHONE,
                             ent.MEMBER_EMAIL,
                             pkg_pitaholding.ExistsInPitaOrg(ent.mess_cfm_id) as Pitaorg,
                             mv.VersionId
                        FROM mess_cfm_announce_memb ent
                        join mess_cfm_announce_info m
                          on (m.mess_cfm_id = ent.mess_cfm_id)
                        join mess_cfm mc
                          on (mc.mess_cfm_id = ent.mess_cfm_id)
                        join messages_versions mv
                          on (mv.versioncode = mc.mess_version)
                       WHERE ent.member_type = 1) LOOP
      /*     1 - Юридическое лицо
      2 - Физическое лицо
      3 - Индивидуальный предприниматель  */
      if vListInfo.Pitaorg is not null then

        vTmpLob := '<h3>Документ ' || to_char(i) || '</h3>' ||

                   TAG_TABLE_BEGIN ||

                   '<tr><td><b>' || 'Номер сообщения:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.messnumber), '-') ||
                   '</td><td><b>' || 'Дата сообщения:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.messdate, 'DD.MM.YYYY'), '-') ||
                   '</td><td><b>' || 'Вид сообщения:' || '</b></td><td>' ||
                   nvl(pkg_analytic.GetCodeDescription(vListInfo.messdoctype,
                                                       1009,
                                                       vListInfo.Versionid),
                       '-') || '</td></tr>' || TAG_TABLE_END ||

                   TAG_TABLE_BEGIN ||

                   '<tr style="background:#cccccc"><td colspan="5"><b>' ||
                   'Информация об объекте:' || '</b></td></tr>' ||

                   '<tr><td><b>' || 'Наименование:' ||
                   '</b></td><td colspan="4">' ||
                   nvl(vListInfo.MEMBER_UR_NAME, '-') || '</td></tr>' ||

                   '<tr><td><b>' || 'ФИО первого руководителя:' ||
                   '</b></td><td colspan="4">' ||
                   nvl(vListInfo.MEMBER_UR_FISTHEAD_NAME, '-') ||
                   '</td></tr>' ||

                   '<tr><td><b>' || 'Тип:' || '</b></td><td>' ||
                   pkg_analytic.GetCodeDescription(vListInfo.MEMBER_TYPE,
                                                   10,
                                                   vListInfo.Versionid) ||
                   '</td><td><b>' || 'Резидент:' || '</b></td><td>' ||
                   vListInfo.isResident || '</td><td colspan="2">' ||
                   nvl(pkg_analytic.GetCodeDescription(vListInfo.MEMBER_RESIDENCE_COUNTRYCODE,
                                                       1019,
                                                       vListInfo.Versionid),
                       '-') || '</td></tr>' ||

                   '<tr><td><b>' || 'Аффилированность:' ||
                   '</b></td><td colspan="4">' ||

                   pkg_analytic.GetCodeDescription(vListInfo.MEMBER_FOREIGN,
                                                   1014,
                                                   vListInfo.Versionid) || ' ' ||
                   vListInfo.Member_Foreign_Add || '</td></tr>' ||
                   TAG_TABLE_END || TAG_TABLE_BEGIN ||

                   '<tr style="background:#cccccc"><td colspan="4"><b>' ||
                   'Информация об операции' || '</b></td></tr>' ||

                   '<tr><td><b>' || 'Номер операции:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.opernumber), ' - ') ||
                   '</td><td><b>' || 'Роль в операции:' || '</b></td><td>' ||
                   pkg_analytic.GetCodeDescription(vListInfo.Member_Role,
                                                   102,
                                                   vListInfo.Versionid) ||
                   '</td></tr><tr><td><b>' || 'Вид участника:' ||
                   '</b></td><td colspan="3">' ||
                   pkg_analytic.GetCodeDescription(vListInfo.Member_Kind,
                                                   1006,
                                                   vListInfo.Versionid) ||
                   '</td></tr>' ||

                   TAG_TABLE_END || TAG_TABLE_BEGIN ||

                   '<tr style="background:#cccccc"><td colspan="8"><b>' ||
                   'Номера' || '</b></td></tr>' ||

                   '<tr><td><b>' || 'РНН' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Taxcode), '-') ||
                   '</td><td><b>' || 'ОКПО' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Okpo), '-') ||
                   '</td><td><b>' || 'ОКЕД' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Oked), '-') ||
                   '</td><td><b>' || 'ИНН/БИН' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Maincode), '-') ||
                   '</td></tr>' ||

                   TAG_TABLE_END || TAG_TABLE_BEGIN ||

                   '</td></tr><tr style="background:#cccccc"><td colspan="4"><b>' ||
                   'Информация о банке-корреспонденте' || '</b></td></tr>' ||

                   '<tr><td><b>' || 'Наименование:' || '</b></td><td>' ||
                   nvl(vListInfo.Member_Bank_Name, '-') || '</td><td><b>' ||
                   'Код:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Bank_Code), ' - ') ||
                   '</td></tr>' ||

                   '<tr><td><b>' || 'Адрес:' || '</b></td><td>' ||
                   nvl(vListInfo.Member_Bank_Address, ' - ') ||
                   '</td><td><b>' || 'Номер счета:' || '</b></td><td>' ||
                   nvl(vListInfo.Member_Bank_Account, '-') || '</td></tr>' ||

                   TAG_TABLE_END || TAG_TABLE_BEGIN ||

                   '<tr style="background:#cccccc"><td colspan="4"><b>' ||
                   'Контактная информация' || '</b></td></tr>' ||

                   '<tr><td><b>' ||
                   'Место регистрации (постоянного жительства):' ||
                   '</b></td><td>' || nvl(vListInfo.regaddress, '-') ||
                   '</td><td><b>' || 'Телефонный номер:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Phone), '-') ||
                   '</td></tr>' ||

                   '<tr><td><b>' ||
                   'Место пребывания (фактического нахождения):' ||
                   '</b></td><td>' || nvl(vListInfo.regaddress, '-') ||
                   '</td><td><b>' || 'Адрес электронной почты:' ||
                   '</b></td><td>' || nvl(vListInfo.Member_Email, '-') ||
                   '</td></tr>' || TAG_TABLE_END || TAG_TABLE_BEGIN ||
                   '<tr style="background:#cccccc"><td colspan="1"><b>' ||
                   'Комментарий:' || '</b></td></tr>' || '<tr><td>' ||
                   nvl(vListInfo.Member_Comments, '-') || '</td></tr>' ||
                   TAG_TABLE_END || '<hr/>';

        dbms_lob.append(vTmpLob, vListInfo.Pitaorg);
        dbms_lob.append(pMessagesCur, vTmpLob);
        i := i + 1;

      end if;
    END LOOP;
    if i = 1 then
      dbms_lob.append(pMessagesCur, vEmptyReport);
    end if;
    dbms_lob.append(pMessagesCur, vHtmlEnd);

    return result;
  exception
    when others then
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  'PKG_Reports.GetPitaOrgListHTML2');
      return - 1;
  end GetPitaOrgListHTML2;

  --GetPitaPersListHTML
  function GetPitaPersListHTML(pReportName  in varchar2,
                               pMessagesCur out clob) return number is
    TAG_TABLE_END   constant varchar2(8) := '</table>';
    TAG_TABLE_BEGIN constant varchar2(110) := '<table cellpadding="4" border="1" bordercolor=#000000 style="border-collapse:collapse" width="100%">';
    result      number default 0;
    vTmpLob     clob;
    i           number default 1;
    vHtmlHeader varchar2(1000 char) := '<html xmlns="http://www.w3.org/1999/xhtml">' ||
                                  '<head><style type="text/css"> body { background-color: #f0ffff; font-family:Verdana; font-size:10px;  }' ||
                                  '#main_container table tr { border-width: 1px; border-style: solid; font-size:10px; }' ||
                                  '</style> </head> <body> <div id="main_container">';
    vHtmlEnd    varchar2(100 char) := '</div> </body> </html>';
    vStrHeader  VARCHAR2(10000) := '<div align="center"><h3>' ||
                                   pReportName || '</h3></div></br></br>';

    vEmptyReport varchar2(100 char) := '<font>Данные успешно обработаны, соответствующих записей не найдено</font></br></br>';
  begin
    pMessagesCur := vHtmlHeader;
    dbms_lob.append(pMessagesCur, vStrHeader);

    FOR vListInfo IN (select m.mess_number as messnumber,
                             m.mess_date as messdate,
                             m.mess_type as messdoctype,
                             nvl(ind.member_ur_name,
                                 (ind.MEMBER_AC_SECONDNAME || ' ' ||
                                 ind.MEMBER_AC_FIRSTNAME || ' ' ||
                                 ind.MEMBER_AC_MIDDLENAME)) as fio,
                             ind.MEMBER_TYPE,
                             decode(ind.MEMBER_RESIDENCE,
                                    1,
                                    'Да',
                                    0,
                                    'Нет',
                                    '-') as isResident,
                             ind.MEMBER_RESIDENCE_COUNTRYCODE,
                             ind.MEMBER_FOREIGN,
                             ind.MEMBER_FOREIGN_ADD,
                             (select o.oper_number
                                from mess_cfm_announce_oper o
                               where o.mess_cfm_id = ind.mess_cfm_id) as opernumber,
                             ind.MEMBER_AC_DOC_TYPECODE,
                             ind.MEMBER_AC_DOC_NUMBER,
                             ind.MEMBER_AC_DOC_SERIES,
                             ind.MEMBER_AC_DOC_WHOM,
                             ind.MEMBER_AC_DOC_DATE,
                             ind.MEMBER_AC_BIRTH_DATE,
                             ind.MEMBER_AC_BIRTH_PLACE,
                             ind.MEMBER_ROLE,
                             ind.MEMBER_KIND,
                             ind.MEMBER_TAXCODE,
                             ind.MEMBER_OKPO,
                             ind.MEMBER_OKED,
                             ind.MEMBER_MAINCODE,
                             ind.MEMBER_BANK_NAME,
                             ind.MEMBER_BANK_ACCOUNT,
                             ind.MEMBER_BANK_ADDRESS,
                             ind.MEMBER_BANK_CODE,
                             pkg_analytic.GetCodeDescription(ind.MEMBER_REG_COUNRYCODE,
                                                             1019,
                                                             mv.VersionId) || ', ' ||
                             ind.MEMBER_REG_AREA || ', ' ||
                             ind.MEMBER_REG_REGION || ', ' ||
                             ind.MEMBER_REG_SITY || ', ' ||
                             ind.MEMBER_REG_STREET || ', ' ||
                             ind.MEMBER_REG_HOUSE || ', ' ||
                             ind.MEMBER_REG_OFFICE || ', ' ||
                             ind.MEMBER_REG_POSTCODE as regaddress,
                             pkg_analytic.GetCodeDescription(ind.MEMBER_SEAT_COUNRYCODE,
                                                             1019,
                                                             mv.VersionId) || ', ' ||
                             ind.MEMBER_SEAT_AREA || ', ' ||
                             ind.MEMBER_SEAT_REGION || ', ' ||
                             ind.MEMBER_SEAT_SITY || ', ' ||
                             ind.MEMBER_SEAT_STREET || ', ' ||
                             ind.MEMBER_SEAT_HOUSE || ', ' ||
                             ind.MEMBER_SEAT_OFFICE || ', ' ||
                             ind.MEMBER_SEAT_POSTCODE as seataddress,
                             ind.MEMBER_COMMENTS,
                             ind.MEMBER_PHONE,
                             ind.MEMBER_EMAIL,
                             pkg_pitaholding.ExistsInPitaPersons(ind.mess_cfm_id) as PitaPerson,
                             mv.versionid
                        FROM mess_cfm_announce_memb ind
                        join mess_cfm_announce_info m
                          on (m.mess_cfm_id = ind.mess_cfm_id)
                        join mess_cfm mc
                          on (mc.mess_cfm_id = ind.mess_cfm_id)
                        join messages_versions mv
                          on (mv.versioncode = mc.mess_version)
                       WHERE ind.member_type = 2
                          or ind.member_type = 3) LOOP
      /*     1 - Юридическое лицо
      2 - Физическое лицо
      3 - Индивидуальный предприниматель  */
      if vListInfo.PitaPerson is not null then
        vTmpLob := '<h3>Документ ' || to_char(i) || '</h3>' ||

                   TAG_TABLE_BEGIN ||

                   '<tr><td><b>' || 'Номер сообщения:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.messnumber), '-') ||
                   '</td><td><b>' || 'Дата сообщения:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.messdate, 'DD.MM.YYYY'), '-') ||
                   '</td><td><b>' || 'Вид сообщения:' || '</b></td><td>' ||
                   nvl(pkg_analytic.GetCodeDescription(vListInfo.messdoctype,
                                                       1009,
                                                       vListInfo.versionid),
                       '-') || '</td></tr>' || TAG_TABLE_END ||

                   TAG_TABLE_BEGIN ||

                   '<tr style="background:#cccccc"><td colspan="6"><b>' ||
                   'Информация об объекте:' || '</b></td></tr>' ||

                   '<tr><td><b>' || 'ФИО:' || '</b></td><td colspan="5">' ||
                   nvl(vListInfo.fio, '-') || '</td></tr>' ||

                   '<tr><td><b>' || 'Тип:' || '</b></td><td>' ||
                   pkg_analytic.GetCodeDescription(vListInfo.Member_Type,
                                                   10,
                                                   vListInfo.versionid) ||
                   '</td><td><b>' || 'Резидент:' || '</b></td><td>' ||
                   vListInfo.isResident || '</td><td colspan="2">' ||
                   nvl(pkg_analytic.GetCodeDescription(vListInfo.MEMBER_RESIDENCE_COUNTRYCODE,
                                                       1019,
                                                       vListInfo.versionid),
                       '-') || '</td></tr>' ||

                   '<tr><td><b>' || 'Документ, удостоверяющий личность:' ||
                   '</b></td><td>' ||
                   pkg_analytic.GetCodeDescription(vListInfo.Member_Ac_Doc_Typecode,
                                                   100,
                                                   vListInfo.versionid) ||
                   '</td><td><b>' || 'Серия:' || '</b></td><td>' ||
                   nvl(vListInfo.Member_Ac_Doc_Series, '-') ||
                   '</td><td><b>' || 'Номер:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Ac_Doc_Number), '-') ||
                   '</td></tr>' ||

                   '<tr><td><b>' || 'Кем выдан:' ||
                   '</b></td><td colspan="2">' ||
                   nvl(vListInfo.Member_Ac_Doc_Whom, '-') ||
                   '</td><td colspan="2"><b>' || 'Дата выдачи:' ||
                   '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Ac_Doc_Date, 'DD.MM.YYYY'),
                       '-') || '</td></tr>' ||

                   '<tr><td><b>' || 'Место рождения:' ||
                   '</b></td><td colspan="2">' ||
                   nvl(vListInfo.Member_Ac_Birth_Place, '-') ||
                   '</td><td colspan="2"><b>' || 'Дата рождения:' ||
                   '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Ac_Birth_Date, 'DD.MM.YYYY'),
                       '-') || '</td></tr>' ||

                   '<tr><td><b>' || 'Аффилированность:' ||
                   '</b></td><td colspan="5">' ||
                   pkg_analytic.GetCodeDescription(vListInfo.Member_Foreign,
                                                   1014,
                                                   vListInfo.versionid) || ' ' ||
                   vListInfo.Member_Foreign_Add || '</td></tr>' ||
                   TAG_TABLE_END || TAG_TABLE_BEGIN ||

                   '<tr style="background:#cccccc"><td colspan="4"><b>' ||
                   'Информация об операции' || '</b></td></tr>' ||

                   '<tr><td><b>' || 'Номер операции:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.opernumber), '-') ||
                   '</td><td><b>' || 'Роль в операции:' || '</b></td><td>' ||
                   pkg_analytic.GetCodeDescription(vListInfo.Member_Role,
                                                   102,
                                                   vListInfo.versionid) ||
                   '</td></tr><tr><td><b>' || 'Вид участника:' ||
                   '</b></td><td colspan="3">' ||
                   pkg_analytic.GetCodeDescription(vListInfo.Member_Kind,
                                                   1006,
                                                   vListInfo.versionid) ||
                   '</td></tr>' ||

                   TAG_TABLE_END || TAG_TABLE_BEGIN ||

                   '<tr style="background:#cccccc"><td colspan="8"><b>' ||
                   'Номера' || '</b></td></tr>' ||

                   '<tr><td><b>' || 'РНН' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Taxcode), '-') ||
                   '</td><td><b>' || 'ОКПО' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Okpo), '-') ||
                   '</td><td><b>' || 'ОКЕД' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Oked), '-') ||
                   '</td><td><b>' || 'ИНН/БИН' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Maincode), '-') ||
                   '</td></tr>' ||

                   TAG_TABLE_END || TAG_TABLE_BEGIN ||

                   '</td></tr><tr style="background:#cccccc"><td colspan="4"><b>' ||
                   'Информация о банке-корреспонденте' || '</b></td></tr>' ||

                   '<tr><td><b>' || 'Наименование:' || '</b></td><td>' ||
                   nvl(vListInfo.Member_Bank_Name, '-') || '</td><td><b>' ||
                   'Код:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Bank_Code), '-') ||
                   '</td></tr>' ||

                   '<tr><td><b>' || 'Адрес:' || '</b></td><td>' ||
                   nvl(vListInfo.Member_Bank_Address, '-') ||
                   '</td><td><b>' || 'Номер счета:' || '</b></td><td>' ||
                   nvl(vListInfo.Member_Bank_Account, '-') || '</td></tr>' ||

                   TAG_TABLE_END || TAG_TABLE_BEGIN ||

                   '<tr style="background:#cccccc"><td colspan="4"><b>' ||
                   'Контактная информация' || '</b></td></tr>' ||

                   '<tr><td><b>' ||
                   'Место регистрации (постоянного жительства):' ||
                   '</b></td><td>' || nvl(vListInfo.regaddress, '-') ||
                   '</td><td><b>' || 'Телефонный номер:' || '</b></td><td>' ||
                   nvl(to_char(vListInfo.Member_Phone), '-') ||
                   '</td></tr>' ||

                   '<tr><td><b>' ||
                   'Место пребывания (фактического нахождения):' ||
                   '</b></td><td>' || nvl(vListInfo.regaddress, '-') ||
                   '</td><td><b>' || 'Адрес электронной почты:' ||
                   '</b></td><td >' || nvl(vListInfo.Member_Email, '-') ||
                   '</td></tr>' || TAG_TABLE_END || TAG_TABLE_BEGIN ||
                   '<tr style="background:#cccccc"><td colspan="1"><b>' ||
                   'Комментарий:' || '</b></td></tr>' || '<tr><td>' ||
                   nvl(vListInfo.Member_Comments, '-') || '</td></tr>' ||
                   TAG_TABLE_END || '<hr/>';

        dbms_lob.append(vTmpLob, vListInfo.Pitaperson);
        dbms_lob.append(pMessagesCur, vTmpLob);
        i := i + 1;
      end if;
    END LOOP;
    if i = 1 then
      dbms_lob.append(pMessagesCur, vEmptyReport);
    end if;
    dbms_lob.append(pMessagesCur, vHtmlEnd);

    return result;
  exception
    when others then
      return - 1;
  end GetPitaPersListHTML;

  --GetReportNames
  function GetReportNames(ReportNamesCur out sys_refcursor) return number is
    result number default 0;
    vlang  varchar2(30 char);
  begin
    vlang := pkg_main.GetUserLangSettings;
    case vlang
      when 'Kazakh' then
        open ReportNamesCur for
          select reportnumber, reportname_kz as "reportname"
            from reports
           where tablename = 'MESSAGES_CFM';
      else
        open ReportNamesCur for
          select reportnumber, reportname
            from reports
           where tablename = 'MESSAGES_CFM';
    end case;
    return result;
  exception
    when others then
      return - 2200; --Ошибка формирования списка отчетов
  end GetReportNames;

  --GetReportName
  function GetReportName(pReportNumber in number, pReportName out varchar2)
    return number is
    result number default 0;
  begin
    select reportname
      into pReportName
      from reports
     where tablename = 'MESSAGES_CFM'
       and reportnumber = pReportNumber;
    return result;
  exception
    when others then
      return - 2201; --Ошибка при получении названия отчета
  end GetReportName;

  --MakeReport
  function MakeReport(pReportNumber in number, pReportBody out clob)
    return number is
    cDATE_FORMAT constant varchar2(21) := 'DD-MM-YYYY hh24:mm:ss';
    result      number default 0;
    pReportName varchar2(1000 char);
    vResult     number default - 1;
    vResCurr    sys_refcursor;
  begin
    vResult := GetReportName(pReportNumber, pReportName);

    case pReportNumber
      when 1 then
        begin
          vResult := GetFirstList(vResCurr);
          if vResult = 0 then
            begin
              pReportName := pReportName || ' (c ' ||
                             to_char(trunc(sysdate) - 1, cDATE_FORMAT) ||
                             ' по ' ||
                             to_char(trunc(sysdate), cDATE_FORMAT) || ')';
              vResult     := GetFirstOrSecondListHTML2(pReportName,
                                                       vResCurr,
                                                       pReportBody);
              if vResult != 0 then
                result := -2202; --Ошибка при формировании отчета
              end if;
              close vResCurr;
            end;
          else
            begin
              result := -2202; --Ошибка при формировании отчета
            end;
          end if;
        end;
      when 2 then
        begin
          vResult := GetNoFirstList(vResCurr);
          if vResult = 0 then
            begin
              pReportName := pReportName || ' (c ' ||
                             to_char(trunc(sysdate) - 1, cDATE_FORMAT) ||
                             ' по ' ||
                             to_char(trunc(sysdate), cDATE_FORMAT) || ')';
              vResult     := GetFirstOrSecondListHTML2(pReportName,
                                                       vResCurr,
                                                       pReportBody);
              if vResult != 0 then
                result := -2202; --Ошибка при формировании отчета
              end if;
              close vResCurr;
            end;
          else
            begin
              result := -2202; --Ошибка при формировании отчета
            end;
          end if;
        end;
      when 3 then
        begin
          vResult := GetSecondList(vResCurr);
          if vResult = 0 then
            begin
              pReportName := pReportName || ' (c ' ||
                             to_char(trunc(sysdate) - 1, cDATE_FORMAT) ||
                             ' по ' ||
                             to_char(trunc(sysdate), cDATE_FORMAT) || ')';
              vResult     := GetFirstOrSecondListHTML2(pReportName,
                                                       vResCurr,
                                                       pReportBody);
              if vResult != 0 then
                result := -2202; --Ошибка при формировании отчета
              end if;
              close vResCurr;
            end;
          else
            begin
              result := -2202; --Ошибка при формировании отчета
            end;
          end if;
        end;
      when 4 then
        vResult := GetPitaOrgListHTML2(pReportName, pReportBody);
        if vResult != 0 then
          result := -2202; --Ошибка при формировании отчета
        end if;
      when 5 then
        vResult := GetPitaPersListHTML(pReportName, pReportBody);
        if vResult != 0 then
          result := -2202; --Ошибка при формировании отчета
        end if;
      when 6 then
        begin
          vResult := GetThirdList(vResCurr);
          if vResult = 0 then
            begin
              pReportName := pReportName || ' (c ' ||
                             to_char(trunc(sysdate), cDATE_FORMAT) ||
                             ' по ' || to_char(sysdate, cDATE_FORMAT) || ')';
              vResult     := GetFirstOrSecondListHTML2(pReportName,
                                                       vResCurr,
                                                       pReportBody);
              if vResult != 0 then
                result := -2202; --Ошибка при формировании отчета
              end if;
              close vResCurr;
            end;
          else
            result := -2202; --Ошибка при формировании отчета
          end if;
        end;
      else
        result := -2203; --Формирование данного отчета не предусмотрено
    end case;

    return result;
  exception
    when others then
      return - 2202; --Ошибка при формировании отчета
  end MakeReport;

end PKG_Reports;
/

CREATE OR REPLACE PACKAGE KFM."PKG_IMPORT" as

  /*
  Загрузка информации по одному сообщению проходит в порядке:
  1) StartLoadingForm – генерируется идентификатор загрузки (plogid), согласно которому дописываются последующие данные;
  2) SetMessageInfo  - записывается основная информация об операции (единожды, согласно указанному в выходном параметре plogid функции StartLoadingForm). В случае попытки повторной записи генерируется исключение. Дальнейшие операции должны быть прерваны;
  3) SetMessageRefers –
  4) SetMessageMembers – записывается информация по каждому из участников операции (в количестве, указанном в параметре poper_members_count функции SetMessageInfo),
  5) По каждому из юридических лиц-участников функцией SetMessageMemberFounders записывается информация по всем его учредителям (согласно идентификатору участника pmember_id, возвращенному функцией SetMessageMembers);
  6) FinishLoadingForm  - сигнализирует о завершении загрузки данных по операции. В случае успешной проверки данные сохраняются в СДФО для дальнейшего редактирования отправки. В случае ошибки в процессе загрузки, во входной параметр передается код ошибки pInternalError, отличный от 0. При необходимости инициализировать повторную загрузку.
  */

  function FinishLoadingForm(plogid           number,
                             pInternalError   number,
                             IsAccepted       out number,
                             ErrorDescription out varchar2) return number;
  --Завершить загрузку провести предварительный контроль данных  для формирования ОДНОГО сообщения об операциии подлежащей финансвому мониторингу
  --Входные параметры:
  /*   plogid     - number  - Идентификатор  загрузки
       pInternalError - number - Код внешней ошибки (в случае возникновения ошибки, если успешно -  передать 0)
  */
  --Выходные параметры:
  /*   IsAccepted - number  - Показатель прохождения предварительного контроля (1 - пройден успешно, 0 -не пройден)
  ErrorDescription - varchar2(4000 char) - Описание ошибки при прохождении предварительного контроля сообщения */
  --Результат:
  /*       0  - загрузка завершена успешно */

  function StartLoadingForm(pversionid in number,
                            plogid     out number) return number;
  --Начать загрузку данных для формирования ОДНОГО сообщения об операциии подлежащей финансвому мониторингу
  --Входные параметры:
  /*   pversionid - number  - Идентификатор версии (на данный момент равен 1,2 или 3) */
  --Выходные параметры:
  /*   plogid     - number  - Идентификатор  загрузки*/
  --Результат:
  /*       0  - загрузка начата успешно (во все остальные функции передать plogid)
       -8030  - Неверный идентификатор версии
  */

  function PerformControl(plogid            number,
                          perrordescription out varchar2) return number;
  function SetMessageInfo(plogid                 number,
                          pmess_oper_status      number,
                          pmess_reason_code      number,
                          pmess_suspic_code      number,
                          poper_number           varchar2,
                          poper_idview           number,
                          poper_idtype           number,
                          poper_members_count    number,
                          poper_currency_code   number,
                          poper_currency_amount number,
                          poper_tenge_amount     number,
                          poper_reason           varchar2,
                          poper_doc_date         date,
                          poper_doc_number       varchar2,
                          poper_susp_first       number,
                          poper_susp_second      number,
                          poper_susp_third       number,
                          poper_difficulties     varchar2,
                          poper_dopinfo          varchar2,
                          poper_isnotidtyped     number := 0, --15.04.2010
                          poper_trans_date       date := null, --15.04.2010
                          pmess_trans_date       date := null,
                          poper_merch_types      number := null,
                          poper_merch_reginfo    varchar2 := null,
                          poper_refers_count     number := 0) return number;

  --Начать загрузку общих данных об операции для формирования ОДНОГО сообщения об операциии подлежащей финансвому мониторингу
  --Входные параметры:
  /*   plogid                 number              - Идентификатор  загрузки
       pmess_oper_status      number              - Состояние операции
                                                    1  Совершена
                                                    2  Продолжается
                                                    3  Приостановлена
                                                    4  Отказано в проведении операции
       pmess_reason_code      number              - Основание для подачи сообщения
                                                    1  Равна или превышает пороговую сумму
                                                    2  Финансирование терроризма и (или) экстремизма (для версии 1, для версий 2,3 - Подозрительная операция)
                                                    3  Подозрительная операция(для версии 1)

       pmess_suspic_code      number              - Критерий подозрительности (если выбрано основание - подозрительная операция)
       poper_number           varchar2(300)       - Номер операции
       poper_idview           number              - Код вида операции
                                                  1  Получение выигрыша, в том числе в электронной форме, по результатам проведения пари, азартной игры в игорных заведениях, а также лотереи
                                                  2  Покупка, продажа и обмен наличной иностранной валюты через обменные пункты;
                                                  3  Получение денег по чеку или векселю как разовая операция, так и операция, осуществляемая в течение семи последовательных календарных дней
                                                  4  Обмен банкнот одного достоинства на банкноты другого достоинства как разовая операция, так и операция, осуществляемая в течение семи последовательных календарных дней
                                                  5  Снятие с банковского счета или зачисление на банковский счет клиента денег как разовая операция, так и операция, осуществляемая в течение семи последовательных календарных дней
                                                  6  Зачисление или перевод на банковский счет клиента денег, осуществляемые физическим или юридическим лицом, имеющим соответственно регистрацию, место жительства или местонахождение в оффшорной зоне, а равно владеющим счетом в банке, зарегистрированном в оффшорной зоне, либо перевод денег клиентом в пользу указанной категории лиц как разовая операция, так и операция, осуществляемая в течение семи последовательных календарных дней
                                                  7  Переводы денег за границу на счета (во вклады), открытые на анонимного владельца; поступление денег из-за границы со счета (вклада), открытого на анонимного владельца, совершенные как разовая операция, так и операция, осуществляемая в течение семи последовательных календарных дней
                                                  8  Открытие сберегательного счета (вклада) в пользу третьего лица и (или) внесение денег на такой счет как разовая операция, так и операция, осуществляемая в течение семи последовательных календарных дней
                                                  9  Платежи и переводы денег, осуществляемые клиентом в пользу другого лица на безвозмездной основе
                                                  10  Приобретение (продажа), ввоз в Республику Казахстан либо вывоз из Республики Казахстан культурных ценностей
                                                  11  Операции, совершаемые юридическими лицами, с момента государственной регистрации которых прошло менее трех месяцев
                                                  12  Ввоз в Республику Казахстан либо вывоз из Республики Казахстан наличной валюты, за исключением ввоза или вывоза, осуществляемого Национальным Банком Республики Казахстан, банками и Национальным оператором почты
                                                  13  Осуществление страховой выплаты или получение страховой премии
                                                  14  Внесение, перечисление добровольных пенсионных взносов в накопительные пенсионные фонды, а также осуществление пенсионных выплат из накопительных пенсионных фондов за счет добровольных пенсионных взносов
                                                  15  Получение или предоставление имущества по договору финансового лизинга
                                                  16  Сделки по оказанию услуг, в том числе подряда, перевозки, транспортной экспедиции, хранения, комиссии, доверительного управления имуществом
                                                  17  Купля–продажа и иные операции с драгоценными металлами, драгоценными камнями и изделиями из них
                                                  18  Сделки с недвижимым и иным имуществом, подлежащим обязательной государственной регистрации
                                                  19  Сделки с ценными бумагами
       poper_idtype           number              - Код ЕКНП (В соответствии с таблицей кодов назначения платежей (приложение 2 к правилам  применения государственного классификатора Республики Казахстан - единого классификатора назначения платежей от 15.11.1999г.N 388)
       poper_members_count    number              - Количество участников в операции
       poper_currency_code    number              - Код валюты операции ( В соответствии с Государственным классификатором Республики Казахстан 07 ИСО 4217 - 2001 «Коды для обозначения валют и фондов»)
       poper_currency_amount  number              - Сумма операции в валюте ее проведения
       poper_tenge_amount     number              - Сумма операции в тенге
       poper_reason           varchar2(300)       - Основание совершения операции
       poper_doc_date         date                - Дата документа, на основании которого проведена операция
       poper_doc_number       varchar2(300)       - Номер документа, на основании которого проведена операция
       poper_susp_first       number              - Код 1-го признака подозрительности операции (справочник 1008)
                                                  1  1. Совершение сделки, не имеющей очевидного экономического смысла
                                                  2  1.1  Платежи за финансовые и иные услуги, комиссии  от сделки в которой значительно  превышают общеустановленные размеры в данном сегменте рынка
                                                  3  1.2  Снятие или зачисление на  счет   юридического  лица  денежных средств в наличной форме в случаях, когда это не обусловлено  характером  его хозяйственной деятельности
                                                  4  1.3  Осуществление платежей, переводов или зачисление денежных средств на депозит в пользу третьего лица, не имеющего очевидного экономического смысла
                                                  5  1.4  Совершение сделок с ценными бумагами на торгах фондовых бирж и иных организаторов торговли на рынке ценных бумаг, в результате которых не меняется владелец этих ценных бумаг
                                                  6  1.5  Одновременное выставление поручений на покупку и продажу ценных бумаг по ценам, имеющим существенное отклонение от текущих рыночных цен по аналогичным сделкам
                                                  7  1.6  Соглашение двух или нескольких участников торгов или их представителей о покупке (продаже) ценных бумаг по ценам, имеющим существенное отклонение от текущих рыночных цен по  аналогичным сделкам.
                                                  8  1.7  Распространение ложной или недостоверной информации с целью побудить инвесторов продавать или приобретать публично размещаемые и/или публично обращаемые ценные бумаги
                                                  9  1.8  Приобретение имущества и иных материальных ценностей в пользу третьего лица, не имеющего очевидного экономического смысла
                                                  10  1.9  Поступления или платежи за товароматериальные ценности, рыночная стоимость которых неадекватно завышена или занижена
                                                  11  1.10  Платежи или поступления денежных средств за товары и услуги лицам, не соответствующие основному профилю его деятельности и его реальным потребностям
                                                  12  1.11  Не принятие клиентом своевременных мер, предусмотренных условиями договора и требованиями законодательства Республики Казахстан для возврата валютной выручки  от экспорта товаров и (или) авансовых платежей, в случае непоставки товаров по импорту и (или) услуг.
                                                  13  1.12  Размещение   денежных   средств   во  вклад  (на депозит)     с      оформлением      документов на предъявителя
                                                  14  1.13  Перевод денежных  средств  за  границу  на  счет (вклад), открытый на анонимного владельца
                                                  15  1.14  Поступление денежных средств  из-за  границы  со счета    (вклада),   открытого   на   анонимного владельца
                                                  16  1.15  Пренебрежение более выгодными условиями оказания услуг, а также предложение необычно высокой комиссии и (или) комиссии отличающейся от обычной, сложившейся в деловой практике
                                                  17  1.16  Несоответствие сделки  деятельности организации, установленной    уставным    документом  этой организации
                                                  18  1.17  Предоставление    лицом,   беспроцентных займов  другим физическим и (или) юридическим  лицам, а равно получение такого займа
                                                  19  1.18  Получение и/или предоставление   имущества   по договору финансовой аренды (лизинга), по невыгодным, экономически нецелесообразным условиям договора
                                                  20  1.19  Поступления или платежи за услуги, которые не могут быть оказаны плательщиком или получателем средств, в силу объективных причин: отсутствие квалифицированного персонала; машин и оборудования; оборотных средств; материальных запасов и т.п.
                                                  21  1.20  Наличие нестандартных или необычно сложных инструкции по порядку проведения расчетов, отличающихся от обычной деловой практики
                                                  22  2. Совершение действий, направленных на уклонение от процедур финансового мониторинга, предусмотренных Законом.
                                                  23  2.1  Попытка проведения операций по утерянным либо похищенным документам, удостоверяющим личность клиента
                                                  24  2.2  Скупка, купля-продажа драгоценных металлов  и   драгоценных камней, ювелирных изделий,  лома драгоценных металлов, за исключением случаев, когда данная деятельность входить в круг его профессиональной деятельности
                                                  25  2.3  Немотивированный отказ в предоставлении клиентом дополнительных сведений (кроме установленных нормативными правовыми документами), но запрашиваемых в соответствии со сложившейся практикой, в том числе о своем доверителе (в случае, когда клиент выступает в качестве представителя юридического или физического лица), а также излишняя озабоченность клиента вопросами конфиденциальности в отношении проводимой операций
                                                  26  2.4  Настоятельное желание клиента работать самостоятельно только с удаленного терминала
                                                  27  2.5  Приобретение физическим и/или юридическим лицом  ценных  бумаг за наличный расчет
                                                  28  2.6  Внесение физическим     лицом     в     уставный капитал   организации   денежных средств в наличной форме
                                                  29  2.7  Получение физическим лицом наличных денежных  средств  по чеку на предъявителя, выданным нерезидентом
                                                  30  2.8  Заполнение документов на перевод или на получение денежного перевода под диктовку (под общим руководством) третьего лица и (или) лиц, присутствующих при операции
                                                  31  2.9  Проведение операции (сделки) одной из сторон которой выступают физическое и/или юридическое лицо, а равно их учредители (акционеры), имеющие регистрацию, место жительство, в оффшорной зоне, а равно владеющем счетом в банке, зарегистрированном в оффшорной зоне
                                                  32  2.10  Необоснованная поспешность в проведении операции, на которой настаивает клиент
                                                  33  2.11  Дробление платежей, переводов и иных финансовых операций с целью уклонения от обязательных процедур финансового мониторинга
                                                  34  3. Совершение операции, по которой имеются основания полагать, что данная операция направлена на финансирование терроризма и (или) экстремизма
                                                  35  3.1  Операция (сделки) и (или) ряд связанных операции одной из сторон которой прямо либо косвенно, через других лиц выступают лица и (или) организаций, включенные в соответствии данными правоохранительных и судебных органов Республики Казахстан и международных организации, признаваемых в Республике Казахстан в Перечень лиц, связанных с участием в террористической и (или) экстремисткой  деятельности
                                                  36  3.2  Операция (сделки) или ряд связанных операции одной из сторон выступают юридические лица, в состав учредителей (собственников) которых входят лица и/или организации, включенные в соответствии с данными правоохранительных и судебных органов Республики Казахстан и международных организации, признаваемых в Республике Казахстан в Перечень лиц, связанных с участием в террористической и (или) экстремисткой  деятельности
       poper_susp_second      number              - Код 2-го признака подозрительности операции
       poper_susp_third       number              - Код 3-го признака подозрительности операции
       poper_difficulties     varchar2(3000 char)      - Описание возникших затруднений квалификации опреации как подозрительной
       poper_dopinfo          varchar2(3000 char)      - Дополнительная информация по операциии

       poper_isnotidtyped            number        - Флаг - Нельзя установить код ЕКНП (1-да(нельзя), 0 -нет(установлен))
       poper_trans_date              date          - Время завершения\начала\приостановки операции

  */

  --Результат:
  /*       0  - загрузка данных завершена успешно
           -- -8031  - Неверный лог загрузки

  */

  function SetMessageRefers(plogid          number,
                            preferid        out number,
                            prefer_doc_num  varchar2,
                            prefer_doc_date date,
                            prefer_doc_oper varchar2) return number;
  --Собрать данные об
  --Входные параметры:
  /*   plogid                number              - Идентификатор  загрузки

  */

  function SetMessageMembers(plogid number,

                             pmember_kind                   number,
                             pmember_role                   number,
                             pmember_residence              number,
                             pmember_residence_countrycode  number,
                             pmember_type                   number,
                             pmember_foreign                number,
                             pmember_foreign_add            varchar2,
                             pmember_bank_code              varchar2,
                             pmember_bank_city              varchar2,
                             pmember_bank_name              varchar2,
                             pmember_bank_account           varchar2,
                             pmember_bank_address           varchar2,
                             pmember_BANK_OFFSHORE_ADDR     varchar2,
                             pmember_taxcode                varchar2, --25/03/2010 R--
                             pmember_okpo                   varchar2, --25/03/2010 R--
                             pmember_oked                   varchar2,
                             pmember_maincode               varchar2, --25/03/2010 R--
                             pmember_phone                  number,
                             pmember_email                  varchar2,
                             pmember_reg_counrycode         number,
                             pmember_reg_area               varchar2,
                             pmember_reg_region             varchar2,
                             pmember_reg_sity               varchar2,
                             pmember_reg_street             varchar2,
                             pmember_reg_house              varchar2,
                             pmember_reg_office             varchar2,
                             pmember_seat_counrycode        number,
                             pmember_seat_area              varchar2,
                             pmember_seat_region            varchar2,
                             pmember_seat_sity              varchar2,
                             pmember_seat_street            varchar2,
                             pmember_seat_house             varchar2,
                             pmember_seat_office            varchar2,
                             pmember_seat_postcode          number,
                             pmember_comments               varchar2,
                             pmember_ur_name                varchar2,
                             pmember_ur_fisthead_name       varchar2,
                             pmember_ac_secondname          varchar2,
                             pmember_ac_firstname           varchar2,
                             pmember_ac_middlename          varchar2,
                             pmember_ac_doc_typecode        number,
                             pmember_ac_doc_number          varchar2, --25/03/2010 R--
                             pmember_ac_doc_series          varchar2,
                             pmember_ac_doc_whom            varchar2,
                             pmember_ac_doc_date            date,
                             pmember_ac_birth_date          date,
                             pmember_ac_birth_place         varchar2,
                             pmember_ur_founders_count      number,
                             pmember_id                     out number,
                             pmember_reg_postcode           number := 0, --31.12.2009,
                             pMEMBER_ISCLIENT               number := null, --15.04.2010
                             pMEMBER_ISNOTNAMED             number := 0, --15.04.2010
                             pMEMBER_MEMBERCODE             number := null, --15.04.2010
                             pMEMBER_REG_AREA_CODE          number := null, --03.10.2011
                             pMEMBER_REG_REGION_CODE        number := null, --03.10.2011
                             pMEMBER_REG_SITY_CODE          number := null, --03.10.2011
                             pMEMBER_REG_STREET_CODE        number := null, --03.10.2011
                             pMEMBER_REG_HOUSE_CODE         number := null, --03.10.2011
                             pMEMBER_REG_OFFICE_CODE        number := null, --03.10.2011
                             pMEMBER_SEAT_AREA_CODE         number := null, --03.10.2011
                             pMEMBER_SEAT_REGION_CODE       number := null, --03.10.2011
                             pMEMBER_SEAT_SITY_CODE         number := null, --03.10.2011
                             pMEMBER_SEAT_STREET_CODE       number := null, --03.10.2011
                             pMEMBER_SEAT_HOUSE_CODE        number := null, --03.10.2011
                             pMEMBER_SEAT_OFFICE_CODE       number := null, --03.10.2011
                             pMEMBER_UR_OPF_CODE            number := null, --03.10.2011
                             pMEMBER_UR_FISTHEAD_SECONDNAME varchar2 := null, --03.10.2011
                             pMEMBER_UR_FISTHEAD_FIRSTNAME  varchar2 := null, --03.10.2011
                             pMEMBER_UR_FISTHEAD_MIDDLENAME varchar2 := null, --03.10.2011
                             pmoney_trans_sys               number := null) return number;

  --Собрать данные об ОДНОМ из участников операции
  --Входные параметры:
  /*   plogid                number              - Идентификатор  загрузки
       pmember_kind          number              - Вид участника операции (справочник 1006). Для версии 2 - другой справочник
                                                  1  Продавец
                                                  2  Покупатель
                                                  3  Поставщик
                                                  4  Производитель
                                                  5  Участник
                                                  6  Патентообладатель
                                                  7  Абонент
                                                  8  Даритель
                                                  9  Одаряемый
                                                  10  Получатель ренты
                                                  11  Плательщик ренты
                                                  12  Арендодатель
                                                  13  Арендатор
                                                  14  Лизингодатель
                                                  15  Лизингополучатель
                                                  16  Наймодатель
                                                  17  Наниматель
                                                  18  Ссудодатель
                                                  19  Ссудополучатель
                                                  20  Заказчик
                                                  21  Подрядчик
                                                  22  Проектировщик
                                                  23  Изыскатель
                                                  24  Исполнитель
                                                  25  Отправитель
                                                  26  Перевозчик
                                                  27  Получатель
                                                  28  Экспедитор
                                                  29  Займодатель
                                                  30  Заемщик
                                                  31  Кредитор
                                                  32  Финансовый агент
                                                  33  Вкладчик
                                                  34  Клиент
                                                  35  Эмитент
                                                  36  Владелец
                                                  37  Принципал
                                                  38  Залогодатель
                                                  39  Залогодержатель
                                                  40  Хранитель
                                                  41  Поклажедатель
                                                  42  Страховщик
                                                  43  Страхователь
                                                  44  Доверитель
                                                  45  Поверенный
                                                  46  Комитент
                                                  47  Комиссионер
                                                  48  Учредитель управления
                                                  49  Доверительный управляющий
                                                  50  Правообладатель
                                                  51  Пользователь
                                                  52  Иной участник
                                                  53  Учредитель
                                                  54  Организатор лотереи, тотализатора
                                                  55  Участник лотереи, тотализатора
                                                  56  Уполномоченное лицо
                                                  57  Выгодоприобретатель
                                                  58  Застрахованный
                                                  59  Должник
                                                  60  Инициатор
                                                  61  Лицензиар
                                                  62  Лицензиат
                                                  63  Бенефициар
                                                  64  Банк-бенефициар
                                                  65  Банк-посредник
                                                  66  Банк-получатель
       pmember_role                   number     - Участие в операции.  В версии 2 отсутствует
                                                 1  Самостоятельно
                                                 2  От имени
                                                 3  По поручению (с указанием наименования, даты и номера документа, на основании которого вступает по поручению)
       pmember_residence              number     - Резиденство (1-резидент, 0 - не резидент)
       pmember_residence_countrycode  number     - Код страны резидентства (если не резидент)
       pmember_type                   number     - Код типа участника операции
                                                 1  Юридическое лицо
                                                 2  Физическое лицо
                                                 3  Индивидуальный предприниматель
       pmember_foreign                number     - Код показателя иностранного публичного лица и аффилированных с ним лиц
                                                 1  Не является
                                                 2  Иностранное публичное должностное лицо (в случае выбора данного пункта, необходимо заполнить дополнительное поле с подробным указанием)
                                                 3  Аффилированные с иностранным публичным должностным лицом лица (в случае выбора данного пункта, необходимо заполнить дополнительное поле с подробным указанием)
       pmember_foreign_add            varchar2(3000 char)  - Дополнительное поле к коду показателя иностранного публичного лица и аффилированных с ним лиц (в случае выбора )
       pmember_bank_code              varchar2(11 char)    - Код банка-корреспондента участника операции . Для версии 2 - Код банка/филиала  участника
       pmember_bank_name              varchar2(300)   - Наименование банка-корреспондента участника операции . Для версии 2 - Наименование банка/филиала  участника
       pmember_bank_account           varchar2(300)   - Номер счета в банке-корреспонденте участника операции . Для версии 2 - Наименование банка/филиала  участника
       pmember_bank_address           varchar2(1000 char)  - Адрес банка-корреспондента участника операции . Для версии 2 - Адрес банка/филиала  участника

       --25/03/2010 R--
       pmember_taxcode                varchar2(12)      - РНН(только цифры)

       --25/03/2010 R--
       pmember_okpo                   varchar2(12)    - ОКПО(только цифры). В версии 2 отсутствует

       pmember_oked                   varchar2(5 char)     - ОКЭД

       --25/03/2010 R--
       pmember_maincode               varchar2(12)    - ИИН\БИН(только цифры)

       pmember_phone                  number(11)      - Контактный телефон
       pmember_email                  varchar2(300)   - Электронная почта
       pmember_reg_counrycode         number          - Юридический адрес - код страны (В соответствии с государственным классификатором Республики Казахстан ГК РК 06 ИСО 3166.1 - 2001 "Коды для обозначения наименований стран и их административно - территориальных подразделений. Часть 1. Коды стран")
                                                        В версии 2 - в соостветствии со справочником "Классификатор стран мира" ,
                                                        согласно приложению 6 к Правилам декларирования товаров и транспортных средств, утвержденных приказом  Агентства  таможенного контроля РК от 20.05.2003 №2355
       pmember_reg_area               varchar2(300)   - Юридический адрес - область
       pmember_reg_region             varchar2(300)   - Юридический адрес - регион
       pmember_reg_sity               varchar2(300)   - Юридический адрес - населенный пункт
       pmember_reg_street             varchar2(300)   - Юридический адрес - улица/проспект/мр-н
       pmember_reg_house              varchar2(300)   - Юридический адрес - № дома
       pmember_reg_office             varchar2(300)   - Юридический адрес - № офиса (при наличии)
       pmember_reg_postcode           number          - Юридический адрес - почтовый индекс. В версии 2 отсутствует
       pmember_seat_counrycode        number          - Фактический адрес - код страны (В соответствии с государственным классификатором Республики Казахстан ГК РК 06 ИСО 3166.1 - 2001 "Коды для обозначения наименований стран и их административно - территориальных подразделений. Часть 1. Коды стран")
                                                        В версии 2 - в соостветствии со справочником "Классификатор стран мира" ,
                                                        согласно приложению 6 к Правилам декларирования товаров и транспортных средств, утвержденных приказом  Агентства  таможенного контроля РК от 20.05.2003 №2355
       pmember_seat_area              varchar2(300)   - Фактический адрес - область
       pmember_seat_region            varchar2(300)   - Фактический адрес - район
       pmember_seat_sity              varchar2(300)   - Фактический адрес - населенный пункт
       pmember_seat_street            varchar2(300)   - Фактический адрес - улица/проспект/мр-н
       pmember_seat_house             varchar2(300)   - Фактический адрес - № дома
       pmember_seat_office            varchar2(300)   - Фактический адрес - № офиса (при наличии)
       pmember_seat_postcode          number          - Фактический адрес - почтовый индекс. В версии 2 отсутствует
       pmember_comments               varchar2(3000 char)  - Комментарии
       pmember_ur_name                varchar2(1000 char)  - Наименование участника (для юридических лиц). В версии 2 - Наименование\ФИО участника операции
       pmember_ur_fisthead_name       varchar2(300)   - ФИО первого руководителя (для юридических лиц)
       pmember_ac_secondname          varchar2(300)   - Фамилия (для физических лиц и ИП)
       pmember_ac_firstname           varchar2(300)   - Имя (для физических лиц и ИП)
       pmember_ac_middlename          varchar2(300)   - Отчество (для физических лиц и ИП)
       pmember_ac_doc_typecode        number          - Код типа документа, удостоверяющего личность (для физических лиц и ИП)
                                                      1  Удостоверение личности
                                                      2  Паспорт гражданина Республики Казахстан
                                                      3  Свидетельство о рождении (для граждан в возрасте до 16 лет)
                                                      4  Справка о приеме гражданства Республики Казахстан
                                                      5  Временное удостоверение личности*
                                                      6  Свидетельство на возвращение*
                                                      7  Справка об освобождении из мест лишения свободы
                                                      8  Военный билет - в отношении военнослужащих, офицеров и прапорщиков Вооруженных Сил, состоящих на военной службе в частях, дислоцированных на территории Республики Казахстан
                                                      9  Иные документы, признаваемые в соответствии с законодательством Республики Казахстан документами, удостоверяющие личность
                                                      11  Паспорт иностранного государства
                                                      12  Вид на жительство иностранца в Республике Казахстан
                                                      13  Удостоверение лица без гражданства
        --25/03/2010 R--
                                                       В версии 2 -
                                                       1  Удостоверение личности
                                                       2  Паспорт гражданина Республики Казахстан
                                                       3  Паспорт гражданина иностранного государства
                                                       4  Вид на жительство иностранца в Республике Казахстан
                                                       5  Удостоверение лица без гражданства
       pmember_ac_doc_number          varchar2(50 char)    - Номер  документа, удостоверяющего личность  (для физических лиц и ИП). В версии 2 - для всех типов  участников
       pmember_ac_doc_series          varchar2(300)   - Серия  документа, удостоверяющего личность  (для физических лиц и ИП). В версии 2 - для всех типов участников
       pmember_ac_doc_whom            varchar2(300)   - Кем выдан  документ, удостоверяющий личность  (для физических лиц и ИП). В версии 2 - для всех типов участников
       pmember_ac_doc_date            date            - Когда выдан  документ, удостоверяющий личность  (для физических лиц и ИП). В версии 2 - для всех типов участников
       pmember_ac_birth_date          date            - Дата рождения  (для физических лиц и ИП)
       pmember_ac_birth_place         varchar2(1000 char)  - Место рождения  (для физических лиц и ИП)
       pmember_founders_count         number,         - Количество учредителей участника (для юридических лиц, для остальных - 0)
       pmember_isclient               number          - В версии 2 - Является ли клиентом СФМ (1 - Является, 2 - Не является)
       pmember_isnotnamed              number          - В версии 2 - Флаг, нельзя ли установить имя\наименование (1- нельзя установить, 0-можно)
       pmember_membercode              number          - В версии 2 - Участник (справочник 1013):
                                                        1  Плательщик по операции
                                                        2  Получатель по операции
                                                        3  Представитель плательщика
                                                        4  Представитель получателя
                                                        5  Лицо от имени и по поручению
                                                        6  Выгодоприобретатель
      pMEMBER_REG_AREA_CODE             NUMBER        Юридический адрес - код области
      pMEMBER_REG_REGION_CODE           NUMBER        Юридический адрес - код района
      pMEMBER_REG_SITY_CODE             NUMBER        Юридический адрес - код населенного пункта
      pMEMBER_REG_STREET_CODE           NUMBER        Юридический адрес - код улицы
      pMEMBER_REG_HOUSE_CODE           NUMBER        Юридический адрес - код дома
      pMEMBER_REG_OFFICE_CODE           NUMBER        Юридический адрес - код офиса
      pMEMBER_SEAT_AREA_CODE           NUMBER        Фактический адрес - код области
      pMEMBER_SEAT_REGION_CODE         NUMBER        Фактический адрес - код района
      pMEMBER_SEAT_SITY_CODE           NUMBER        Фактический адрес - код населенного пункта
      pMEMBER_SEAT_STREET_CODE         NUMBER        Фактический адрес - код улицы
      pMEMBER_SEAT_HOUSE_CODE           NUMBER        Фактический адрес - код дома
      pMEMBER_SEAT_OFFICE_CODE         NUMBER        Фактический адрес - код офиса
      pMEMBER_UR_OPF_CODE               NUMBER        ОПФ код юридического лица
      pMEMBER_UR_FISTHEAD_SECONDNAME   VARCHAR2(300)        Фамилия первого руководителя (для юридических лиц)
      pMEMBER_UR_FISTHEAD_FIRSTNAME     VARCHAR2(300)        Имя первого руководителя (для юридических лиц)
      pMEMBER_UR_FISTHEAD_MIDDLENAME   VARCHAR2(300)        Отчество первого руководителя (для юридических лиц)
  --Выходные параметры:
       /* pmember_id                    number          - ID участника операции*/
  --Результат:
  /*       0  - загрузка данных завершена успешно
           -- -8031  - Неверный лог загрузки
           -- -8036;--нeверный номер РНН  (заменено на null)     --25/03/2010 R--
           -- -8037;--нeверный номер ОКПО  (заменено на null)    --25/03/2010 R--
           -- -8038;--нeверный номер ИИН/БИН  (заменено на null) --25/03/2010 R--
  */

  function SetMessageMemberFounders(plogid                       number,
                                    pmember_id                   number,
                                    pfounder_type                number := null,
                                    pfounder_maincode            varchar2 := null, --25/03/2010 R--
                                    pfounder_reg_counrycode      number := null,
                                    pfounder_reg_area            varchar2 := null,
                                    pfounder_reg_region          varchar2 := null,
                                    pfounder_reg_sity            varchar2 := null,
                                    pfounder_reg_street          varchar2 := null,
                                    pfounder_reg_house           varchar2 := null,
                                    pfounder_reg_office          varchar2 := null,
                                    pfounder_reg_postcode        number := null,
                                    pfounder_seat_counrycode     number := null,
                                    pfounder_seat_area           varchar2 := null,
                                    pfounder_seat_region         varchar2 := null,
                                    pfounder_seat_sity           varchar2 := null,
                                    pfounder_seat_street         varchar2 := null,
                                    pfounder_seat_house          varchar2 := null,
                                    pfounder_seat_office         varchar2 := null,
                                    pfounder_seat_postcode       number := null,
                                    pfounder_ur_name             varchar2,
                                    pfounder_ur_residence        number,
                                    pfounder_ur_residence_c_code number,
                                    pfounder_ur_reg_whom         varchar2 := null,
                                    pfounder_ur_reg_number       varchar2 := null,
                                    pfounder_ur_reg_date         date := null,
                                    pfounder_ur_taxcode          varchar2 := null, --25/03/2010 R--
                                    pfounder_ac_secondname       varchar2 := null,
                                    pfounder_ac_firstname        varchar2 := null,
                                    pfounder_ac_middlename       varchar2 := null,
                                    pfounder_ac_birth_date       date := null,
                                    pfounder_ac_reg_number       varchar2 := null, --25/03/2010 R--
                                    pfounder_ac_reg_series       varchar2 := null,
                                    pfounder_ac_reg_whom         varchar2 := null,
                                    pfounder_ac_reg_date         date := null,
                                    pfounder_id                  out number,
                                    pfounder_ur_opf_code         in number := null --03.10.2011
                                    ) return number;
  --Собрать данные об ОДНОМ из учредителей участника (идентифицируемого pmember_id)операции
  --Входные параметры:
  /*   plogid                        number        - Идентификатор  загрузки
       pmember_id                    number        - ID участника операции
       pfounder_type                 number        - Код типа учредителя операции. В версии 2 отсутствует.
                                                    1  Юридическое лицо
                                                    2  Физическое лицо
       --03.10.2011 -- Используется как обязательный параметр в версии 3!!!!!!!
                     1  Юридическое лицо
                     2  Физическое лицо
                     3  И.П.

       --25/03/2010 R--
       pfounder_maincode             varchar2(12)    - ИИН/БИН (только цифры)

       pfounder_reg_counrycode       number        - Юридический адрес - код страны (В соответствии с государственным классификатором Республики Казахстан ГК РК 06 ИСО 3166.1 - 2001 "Коды для обозначения наименований стран и их административно - территориальных подразделений. Часть 1. Коды стран")
                                                     В версии 2 отсутствует
       pfounder_reg_area             varchar2(300) - Юридический адрес - область
                                                     В версии 2 отсутствует
       pfounder_reg_region           varchar2(300) - Юридический адрес - регион
                                                     В версии 2 отсутствует
       pfounder_reg_sity             varchar2(300) - Юридический адрес - населенный пункт
                                                     В версии 2 отсутствует
       pfounder_reg_street           varchar2(300) - Юридический адрес - улица/проспект/мр-н
                                                     В версии 2 отсутствует
       pfounder_reg_house            varchar2(300) - Юридический адрес - № дома
                                                     В версии 2 отсутствует
       pfounder_reg_office           varchar2(300) - Юридический адрес - № офиса (при наличии)
                                                     В версии 2 отсутствует
       pfounder_reg_postcode         number        - Юридический адрес - почтовый индекс
                                                     В версии 2 отсутствует
       pfounder_seat_counrycode      number        - Фактический адрес - код страны (В соответствии с государственным классификатором Республики Казахстан ГК РК 06 ИСО 3166.1 - 2001 "Коды для обозначения наименований стран и их административно - территориальных подразделений. Часть 1. Коды стран")
                                                     В версии 2 отсутствует
       pfounder_seat_area            varchar2(300) - Фактический адрес - область
                                                     В версии 2 отсутствует
       pfounder_seat_region          varchar2(300) - Фактический адрес - район
                                                     В версии 2 отсутствует
       pfounder_seat_sity            varchar2(300) - Фактический адрес - населенный пункт
                                                     В версии 2 отсутствует
       pfounder_seat_street          varchar2(300) - Фактический адрес - улица/проспект/мр-н
                                                     В версии 2 отсутствует
       pfounder_seat_house           varchar2(300) - Фактический адрес - № дома
                                                     В версии 2 отсутствует
       pfounder_seat_office          varchar2(300) - Фактический адрес - № офиса (при наличии)
                                                     В версии 2 отсутствует
       pfounder_seat_postcode        number        - Фактический адрес - почтовый индекс
                                                     В версии 2 отсутствует
       pfounder_ur_name              varchar2(1000 char)- Наименование (для юридического лица). В версии 2- Наименование\ФИО учредителя.
        --03.10.2011 !!!!!Используется в версии 3 как "Название Юр.лица !!!!!!!

       pfounder_ur_residence         number        - Резиденство (1-резидент, 0 - не резидент)(для юридического лица)
       pfounder_ur_residence_c_code  number        - Код страны резидентства (если не резидент)(для юридического лица)(В соответствии с государственным классификатором Республики Казахстан ГК РК 06 ИСО 3166.1 - 2001 "Коды для обозначения наименований стран и их административно - территориальных подразделений. Часть 1. Коды стран")

       pfounder_ur_reg_whom          varchar2(300) - Орган регистрации(для юридического лица)
                                                     В версии 2 отсутствует
       pfounder_ur_reg_number        varchar2(300) - Номер государственной регистрации(для юридического лица)
                                                     В версии 2 отсутствует
       pfounder_ur_reg_date          date          - Дата регистрации (для юридического лица)
                                                     В версии 2 отсутствует
        --25/03/2010 R--
       pfounder_ur_taxcode           varchar2(12)  - РНН (для юридического лица)(только цифры)
                                                     В версии 2 отсутствует
       pfounder_ac_secondname        varchar2(300) - Фамилия (для физических лиц и ИП)
                                                     В версии 2 отсутствует.
       --03.10.2011 !!!!! !!!!!!!Используется в версии 3 для физ лиц!!!!!!!

       pfounder_ac_firstname         varchar2(300) - Имя (для физических лиц и ИП)
                                                     В версии 2 отсутствует.
       --03.10.2011 !!!!! !!!!!!!Используется в версии 3 для физ лиц!!!!!!!

       pfounder_ac_middlename        varchar2(300) - Отчество (для физических лиц и ИП)
                                                     В версии 2 отсутствует. Используется в версии 3!!!!!!!
       --03.10.2011 !!!!! !!!!!!!Используется в версии 3 для физ лиц!!!!!!!

       pfounder_ac_birth_date        date          - Дата рождения (для физических лиц и ИП)
                                                     В версии 2 отсутствует
        pfounder_ac_reg_number        varchar2(50 char)  - Номер паспорта  (для физических лиц и ИП)
                                                     В версии 2 отсутствует
       pfounder_ac_reg_series        varchar2(300) - Серия паспорта  (для физических лиц и ИП)
                                                     В версии 2 отсутствует
       pfounder_ac_reg_whom          varchar2(300) - Кем выдан паспорт  (для физических лиц и ИП)
                                                     В версии 2 отсутствует
       pfounder_ac_reg_date          date          - Когда выдан паспорт  (для физических лиц и ИП)
                                                     В версии 2 отсутствует
        --03.10.2011
       pfounder_ur_opf_code          number        - ОПФ код юридического лица. Только для для версии 3!!!!!!!
  --Выходные параметры:
       /*  pfounder_id                   number    -  ID учредителя участника операции*/
  --Результат:
  /*       0  - загрузка данных завершена успешно
           -- -8031  - Неверный лог загрузки
           -- -8036;--нeверный номер РНН  (заменено на null) --25/03/2010 R--
           -- -8038;--нeверный номер ИИН/БИН (заменено на null) --25/03/2010 R--

  */

  function SetMessageMemberAccounts(plogid         number,
                                    pmember_id     number,
                                    paccountnumber varchar2,
                                    pbankname      varchar2,
                                    pbankcode      varchar2,
                                    pbankaddress   varchar2,
                                    paccount_id    out number) return number;

  --Собрать данные об ОДНОМ из корреспондетских счетов участника (идентифицируемого pmember_id)операции
  --  Только для 2 версии
  --Входные параметры:
  /*   plogid                        number        - Идентификатор  загрузки
      pmember_id                    number        - ID участника операции
      paccountnumber                varchar2(300) - Номер счета
      pbankname                     varchar2(300) - Наименование банка
      pbankcode                     varchar2(50 char)  - Код банка
      pbankaddress                  varchar2(1000 char) - Cтрана местонахождения банка
       --25/03/2010 R--
  --Выходные параметры:
      /*  paccount_id       number    -  ID записи о корреспондентских счетах*/
  --Результат:
  /*       0  - загрузка данных завершена успешно
           -- -8031  - Неверный лог загрузки


  */

  function GetEmptyTag(ptype number) return clob;
  function GetAdditionalInfoXML(plogid      number,
                                pmembertype number,
                                pmemberid   number) return clob;
  function GetFounderInfoXML(plogid       number,
                             pfoundertype number,
                             pmemberid    number,
                             pfounderid   number) return clob;
  function LoadMessageInfo(plogid       number,
                           pMessInfoCur out sys_refcursor) return number;
  /*  plogid - лог выполняемой загрузки
  pMessInfoCur - курсор структуры:

    -- MESS_OPER_STATUS      NUMBER          Y                  Состояние операции
    -- MESS_REASON_CODE      NUMBER          Y                  Основание для подачи сообщения (справочник 1011)
    -- MESS_SUSPIC_CODE      NUMBER          Y                  Критерий подозрительности (если выбрано основание - подозрительная операция)
    -- OPER_NUMBER           VARCHAR2(300)   Y                  Номер операции
    -- OPER_IDVIEW           NUMBER          Y                  Код вида операции (справочник 1004)
    -- OPER_IDTYPE           NUMBER          Y                  Код ЕКНП (справочник 1017)
    -- OPER_MEMBERS_COUNT    NUMBER          Y                  Количество участников в операции
    -- OPER_CURRENCY_CODE    NUMBER          Y                  Код валюты операции (справочник 1018)
    -- OPER_CURRENCY_AMOUNT  NUMBER          Y                  Сумма операции в валюте ее проведения
    -- OPER_TENGE_AMOUNT     NUMBER          Y                  Сумма операции в тенге
    -- OPER_REASON           VARCHAR2(300)   Y                  Основание совершения операции
    -- OPER_DOC_DATE         DATE            Y                  Дата документа, на основании которого проведена операция
    -- OPER_DOC_NUMBER       VARCHAR2(300)   Y                  Номер документа, на основании которого проведена операция
    -- OPER_SUSP_FIRST       NUMBER          Y                  Код 1-го признака подозрительности операции (справочник 1008)
    -- OPER_SUSP_SECOND      NUMBER          Y                  Код 2-го признака подозрительности операции (справочник 1008)
    -- OPER_SUSP_THIRD       NUMBER          Y                  Код 3-го признака подозрительности операции (справочник 1008)
    -- OPER_DIFFICULTIES     varchar2(3000 char)  Y                  Описание возникших затруднений квалификации опреации как подозрительной
    -- OPER_DOPINFO          varchar2(3000 char)  Y                  Дополнительная информация по операциии

  */

  function LoadMessageMembers(plogid      number,
                              pMembersCur out sys_refcursor) return number;
  /*  plogid - лог выполняемой загрузки
  pMembersCur - курсор структуры:

   -- MEMBER_ID                     NUMBER                             ID участника операции
   -- MEMBER_KIND                   NUMBER          Y                  Вид участника операции (справочник 1006)
   -- MEMBER_ROLE                   NUMBER          Y                  Участие в операции (справочник 102)
   -- MEMBER_RESIDENCE              NUMBER          Y                  Резиденство (1-резидент, 0 - не резидент)
   -- MEMBER_RESIDENCE_COUNTRYCODE  NUMBER          Y                  Код страны резидентства (если не резидент)
   -- MEMBER_TYPE                   NUMBER          Y                  Код типа участника операции (справочник 10)
   -- MEMBER_FOREIGN                NUMBER          Y                  Код показателя иностранного публичного лица и аффилированных с ним лиц (справочник 1014)
   -- MEMBER_FOREIGN_ADD            varchar2(3000 char)  Y                  Дополнительное поле к коду показателя иностранного публичного лица и аффилированных с ним лиц (в случае выбора )
   -- MEMBER_BANK_CODE              varchar2(11 char)    Y                  Код банка-корреспондента участника операции
   -- MEMBER_BANK_NAME              VARCHAR2(300)   Y                  Наименование банка-корреспондента участника операции
   -- MEMBER_BANK_ACCOUNT           VARCHAR2(300)   Y                  Номер счета в банке-корреспонденте участника операции
   -- MEMBER_BANK_ADDRESS           varchar2(1000 char)  Y                  Адрес банка-корреспондента участника операции
   -- MEMBER_TAXCODE                NUMBER(12)      Y                  РНН
   -- MEMBER_OKPO                   NUMBER(8)       Y                  ОКПО
   -- MEMBER_OKED                   varchar2(5 char)     Y                  ОКЭД
   -- MEMBER_MAINCODE               NUMBER(12)      Y                  ИИН\БИН
   -- MEMBER_PHONE                  NUMBER          Y                  Контактный телефон
   -- MEMBER_EMAIL                  VARCHAR2(300)   Y                  Электронная почта
   -- MEMBER_REG_COUNRYCODE         NUMBER          Y                  Юридический адрес - код страны (справочник 1019)
   -- MEMBER_REG_AREA               VARCHAR2(300)   Y                  Юридический адрес - область
   -- MEMBER_REG_REGION             VARCHAR2(300)   Y                  Юридический адрес - регион
   -- MEMBER_REG_SITY               VARCHAR2(300)   Y                  Юридический адрес - населенный пункт
   -- MEMBER_REG_STREET             VARCHAR2(300)   Y                  Юридический адрес - улица/проспект/мр-н
   -- MEMBER_REG_HOUSE              VARCHAR2(300)   Y                  Юридический адрес - № дома
   -- MEMBER_REG_OFFICE             VARCHAR2(300)   Y                  Юридический адрес - № офиса (при наличии)
   -- MEMBER_REG_POSTCODE           NUMBER          Y                  Юридический адрес - почтовый индекс
   -- MEMBER_SEAT_COUNRYCODE        NUMBER          Y                  Фактический адрес - код страны (справочник 1019)
   -- MEMBER_SEAT_AREA              VARCHAR2(300)   Y                  Фактический адрес - область
   -- MEMBER_SEAT_REGION            VARCHAR2(300)   Y                  Фактический адрес - район
   -- MEMBER_SEAT_SITY              VARCHAR2(300)   Y                  Фактический адрес - населенный пункт
   -- MEMBER_SEAT_STREET            VARCHAR2(300)   Y                  Фактический адрес - улица/проспект/мр-н
   -- MEMBER_SEAT_HOUSE             VARCHAR2(300)   Y                  Фактический адрес - № дома
   -- MEMBER_SEAT_OFFICE            VARCHAR2(300)   Y                  Фактический адрес - № офиса (при наличии)
   -- MEMBER_SEAT_POSTCODE          NUMBER          Y                  Фактический адрес - почтовый индекс
   -- MEMBER_COMMENTS               varchar2(3000 char)  Y                  Комментарии
   -- MEMBER_UR_NAME                varchar2(1000 char)  Y                  Наименование участника (для юридических лиц)
   -- MEMBER_UR_FISTHEAD_NAME       VARCHAR2(300)   Y                  ФИО первого руководителя (для юридических лиц)
   -- MEMBER_AC_SECONDNAME          VARCHAR2(300)   Y                  Фамилия (для физических лиц и ИП)
   -- MEMBER_AC_FIRSTNAME           VARCHAR2(300)   Y                  Имя (для физических лиц и ИП)
   -- MEMBER_AC_MIDDLENAME          VARCHAR2(300)   Y                  Отчество (для физических лиц и ИП)
   -- MEMBER_AC_DOC_TYPECODE        NUMBER          Y                  Код типа документа, удостоверяющего личность (справочник 100)  (для физических лиц и ИП)
   -- MEMBER_AC_DOC_NUMBER          NUMBER          Y                  Номер  документа, удостоверяющего личность  (для физических лиц и ИП)
   -- MEMBER_AC_DOC_SERIES          VARCHAR2(300)   Y                  Серия  документа, удостоверяющего личность  (для физических лиц и ИП)
   -- MEMBER_AC_DOC_WHOM            VARCHAR2(300)   Y                  Кем выдан  документ, удостоверяющий личность  (для физических лиц и ИП)
   -- MEMBER_AC_DOC_DATE            DATE            Y                  Когда выдан  документ, удостоверяющий личность  (для физических лиц и ИП)
   -- MEMBER_AC_BIRTH_DATE          DATE            Y                  Дата рождения  (для физических лиц и ИП)
   -- MEMBER_AC_BIRTH_PLACE         varchar2(1000 char)  Y                  Место рождения  (для физических лиц и ИП)

  */

  function LoadMessageFounders(plogid       in number,
                               pmember_id   number,
                               pFoundersCur out sys_refcursor) return number;
  /*  plogid - лог выполняемой загрузки
      pmember_id - id участника

  pFoundersCur - курсор структуры:

  -- FOUNDER_ID                   NUMBER                             ID учредителя участника операции
  -- FOUNDER_TYPE                 NUMBER          Y                  Код типа учредителя операции (справочник 10)
  -- FOUNDER_MAINCODE             NUMBER(12)      Y                  ИИН/БИН
  -- FOUNDER_REG_COUNRYCODE       NUMBER          Y                  Юридический адрес - код страны (справочник 1019)
  -- FOUNDER_REG_AREA             VARCHAR2(300)   Y                  Юридический адрес - область
  -- FOUNDER_REG_REGION           VARCHAR2(300)   Y                  Юридический адрес - регион
  -- FOUNDER_REG_SITY             VARCHAR2(300)   Y                  Юридический адрес - населенный пункт
  -- FOUNDER_REG_STREET           VARCHAR2(300)   Y                  Юридический адрес - улица/проспект/мр-н
  -- FOUNDER_REG_HOUSE            VARCHAR2(300)   Y                  Юридический адрес - № дома
  -- FOUNDER_REG_OFFICE           VARCHAR2(300)   Y                  Юридический адрес - № офиса (при наличии)
  -- FOUNDER_REG_POSTCODE         NUMBER          Y                  Юридический адрес - почтовый индекс
  -- FOUNDER_SEAT_COUNRYCODE      NUMBER          Y                  Фактический адрес - код страны (справочник 1019)
  -- FOUNDER_SEAT_AREA            VARCHAR2(300)   Y                  Фактический адрес - область
  -- FOUNDER_SEAT_REGION          VARCHAR2(300)   Y                  Фактический адрес - район
  -- FOUNDER_SEAT_SITY            VARCHAR2(300)   Y                  Фактический адрес - населенный пункт
  -- FOUNDER_SEAT_STREET          VARCHAR2(300)   Y                  Фактический адрес - улица/проспект/мр-н
  -- FOUNDER_SEAT_HOUSE           VARCHAR2(300)   Y                  Фактический адрес - № дома
  -- FOUNDER_SEAT_OFFICE          VARCHAR2(300)   Y                  Фактический адрес - № офиса (при наличии)
  -- FOUNDER_SEAT_POSTCODE        NUMBER          Y                  Фактический адрес - почтовый индекс
  -- FOUNDER_UR_NAME              varchar2(1000 char)  Y                  Наименование (для юридического лица)
  -- FOUNDER_UR_RESIDENCE         NUMBER          Y                  Резиденство (1-резидент, 0 - не резидент)(для юридического лица)
  -- FOUNDER_UR_RESIDENCE_C_CODE  NUMBER          Y                  Код страны резидентства (если не резидент)(для юридического лица)
  -- FOUNDER_UR_REG_WHOM          VARCHAR2(300)   Y                  Орган регистрации(для юридического лица)
  -- FOUNDER_UR_REG_NUMBER        VARCHAR2(300)   Y                  Номер государственной регистрации(для юридического лица)
  -- FOUNDER_UR_REG_DATE          DATE            Y                  Дата регистрации (для юридического лица)
  -- FOUNDER_UR_TAXCODE           NUMBER(12)      Y                  РНН
  -- FOUNDER_AC_SECONDNAME        VARCHAR2(300)   Y                  Фамилия (для физических лиц и ИП)
  -- FOUNDER_AC_FIRSTNAME         VARCHAR2(300)   Y                  Имя (для физических лиц и ИП)
  -- FOUNDER_AC_MIDDLENAME        VARCHAR2(300)   Y                  Отчество (для физических лиц и ИП)
  -- FOUNDER_AC_BIRTH_DATE        DATE            Y                  Дата рождения (для физических лиц и ИП)
  -- FOUNDER_AC_REG_NUMBER        NUMBER          Y                  Номер паспорта  (для физических лиц и ИП)
  -- FOUNDER_AC_REG_SERIES        VARCHAR2(300)   Y                  Серия паспорта  (для физических лиц и ИП)
  -- FOUNDER_AC_REG_WHOM          VARCHAR2(300)   Y                  Кем выдан паспорт  (для физических лиц и ИП)
  -- FOUNDER_AC_REG_DATE          DATE            Y                  Когда выдан паспорт  (для физических лиц и ИП)


  */
  --
  function refers_2_xml(p_log_id in NUMBER) return xmltype;

  function GetFoundersXML(plogid    number,
                          pmemberid number) return clob;
  function GetMembersXML(plogid number) return CLOB;
  function GetMessInfoXML(plogid number) return CLOB;

  function CreateImportXML(plogid number) return CLOB;
  /*function GetBool(param in number) return varchar2;*/
  function CreateImportXML_2(plogid number) return CLOB;
  function GetAccountsXML_2(plogid    number,
                            pmemberid number) return CLOB;
  function GetFounderInfoXML_2(plogid     number,
                               pmemberid  number,
                               pfounderid number) return clob;
  function GetFoundersXML_2(plogid    number,
                            pmemberid number) return xmltype;
  function GetAdditionalInfoXML_2(plogid      number,
                                  pmembertype number,
                                  pmemberid   number) return clob;
  function GetAdditionalInfoXML_3(plogid      number,
                                  pmembertype number,
                                  pmemberid   number) return clob;
  function GetFounderInfoXML_3(plogid       number,
                               pfoundertype number,
                               pmemberid    number,
                               pfounderid   number) return clob;
  function GetFoundersXML_3(plogid    number,
                            pmemberid number) return CLOB;
  function CreateImportXML_3(plogid number) return CLOB;
  /*function IsRightCodeVal(plogid number,
  pTableName varchar2,
  pFieldName varchar2,
  pCodeType number,

  pException out varchar2) return number;*/

end PKG_Import;
/

CREATE OR REPLACE PACKAGE BODY KFM."PKG_IMPORT" as

  function PerformControl(plogid            number,
                          perrordescription out varchar2) return number is
    result        number default 0;
    vcount        number;
    vcount_refer  number default 0;
    vcount_memb   number default 0;
    vcount_found  number default 0;
    vcounter_memb number default 1;
    pExc          varchar2(3000 char);
    pversion      number;

  begin
    --1 - проверка количества участников
    select count(*)
    into vcount
    from imp_messinfo
    where log_id = plogid;
    if vcount = 0 then
      perrordescription := 'Ошибочные данные, либо не внесена информация об операции и\или основаниях подачи сообщения';
      result            := -8032;
    end if;

    select count(*)
    into vcount
    from imp_refer im
    where im.log_id = plogid;
    select oper_refers_count
    into vcount_refer
    from imp_messinfo
    where log_id = plogid;
    if vcount <> vcount_refer then
      perrordescription := 'Число ссылок на документы не соответствует их количеству';
      result            := -8032;
    end if;

    select count(*)
    into vcount
    from imp_members im
    where im.log_id = plogid;
    select oper_members_count
    into vcount_memb
    from imp_messinfo
    where log_id = plogid;
    if vcount <> vcount_memb then
      perrordescription := 'Число участников не соответствует их количеству';
      result            := -8032;
    end if;
    loop
      exit when vcounter_memb > vcount_memb;
      select count(*)
      into vcount
      from imp_found imf
      where imf.log_id = plogid
      and imf.member_id = vcounter_memb;
      select MEMBER_UR_FOUNDERS_COUNT
      into vcount_found
      from imp_members
      where log_id = plogid
      and member_id = vcounter_memb;

      if vcount <> vcount_found then
        perrordescription := 'Число уредителей участника не соответствует их количеству';
        result            := -8032;
        exit;
      end if;
      vcounter_memb := vcounter_memb + 1;
    end loop;
    select version
    into pversion
    from imp_audit
    where logid = plogid;

    for prec in ( /*select tablename,tablefield,analytictype
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              from analytictypes_depend
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              where version=pversion and tablename is not null*/
                 select c.analytictype,
                         t.tablename,
                         t.tablefield
                 from analytictypes_column_depend t
                 join analytictypes_vers_depend c
                 on (t.datacode = c.datacode and t.version = c.version)
                 where t.version = pversion
                 and t.stepid = 1) loop
      begin

        if pkg_common.IsRightCodeVal(plogid, prec.tablename, prec.tablefield, prec.analytictype, pExc) = -1 then
          perrordescription := perrordescription || pExc;
          result            := -8032;
        end if;
      exception
        when others then
          null;

      end;
    end loop;

    return result;
  exception
    when others then
      null;

      --3 - проверка вводимых данных по  типам участников
      --4 - проерка вводимых данных по типам учредителей

      return result;
  end;

  --Завершить загрузку провести предварительный контроль данных  для формирования ОДНОГО сообщения об операциии подлежащей финансвому мониторингу
  --Входные параметры:
  /*   plogid     - number  - Идентификатор  загрузки*/
  --Выходные параметры:
  /*   IsAccepted - number  - Показатель прохождения предварительного контроля (1 - пройден успешно, 0 -не пройден)
  ErrorDescription - varchar2(4000 char) - Описание ошибки при прохождении предварительного контроля сообщения */
  --Результат:
  /*       0  - загрузка завершена успешно */

  function FinishLoadingForm(plogid           number,
                             pInternalError   number,
                             IsAccepted       out number,
                             ErrorDescription out varchar2) return number is
    result      number default 0;
    errorresult clob;
    pXml        clob;
    pXmlcheck   Clob;
    --pElectr number default 0;
    pmessid  number default 0;
    vcount   number default 0;
    pversion number;
    pragma autonomous_transaction;
  begin
    select count(*)
    into vcount
    from imp_audit
    where logid = plogid;
    if vcount = 0 then
      return - 8031;
    end if;

    result := 0;--PerformControl(plogid, errorresult);
    if result <> 0 then
      update imp_audit
      set pimportfinish    = sysdate,
          isaccepted       = 0,
          errordescription = substr(errorresult, 1, 4000)
      where logid = plogid;

      ErrorDescription := substr(errorresult, 1, 4000);
      IsAccepted       := 0;
    else
      begin
        select version
        into pversion
        from imp_audit
        where logid = plogid;
        case pversion
          when 1 then
            pXml := CreateImportXML(plogid);
          when 2 then
            pXml := CreateImportXML_2(plogid);
          when 3 then
            pXml := CreateImportXML_3(plogid);
        end case;
        update imp_audit
        set pimportfinish = sysdate,
            isaccepted    = 1
        where logid = plogid;

        IsAccepted := 1;
      exception
        when others then
          update imp_audit
          set pimportfinish    = sysdate,
              isaccepted       = 0,
              errordescription = 'Ошибка при формировании XML'
          where logid = plogid;
      end;
      result := pkg_messages_cfm.Save_Message(pXml, pmessid, pXmlcheck);
      update imp_audit
      set messid          = pmessid,
          ploading_finish = sysdate
      where logid = plogid;
      if result <> 0 then
        null;
      end if;
    end if;
    commit;
    return result;
  end;

  --Начать загрузку данных для формирования ОДНОГО сообщения об операциии подлежащей финансвому мониторингу
  --Входные параметры:
  /*   pversionid - number  - Идентификатор версии (на данный момент равен 1) */
  --Выходные параметры:
  /*   plogid     - number  - Идентификатор  загрузки*/
  --Результат:
  /*       0  - загрузка начата успешно (во все остальные функции передать plogid)
       -8030  - Неверный идентификатор версии
       -8031  - Неверный лог загрузки
       -8032  - загрузка не произведена, т.к. промежуточный контроль прошел неудачно
  */
  function StartLoadingForm(pversionid in number,
                            plogid     out number) return number is
    result number default 0;

    pragma autonomous_transaction;
  begin
    if pversionid not in (1, 2, 3) then
      result := -8030;
    else
      --добавить проверку на удачное завершение
      insert into imp_audit
        (pimportstart,
         version)
      values
        (sysdate,
         pversionid)
      returning logid into plogid;
      commit;
    end if;
    return result;
  end;

  function SetMessageInfo(plogid                 number,
                          pmess_oper_status      number,
                          pmess_reason_code      number,
                          pmess_suspic_code      number,
                          poper_number           varchar2,
                          poper_idview           number,
                          poper_idtype           number,
                          poper_members_count    number,
                          poper_currency_code   number,
                          poper_currency_amount number,
                          poper_tenge_amount     number,
                          poper_reason           varchar2,
                          poper_doc_date         date,
                          poper_doc_number       varchar2,
                          poper_susp_first       number,
                          poper_susp_second      number,
                          poper_susp_third       number,
                          poper_difficulties     varchar2,
                          poper_dopinfo          varchar2,
                          poper_isnotidtyped     number := 0,
                          poper_trans_date       date := null,
                          pmess_trans_date       date := null,
                          poper_merch_types      number := null,
                          poper_merch_reginfo    varchar2 := null,
                          poper_refers_count     number := 0) return number is
    result number default 0;

    pversion number;
    pragma autonomous_transaction;
  begin
    begin
      select version
      into pversion
      from imp_audit
      where logid = plogid;
    exception
      when others then
        commit;
        return - 8031;
    end;
    insert into imp_messinfo
      (log_id,
       mess_oper_status,
       mess_reason_code,
       mess_suspic_code,
       oper_number,
       oper_idview,
       oper_idtype,
       oper_members_count,
       oper_currency_code,
       oper_currency_amount,
       oper_tenge_amount,
       oper_reason,
       oper_doc_date,
       oper_doc_number,
       oper_susp_first,
       oper_susp_second,
       oper_susp_third,
       oper_difficulties,
       oper_dopinfo,
       oper_isnotidtyped,
       oper_trans_date,
       mess_trans_date,
       oper_merch_types,
       oper_merch_reginfo,
       oper_refers_count)
    values
      (plogid,
       pmess_oper_status,
       pmess_reason_code,
       pmess_suspic_code,
       poper_number,
       poper_idview,
       poper_idtype,
       poper_members_count,
       poper_currency_code,
       poper_currency_amount,
       poper_tenge_amount,
       poper_reason,
       poper_doc_date,
       poper_doc_number,
       poper_susp_first,
       poper_susp_second,
       poper_susp_third,
       poper_difficulties,
       poper_dopinfo,
       poper_isnotidtyped,
       poper_trans_date,
       pmess_trans_date,
       poper_merch_types,
       poper_merch_reginfo,
       poper_refers_count);
    commit;
    return result;

    --exception when others then null;
    -- -8031  - Неверный лог загрузки
    --Добавить поле readyforimport - когда число участников будет равно их количеству (в том числе и учредителей участника)

  end;

  function SetMessageRefers(plogid          number,
                            preferid        out number,
                            prefer_doc_num  varchar2,
                            prefer_doc_date date,
                            prefer_doc_oper varchar2) return number is
    result number default 0;
    vcount number default 0;
    pragma autonomous_transaction;
  begin
    select count(*)
    into vcount
    from imp_audit
    where logid = plogid;
    if vcount = 0 then
      commit;
      return - 8031;
    end if;
    --25/03/2010 R--

    select nvl(max(im.referid), 0) + 1
    into preferid
    from imp_refer im
    where im.log_id = plogid;

    insert into imp_refer
      (log_id,
       referid,
       refer_doc_num,
       refer_doc_date,
       refer_doc_oper)
    values
      (plogid,
       preferid,
       prefer_doc_num,
       prefer_doc_date,
       prefer_doc_oper)
    returning referid into preferid;
    commit;
    return result;
  end;

  function SetMessageMembers(plogid                         number,
                             pmember_kind                   number,
                             pmember_role                   number,
                             pmember_residence              number,
                             pmember_residence_countrycode  number,
                             pmember_type                   number,
                             pmember_foreign                number,
                             pmember_foreign_add            varchar2,
                             pmember_bank_code              varchar2,
                             pmember_bank_city              varchar2,
                             pmember_bank_name              varchar2,
                             pmember_bank_account           varchar2,
                             pmember_bank_address           varchar2,
                 pmember_BANK_OFFSHORE_ADDR     varchar2,
                             pmember_taxcode                varchar2, --25/03/2010 R--
                             pmember_okpo                   varchar2, --25/03/2010 R--
                             pmember_oked                   varchar2,
                             pmember_maincode               varchar2, --25/03/2010 R--
                             pmember_phone                  number,
                             pmember_email                  varchar2,
                             pmember_reg_counrycode         number,
                             pmember_reg_area               varchar2,
                             pmember_reg_region             varchar2,
                             pmember_reg_sity               varchar2,
                             pmember_reg_street             varchar2,
                             pmember_reg_house              varchar2,
                             pmember_reg_office             varchar2,
                             pmember_seat_counrycode        number,
                             pmember_seat_area              varchar2,
                             pmember_seat_region            varchar2,
                             pmember_seat_sity              varchar2,
                             pmember_seat_street            varchar2,
                             pmember_seat_house             varchar2,
                             pmember_seat_office            varchar2,
                             pmember_seat_postcode          number,
                             pmember_comments               varchar2,
                             pmember_ur_name                varchar2,
                             pmember_ur_fisthead_name       varchar2,
                             pmember_ac_secondname          varchar2,
                             pmember_ac_firstname           varchar2,
                             pmember_ac_middlename          varchar2,
                             pmember_ac_doc_typecode        number,
                             pmember_ac_doc_number          varchar2, --25/03/2010 R--
                             pmember_ac_doc_series          varchar2,
                             pmember_ac_doc_whom            varchar2,
                             pmember_ac_doc_date            date,
                             pmember_ac_birth_date          date,
                             pmember_ac_birth_place         varchar2,
                             pmember_ur_founders_count      number,
                             pmember_id                     out number,
                             pmember_reg_postcode           number := 0,
                             pMEMBER_ISCLIENT               number := null,
                             pMEMBER_ISNOTNAMED             number := 0,
                             pMEMBER_MEMBERCODE             number := null,
                             pMEMBER_REG_AREA_CODE          number := null, --03.10.2011
                             pMEMBER_REG_REGION_CODE        number := null, --03.10.2011
                             pMEMBER_REG_SITY_CODE          number := null, --03.10.2011
                             pMEMBER_REG_STREET_CODE        number := null, --03.10.2011
                             pMEMBER_REG_HOUSE_CODE         number := null, --03.10.2011
                             pMEMBER_REG_OFFICE_CODE        number := null, --03.10.2011
                             pMEMBER_SEAT_AREA_CODE         number := null, --03.10.2011
                             pMEMBER_SEAT_REGION_CODE       number := null, --03.10.2011
                             pMEMBER_SEAT_SITY_CODE         number := null, --03.10.2011
                             pMEMBER_SEAT_STREET_CODE       number := null, --03.10.2011
                             pMEMBER_SEAT_HOUSE_CODE        number := null, --03.10.2011
                             pMEMBER_SEAT_OFFICE_CODE       number := null, --03.10.2011
                             pMEMBER_UR_OPF_CODE            number := null, --03.10.2011
                             pMEMBER_UR_FISTHEAD_SECONDNAME varchar2 := null, --03.10.2011
                             pMEMBER_UR_FISTHEAD_FIRSTNAME  varchar2 := null, --03.10.2011
                             pMEMBER_UR_FISTHEAD_MIDDLENAME varchar2 := null, --03.10.2011
                             pmoney_trans_sys               number := null) return number is
    result            number default 0;
    vcount            number default 0;
    tempnumber        number;
    pmember_taxcode_  varchar2(12);
    pmember_okpo_     varchar2(12);
    pmember_maincode_ varchar2(12);
    pragma autonomous_transaction;
  begin
    select count(*)
    into vcount
    from imp_audit
    where logid = plogid;
    if vcount = 0 then
      commit;
      return - 8031;
    end if;
    --25/03/2010 R--
    begin
      select to_number(pmember_taxcode)
      into tempnumber
      from dual;
      pmember_taxcode_ := pmember_taxcode;
    exception
      when others then
        pmember_taxcode_ := null;
        result           := -8036; --нeверный номер РНН
    end;
    begin
      select to_number(pmember_okpo)
      into tempnumber
      from dual;
      pmember_okpo_ := pmember_okpo;
    exception
      when others then
        pmember_okpo_ := null;
        result        := -8037; --нeверный номер ОКПО
    end;
    begin
      select to_number(pmember_maincode)
      into tempnumber
      from dual;
      pmember_maincode_ := pmember_maincode;
    exception
      when others then
        pmember_maincode_ := null;
        result            := -8038; --нeверный номер ИИН/БИН
    end;
    --25/03/2010 R--

    select nvl(max(im.member_id), 0) + 1
    into pmember_id
    from imp_members im
    where im.log_id = plogid;

    insert into imp_members
      (log_id,
       member_id,
       member_kind,
       member_role,
       member_residence,
       member_residence_countrycode,
       member_type,
       member_foreign,
       member_foreign_add,
       member_bank_code,
       member_bank_city,
       member_bank_name,
       member_bank_account,
       member_bank_address,
       MEMBER_BANK_OFFSHORE_ADDR,
       member_taxcode,
       member_okpo,
       member_oked,
       member_maincode,
       member_phone,
       member_email,
       member_reg_counrycode,
       member_reg_area,
       member_reg_region,
       member_reg_sity,
       member_reg_street,
       member_reg_house,
       member_reg_office,
       member_reg_postcode,
       member_seat_counrycode,
       member_seat_area,
       member_seat_region,
       member_seat_sity,
       member_seat_street,
       member_seat_house,
       member_seat_office,
       member_seat_postcode,
       member_comments,
       member_ur_name,
       member_ur_fisthead_name,
       member_ac_secondname,
       member_ac_firstname,
       member_ac_middlename,
       member_ac_doc_typecode,
       member_ac_doc_number,
       member_ac_doc_series,
       member_ac_doc_whom,
       member_ac_doc_date,
       member_ac_birth_date,
       member_ac_birth_place,
       member_isclient,
       member_isnotnamed,
       member_membercode,
       member_ur_founders_count,
       member_reg_area_code,
       member_reg_region_code,
       member_reg_sity_code,
       member_reg_street_code,
       member_reg_house_code,
       member_reg_office_code,
       member_seat_area_code,
       member_seat_region_code,
       member_seat_sity_code,
       member_seat_street_code,
       member_seat_house_code,
       member_seat_office_code,
       member_ur_opf_code,
       member_ur_fisthead_secondname,
       member_ur_fisthead_firstname,
       member_ur_fisthead_middlename,
       money_trans_sys)
    values
      (plogid,
       pmember_id,
       pmember_kind,
       pmember_role,
       pmember_residence,
       pmember_residence_countrycode,
       pmember_type,
       pmember_foreign,
       pmember_foreign_add,
       pmember_bank_code,
       pmember_bank_city,
       pmember_bank_name,
       pmember_bank_account,
       pmember_bank_address,
       pmember_BANK_OFFSHORE_ADDR,
       pmember_taxcode_,
       pmember_okpo_,
       pmember_oked,
       pmember_maincode_,
       pmember_phone,
       pmember_email,
       pmember_reg_counrycode,
       pmember_reg_area,
       pmember_reg_region,
       pmember_reg_sity,
       pmember_reg_street,
       pmember_reg_house,
       pmember_reg_office,
       pmember_reg_postcode,
       pmember_seat_counrycode,
       pmember_seat_area,
       pmember_seat_region,
       pmember_seat_sity,
       pmember_seat_street,
       pmember_seat_house,
       pmember_seat_office,
       pmember_seat_postcode,
       pmember_comments,
       pmember_ur_name,
       pmember_ur_fisthead_name,
       pmember_ac_secondname,
       pmember_ac_firstname,
       pmember_ac_middlename,
       pmember_ac_doc_typecode,
       pmember_ac_doc_number,
       pmember_ac_doc_series,
       pmember_ac_doc_whom,
       pmember_ac_doc_date,
       pmember_ac_birth_date,
       pmember_ac_birth_place,
       pmember_isclient,
       pmember_isnotnamed,
       pmember_membercode,
       pmember_ur_founders_count,
       pmember_reg_area_code,
       pmember_reg_region_code,
       pmember_reg_sity_code,
       pmember_reg_street_code,
       pmember_reg_house_code,
       pmember_reg_office_code,
       pmember_seat_area_code,
       pmember_seat_region_code,
       pmember_seat_sity_code,
       pmember_seat_street_code,
       pmember_seat_house_code,
       pmember_seat_office_code,
       pmember_ur_opf_code,
       pmember_ur_fisthead_secondname,
       pmember_ur_fisthead_firstname,
       pmember_ur_fisthead_middlename,
       pmoney_trans_sys)
    returning member_id into pmember_id;
    commit;
    return result;
  end;

  function SetMessageMemberFounders(plogid                       number,
                                    pmember_id                   number,
                                    pfounder_type                number := null,
                                    pfounder_maincode            varchar2 := null, --25/03/2010 R--
                                    pfounder_reg_counrycode      number := null,
                                    pfounder_reg_area            varchar2 := null,
                                    pfounder_reg_region          varchar2 := null,
                                    pfounder_reg_sity            varchar2 := null,
                                    pfounder_reg_street          varchar2 := null,
                                    pfounder_reg_house           varchar2 := null,
                                    pfounder_reg_office          varchar2 := null,
                                    pfounder_reg_postcode        number := null,
                                    pfounder_seat_counrycode     number := null,
                                    pfounder_seat_area           varchar2 := null,
                                    pfounder_seat_region         varchar2 := null,
                                    pfounder_seat_sity           varchar2 := null,
                                    pfounder_seat_street         varchar2 := null,
                                    pfounder_seat_house          varchar2 := null,
                                    pfounder_seat_office         varchar2 := null,
                                    pfounder_seat_postcode       number := null,
                                    pfounder_ur_name             varchar2,
                                    pfounder_ur_residence        number,
                                    pfounder_ur_residence_c_code number,
                                    pfounder_ur_reg_whom         varchar2 := null,
                                    pfounder_ur_reg_number       varchar2 := null,
                                    pfounder_ur_reg_date         date := null,
                                    pfounder_ur_taxcode          varchar2 := null, --25/03/2010 R--
                                    pfounder_ac_secondname       varchar2 := null,
                                    pfounder_ac_firstname        varchar2 := null,
                                    pfounder_ac_middlename       varchar2 := null,
                                    pfounder_ac_birth_date       date := null,
                                    pfounder_ac_reg_number       varchar2 := null, --25/03/2010 R--
                                    pfounder_ac_reg_series       varchar2 := null,
                                    pfounder_ac_reg_whom         varchar2 := null,
                                    pfounder_ac_reg_date         date := null,
                                    pfounder_id                  out number,
                                    pfounder_ur_opf_code         in number := null --03.10.2011
                                    ) return number is
    result               number default 0;
    vcount               number default 0;
    pfounder_maincode_   varchar2(12);
    pfounder_ur_taxcode_ varchar2(12);
    tempnumber           number;
    pragma autonomous_transaction;
  begin
    select count(*)
    into vcount
    from imp_audit
    where logid = plogid;
    if vcount = 0 then
      commit;
      return - 8031;
    end if;
    --25/03/2010 R--
    begin
      select to_number(pfounder_maincode)
      into tempnumber
      from dual;
      pfounder_maincode_ := pfounder_maincode;
    exception
      when others then
        pfounder_maincode_ := null;
        result             := -8038; --нeкорректный номер ИНН\БИН
    end;
    begin
      select to_number(pfounder_ur_taxcode)
      into tempnumber
      from dual;
      pfounder_ur_taxcode_ := pfounder_ur_taxcode;
    exception
      when others then
        pfounder_ur_taxcode_ := null;
        result               := -8036; --нeкорректный номер РНН
    end;
    --25/03/2010 R--
    select nvl(max(ifnd.founder_id), 0) + 1
    into pfounder_id
    from imp_found ifnd
    where ifnd.log_id = plogid
    and ifnd.member_id = pmember_id;

    insert into imp_found
      (log_id,
       member_id,
       founder_id,
       founder_type,
       founder_maincode,
       founder_reg_counrycode,
       founder_reg_area,
       founder_reg_region,
       founder_reg_sity,
       founder_reg_street,
       founder_reg_house,
       founder_reg_office,
       founder_reg_postcode,
       founder_seat_counrycode,
       founder_seat_area,
       founder_seat_region,
       founder_seat_sity,
       founder_seat_street,
       founder_seat_house,
       founder_seat_office,
       founder_seat_postcode,
       founder_ur_name,
       founder_ur_residence,
       founder_ur_residence_c_code,
       founder_ur_reg_whom,
       founder_ur_reg_number,
       founder_ur_reg_date,
       founder_ur_taxcode,
       founder_ac_secondname,
       founder_ac_firstname,
       founder_ac_middlename,
       founder_ac_birth_date,
       founder_ac_reg_number,
       founder_ac_reg_series,
       founder_ac_reg_whom,
       founder_ac_reg_date,
       founder_ur_opf_code)
    values
      (plogid,
       pmember_id,
       pfounder_id,
       pfounder_type,
       pfounder_maincode_,
       pfounder_reg_counrycode,
       pfounder_reg_area,
       pfounder_reg_region,
       pfounder_reg_sity,
       pfounder_reg_street,
       pfounder_reg_house,
       pfounder_reg_office,
       pfounder_reg_postcode,
       pfounder_seat_counrycode,
       pfounder_seat_area,
       pfounder_seat_region,
       pfounder_seat_sity,
       pfounder_seat_street,
       pfounder_seat_house,
       pfounder_seat_office,
       pfounder_seat_postcode,
       pfounder_ur_name,
       pfounder_ur_residence,
       pfounder_ur_residence_c_code,
       pfounder_ur_reg_whom,
       pfounder_ur_reg_number,
       pfounder_ur_reg_date,
       pfounder_ur_taxcode_,
       pfounder_ac_secondname,
       pfounder_ac_firstname,
       pfounder_ac_middlename,
       pfounder_ac_birth_date,
       pfounder_ac_reg_number,
       pfounder_ac_reg_series,
       pfounder_ac_reg_whom,
       pfounder_ac_reg_date,
       pfounder_ur_opf_code)
    returning founder_id into pfounder_id;
    commit;
    return result;
  end;

  function SetMessageMemberAccounts(plogid         number,
                                    pmember_id     number,
                                    paccountnumber varchar2,
                                    pbankname      varchar2,
                                    pbankcode      varchar2,
                                    pbankaddress   varchar2,
                                    paccount_id    out number) return number is
    result number default 0;
    vcount number default 0;
    pragma autonomous_transaction;
  begin
    select count(*)
    into vcount
    from imp_audit
    where logid = plogid;
    if vcount = 0 then
      commit;
      return - 8031;
    end if;
    select nvl(max(ifnd.accountid), 0) + 1
    into paccount_id
    from imp_accounts ifnd
    where ifnd.log_id = plogid
    and ifnd.memberid = pmember_id;
    insert into imp_accounts
      (log_id,
       memberid,
       accountid,
       accountnumber,
       bankname,
       bankcode,
       bankaddress)
    values
      (plogid,
       pmember_id,
       paccount_id,
       paccountnumber,
       pbankname,
       pbankcode,
       pbankaddress);
    commit;
    return result;
  end;

  function LoadMessageInfo(plogid       number,
                           pMessInfoCur out sys_refcursor) return number is
    result number default 0;
  begin
    open pMessInfoCur for
      select mess_oper_status,
             mess_reason_code,
             mess_suspic_code,
             oper_number,
             oper_idview,
             oper_idtype,
             oper_members_count,
             oper_currency_code,
             oper_currency_amount,
             oper_tenge_amount,
             oper_reason,
             oper_doc_date,
             oper_doc_number,
             oper_susp_first,
             oper_susp_second,
             oper_susp_third,
             oper_difficulties,
             oper_dopinfo,
             oper_merch_types,
             oper_merch_reginfo,
             oper_refers_count
      from imp_messinfo
      where log_id = plogid;
    return result;
  end;
  function LoadMessageMembers(plogid      number,
                              pMembersCur out sys_refcursor) return number is
    result number default 0;
  begin
    open pMembersCur for
      select member_id,
             member_kind,
             member_role,
             member_residence,
             member_residence_countrycode,
             member_type,
             member_foreign,
             member_foreign_add,
             member_bank_code,
             member_bank_city,
             member_bank_name,
             member_bank_account,
             member_bank_address,
             MEMBER_BANK_OFFSHORE_ADDR,
             member_taxcode,
             member_okpo,
             member_oked,
             member_maincode,
             member_phone,
             member_email,
             member_reg_counrycode,
             member_reg_area,
             member_reg_region,
             member_reg_sity,
             member_reg_street,
             member_reg_house,
             member_reg_office,
             member_reg_postcode,
             member_seat_counrycode,
             member_seat_area,
             member_seat_region,
             member_seat_sity,
             member_seat_street,
             member_seat_house,
             member_seat_office,
             member_seat_postcode,
             member_comments,
             member_ur_name,
             member_ur_fisthead_name,
             member_ac_secondname,
             member_ac_firstname,
             member_ac_middlename,
             member_ac_doc_typecode,
             member_ac_doc_number,
             member_ac_doc_series,
             member_ac_doc_whom,
             member_ac_doc_date,
             member_ac_birth_date,
             member_ac_birth_place,
             money_trans_sys
      from imp_members
      where log_id = plogid;

    return result;
  end;

  function LoadMessageFounders(plogid       in number,
                               pmember_id   number,
                               pFoundersCur out sys_refcursor) return number is
    result number default 0;
  begin
    open pFoundersCur for
      select founder_id,
             founder_type,
             founder_maincode,
             founder_reg_counrycode,
             founder_reg_area,
             founder_reg_region,
             founder_reg_sity,
             founder_reg_street,
             founder_reg_house,
             founder_reg_office,
             founder_reg_postcode,
             founder_seat_counrycode,
             founder_seat_area,
             founder_seat_region,
             founder_seat_sity,
             founder_seat_street,
             founder_seat_house,
             founder_seat_office,
             founder_seat_postcode,
             founder_ur_name,
             founder_ur_residence,
             founder_ur_residence_c_code,
             founder_ur_reg_whom,
             founder_ur_reg_number,
             founder_ur_reg_date,
             founder_ur_taxcode,
             founder_ac_secondname,
             founder_ac_firstname,
             founder_ac_middlename,
             founder_ac_birth_date,
             founder_ac_reg_number,
             founder_ac_reg_series,
             founder_ac_reg_whom,
             founder_ac_reg_date
      from imp_found
      where log_id = plogid
      and member_id = pmember_id;

    return result;
  end;

  function CompleteLoading(plogid  number,
                           pmessid number) return number is
    result number default 0;
  begin
    insert into imp_audit
      (logid,
       messid,
       ploading_finish)
    values
      (plogid,
       pmessid,
       sysdate);
    return result;
  end;
  /*
  function GetReadyForLoading(pstartdate date, pfinishdate date); */

  function GetFoundersXML(plogid    number,
                          pmemberid number) return CLOB is
    lRes xmltype;
  begin
    SELECT XMLElement("FoundersList", NULL)
    INTO lRes
    from dual;

    SELECT XMLElement("FoundersList", XMLAgg(XMLtype(GetFounderInfoXml(plogid, imf.founder_type, imf.member_id, imf.founder_id))))
    INTO lRes
    from imp_found imf
    where imf.log_id = plogid
    and imf.member_id = pmemberid
    order by imf.founder_id;

    return lRes.getclobval();
  exception
    when no_data_found then
      return lRes.getclobval();
  end;

  function GetEmptyTag(ptype number) return clob is
    lRes xmltype;
  begin
    if ptype = 2 then
      --физик
      select XMLElement("AdditionalInformationAc",
                        XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                        XMLElement("URAddress",
                                   XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil")),
                                   XMLElement("Area", null),
                                   XMLElement("District", null),
                                   XMLElement("Town", null),
                                   XMLElement("Street", null),
                                   XMLElement("HomeNumber", null),
                                   XMLElement("OfficeNumber", null),
                                   XMLElement("PostalCode", null),
                                   XMLElement("AddressNotStruct", null)

                                   ),
                        XMLElement("ACAddress",
                                   XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil")),
                                   XMLElement("Area", null),
                                   XMLElement("District", null),
                                   XMLElement("Town", null),
                                   XMLElement("Street", null),
                                   XMLElement("HomeNumber", null),
                                   XMLElement("OfficeNumber", null),
                                   XMLElement("PostalCode", null),
                                   XMLElement("AddressNotStruct", null)),
                        XMLElement("FirstName", null),
                        XMLElement("SecondName", null),
                        XMLElement("MiddleName", null),
                        XMLElement("PlaceBirdth", null),
                        XMLElement("DateBirdth", XMLATTRIBUTES('true' as "xsi:nil")),
                        XMLElement("DocumentIdentity", XMLATTRIBUTES('true' as "xsi:nil")),
                        XMLElement("SeriesDocIdentity", null),
                        XMLElement("NumberDocIdentity", null),
                        XMLElement("IssuedDocument", null),
                        XMLElement("DateIssuance", XMLATTRIBUTES('true' as "xsi:nil"))

                        )
      into lRes
      from dual;

    elsif ptype = 3 then
      --ИП
      select XMLElement("AdditionalInformationIp",
                        XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                        XMLElement("URAddress",
                                   XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil")),
                                   XMLElement("Area", null),
                                   XMLElement("District", null),
                                   XMLElement("Town", null),
                                   XMLElement("Street", null),
                                   XMLElement("HomeNumber", null),
                                   XMLElement("OfficeNumber", null),
                                   XMLElement("PostalCode", null),
                                   XMLElement("AddressNotStruct", null)

                                   ),
                        XMLElement("ACAddress",
                                   XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil")),
                                   XMLElement("Area", null),
                                   XMLElement("District", null),
                                   XMLElement("Town", null),
                                   XMLElement("Street", null),
                                   XMLElement("HomeNumber", null),
                                   XMLElement("OfficeNumber", null),
                                   XMLElement("PostalCode", null),
                                   XMLElement("AddressNotStruct", null)),
                        XMLElement("FirstName", null),
                        XMLElement("SecondName", null),
                        XMLElement("MiddleName", null),
                        XMLElement("PlaceBirdth", null),
                        XMLElement("DateBirdth", XMLATTRIBUTES('true' as "xsi:nil")),
                        XMLElement("DocumentIdentity", XMLATTRIBUTES('true' as "xsi:nil")),
                        XMLElement("SeriesDocIdentity", null),
                        XMLElement("NumberDocIdentity", null),
                        XMLElement("IssuedDocument", null),
                        XMLElement("DateIssuance", XMLATTRIBUTES('true' as "xsi:nil"))

                        )
      into lRes
      from dual;
    elsif ptype = 1 then
      --юр
      select XMLElement("AdditionalInformationUr",
                        XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                        XMLElement("URAddress",
                                   XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil")),
                                   XMLElement("Area", null),
                                   XMLElement("District", null),
                                   XMLElement("Town", null),
                                   XMLElement("Street", null),
                                   XMLElement("HomeNumber", null),
                                   XMLElement("OfficeNumber", null),
                                   XMLElement("PostalCode", null),
                                   XMLElement("AddressNotStruct", null)),
                        XMLElement("ACAddress",
                                   XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil")),
                                   XMLElement("Area", null),
                                   XMLElement("District", null),
                                   XMLElement("Town", null),
                                   XMLElement("Street", null),
                                   XMLElement("HomeNumber", null),
                                   XMLElement("OfficeNumber", null),
                                   XMLElement("PostalCode", null),
                                   XMLElement("AddressNotStruct", null)),
                        XMLElement("FullName", null),
                        XMLElement("FirstHead", null))

      into lRes
      from dual;
    elsif ptype = 4 then
      -- учредитель  - юрик
      select XMLElement("founderUR",
                        XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                        XMLElement("URAddress",
                                   XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil")),
                                   XMLElement("Area", null),
                                   XMLElement("District", null),
                                   XMLElement("Town", null),
                                   XMLElement("Street", null),
                                   XMLElement("HomeNumber", null),
                                   XMLElement("OfficeNumber", null),
                                   XMLElement("PostalCode", null)),
                        XMLElement("ACAddress",
                                   XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil")),
                                   XMLElement("Area", null),
                                   XMLElement("District", null),
                                   XMLElement("Town", null),
                                   XMLElement("Street", null),
                                   XMLElement("HomeNumber", null),
                                   XMLElement("OfficeNumber", null),
                                   XMLElement("PostalCode", null)

                                   ),
                        XMLElement("FounderName", null),
                        XMLElement("Residence", 'false'),
                        XMLElement("ResidenceSity", XMLATTRIBUTES('true' as "xsi:nil")),
                        XMLElement("Authority", null),
                        XMLElement("RegistrationDate", XMLATTRIBUTES('true' as "xsi:nil")),
                        XMLElement("RegistrationNumber", null),
                        XMLElement("BIN", null),
                        XMLElement("RNN", null))

      into lRes
      from dual;
      null;
    elsif ptype = 5 then
      -- учредитель - физик
      select XMLElement("FounderAC",
                        XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                        XMLElement("URAddress",
                                   XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil")),
                                   XMLElement("Area", null),
                                   XMLElement("District", null),
                                   XMLElement("Town", null),
                                   XMLElement("Street", null),
                                   XMLElement("HomeNumber", null),
                                   XMLElement("OfficeNumber", null),
                                   XMLElement("PostalCode", null)

                                   ),
                        XMLElement("ACAddress",
                                   XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil")),
                                   XMLElement("Area", null),
                                   XMLElement("District", null),
                                   XMLElement("Town", null),
                                   XMLElement("Street", null),
                                   XMLElement("HomeNumber", null),
                                   XMLElement("OfficeNumber", null),
                                   XMLElement("PostalCode", null)

                                   ),
                        XMLElement("FirstName", null),
                        XMLElement("SecondName", null),
                        XMLElement("MiddleName", null),
                        XMLElement("DateBirdth", XMLATTRIBUTES('true' as "xsi:nil")),
                        XMLElement("PassportSeries", null),
                        XMLElement("PassportNumber", null),
                        XMLElement("IssuedDocument", null),
                        XMLElement("DateIssuance", XMLATTRIBUTES('true' as "xsi:nil")),
                        XMLElement("IIN", null))

      INTO lRes
      from dual;
    end if;

    return lRes.getclobval();
  end;
  function GetFounderInfoXML(plogid       number,
                             pfoundertype number,
                             pmemberid    number,
                             pfounderid   number) return clob is
    lRes xmltype;
  begin
    SELECT XMLElement("Founder", NULL)
    INTO lRes
    from dual;

    case pfoundertype
      when 1 then
        select XMLElement("Founder",
                          XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                          XMLElement("PersonType", decode(imf.founder_type, 1, 2, 2, 1)),
                          xmltype(GetEmptyTag(5)),
                          XMLElement("founderUR",
                                     XMLElement("URAddress",
                                                nvl2(imf.founder_reg_counrycode, XMLElement("Country", imf.founder_reg_counrycode), XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil"))),
                                                XMLElement("Area", imf.founder_reg_area),
                                                XMLElement("District", imf.founder_reg_region),
                                                XMLElement("Town", imf.founder_reg_sity),
                                                XMLElement("Street", imf.founder_reg_street),
                                                XMLElement("HomeNumber", imf.founder_reg_house),
                                                XMLElement("OfficeNumber", imf.founder_reg_office),
                                                XMLElement("PostalCode", imf.founder_reg_postcode)

                                                ),
                                     XMLElement("ACAddress",
                                                nvl2(imf.founder_seat_counrycode, XMLElement("Country", imf.founder_seat_counrycode), XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil"))),
                                                XMLElement("Area", imf.founder_seat_area),
                                                XMLElement("District", imf.founder_seat_region),
                                                XMLElement("Town", imf.founder_seat_sity),
                                                XMLElement("Street", imf.founder_seat_street),
                                                XMLElement("HomeNumber", imf.founder_seat_house),
                                                XMLElement("OfficeNumber", imf.founder_seat_office),
                                                XMLElement("PostalCode", imf.founder_seat_postcode)

                                                ),
                                     XMLElement("FounderName", imf.founder_ur_name),
                                     nvl2(imf.founder_ur_residence, XMLElement("Residence", decode(imf.founder_ur_residence, 0, 'false', 1, 'true')), XMLElement("Residence", XMLATTRIBUTES('true' as "xsi:nil"))),
                                     nvl2(imf.founder_ur_residence_c_code, XMLElement("ResidenceSity", imf.founder_ur_residence_c_code), XMLElement("ResidenceSity", XMLATTRIBUTES('true' as "xsi:nil"))),
                                     XMLElement("Authority", imf.founder_ur_reg_whom),
                                     nvl2(imf.founder_ur_reg_date, XMLElement("RegistrationDate", to_char(imf.founder_ur_reg_date, 'yyyy-mm-dd')), XMLElement("RegistrationDate", XMLATTRIBUTES('true' as "xsi:nil"))),
                                     XMLElement("RegistrationNumber", imf.founder_ur_reg_number),
                                     XMLElement("BIN", imf.founder_maincode),
                                     XMLElement("RNN", imf.founder_ur_taxcode)

                                     ))
        into lRes
        from imp_found imf
        where imf.log_id = plogid
        and imf.member_id = pmemberid
        and imf.founder_id = pfounderid;
      when 2 then
        select XMLElement("Founder",
                          XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                          XMLElement("PersonType", decode(imf.founder_type, 1, 2, 2, 1)),

                          XMLElement("FounderAC",
                                     XMLElement("URAddress",
                                                nvl2(imf.founder_reg_counrycode, XMLElement("Country", imf.founder_reg_counrycode), XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil"))),
                                                XMLElement("Area", imf.founder_reg_area),
                                                XMLElement("District", imf.founder_reg_region),
                                                XMLElement("Town", imf.founder_reg_sity),
                                                XMLElement("Street", imf.founder_reg_street),
                                                XMLElement("HomeNumber", imf.founder_reg_house),
                                                XMLElement("OfficeNumber", imf.founder_reg_office),
                                                XMLElement("PostalCode", imf.founder_reg_postcode)

                                                ),
                                     XMLElement("ACAddress",
                                                nvl2(imf.founder_seat_counrycode, XMLElement("Country", imf.founder_seat_counrycode), XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil"))),
                                                XMLElement("Area", imf.founder_seat_area),
                                                XMLElement("District", imf.founder_seat_region),
                                                XMLElement("Town", imf.founder_seat_sity),
                                                XMLElement("Street", imf.founder_seat_street),
                                                XMLElement("HomeNumber", imf.founder_seat_house),
                                                XMLElement("OfficeNumber", imf.founder_seat_office),
                                                XMLElement("PostalCode", imf.founder_seat_postcode)

                                                ),
                                     XMLElement("FirstName", imf.founder_ac_secondname),
                                     XMLElement("SecondName", imf.founder_ac_firstname),
                                     XMLElement("MiddleName", imf.founder_ac_middlename),
                                     nvl2(imf.founder_ac_birth_date, XMLElement("DateBirdth", to_char(imf.founder_ac_birth_date, 'yyyy-mm-dd')), XMLElement("DateBirdth", XMLATTRIBUTES('true' as "xsi:nil"))),
                                     XMLElement("PassportSeries", imf.founder_ac_reg_series),
                                     XMLElement("PassportNumber", imf.founder_ac_reg_number),
                                     XMLElement("IssuedDocument", imf.founder_ac_reg_whom),
                                     nvl2(imf.founder_ac_reg_date, XMLElement("DateIssuance", to_char(imf.founder_ac_reg_date, 'yyyy-mm-dd')), XMLElement("DateIssuance", XMLATTRIBUTES('true' as "xsi:nil"))),
                                     XMLElement("IIN", imf.founder_maincode)),
                          xmltype(GetEmptyTag(4)))

        into lRes
        from imp_found imf
        where imf.log_id = plogid
        and imf.member_id = pmemberid
        and imf.founder_id = pfounderid;
    end case;
    return lRes.getclobval();
  exception
    when others then
      return lRes.getclobval();
  end;
  function GetAdditionalInfoXML(plogid      number,
                                pmembertype number,
                                pmemberid   number) return clob is
    lRes xmltype;
  begin
    SELECT XMLElement("AdditionalPersonInfo", NULL)
    INTO lRes
    from dual;

    case pmembertype
      when 1 then
        SELECT XMLElement("AdditionalPersonInfo",
                          XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                          XMLElement("PersonType", 2),
                          --Ac
                          xmltype(GetEmptyTag(2)),
                          --Ip
                          xmltype(GetEmptyTag(3)),
                          --Ur

                          XMLElement("AdditionalInformationUr",
                                     XMLElement("URAddress",
                                                nvl2(member_reg_counrycode, XMLElement("Country", member_reg_counrycode), XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil"))),
                                                XMLElement("Area", member_reg_area),
                                                XMLElement("District", member_reg_region),
                                                XMLElement("Town", member_reg_sity),
                                                XMLElement("Street", member_reg_street),
                                                XMLElement("HomeNumber", member_reg_house),
                                                XMLElement("OfficeNumber", member_reg_office),
                                                XMLElement("PostalCode", member_reg_postcode),
                                                XMLElement("AddressNotStruct", null)

                                                ),
                                     XMLElement("ACAddress",
                                                nvl2(member_seat_counrycode, XMLElement("Country", member_seat_counrycode), XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil"))),
                                                XMLElement("Area", member_seat_area),
                                                XMLElement("District", member_seat_region),
                                                XMLElement("Town", member_seat_sity),
                                                XMLElement("Street", member_seat_street),
                                                XMLElement("HomeNumber", member_seat_house),
                                                XMLElement("OfficeNumber", member_seat_office),
                                                XMLElement("PostalCode", member_seat_postcode),
                                                XMLElement("AddressNotStruct", null)

                                                ),
                                     XMLForest(member_ur_name as "FullName",
                                               member_ur_fisthead_name as "FirstHead"

                                               )))
        into lRes
        from imp_members imm
        where imm.log_id = plogid
        and imm.member_id = pmemberid
        order by imm.member_id;
      when 2 then
        SELECT XMLElement("AdditionalPersonInfo",
                          XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                          XMLElement("PersonType", 1),
                          XMLElement("AdditionalInformationAc",
                                     XMLElement("URAddress",
                                                nvl2(member_reg_counrycode, XMLElement("Country", member_reg_counrycode), XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil"))),
                                                XMLElement("Area", member_reg_area),
                                                XMLElement("District", member_reg_region),
                                                XMLElement("Town", member_reg_sity),
                                                XMLElement("Street", member_reg_street),
                                                XMLElement("HomeNumber", member_reg_house),
                                                XMLElement("OfficeNumber", member_reg_office),
                                                XMLElement("PostalCode", member_reg_postcode),
                                                XMLElement("AddressNotStruct", null)),
                                     XMLElement("ACAddress",
                                                nvl2(member_seat_counrycode, XMLElement("Country", member_seat_counrycode), XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil"))),
                                                XMLElement("Area", member_seat_area),
                                                XMLElement("District", member_seat_region),
                                                XMLElement("Town", member_seat_sity),
                                                XMLElement("Street", member_seat_street),
                                                XMLElement("HomeNumber", member_seat_house),
                                                XMLElement("OfficeNumber", member_seat_office),
                                                XMLElement("PostalCode", member_seat_postcode),
                                                XMLElement("AddressNotStruct", null)),
                                     XMLElement("FirstName", member_ac_secondname),
                                     XMLElement("SecondName", member_ac_firstname),
                                     XMLElement("MiddleName", member_ac_middlename),
                                     XMLElement("PlaceBirdth", member_ac_birth_place),
                                     nvl2(member_ac_birth_date, XMLElement("DateBirdth", to_char(member_ac_birth_date, 'yyyy-mm-dd')), XMLElement("DateBirdth", XMLATTRIBUTES('true' as "xsi:nil"))),
                                     nvl2(member_ac_doc_typecode, XMLElement("DocumentIdentity", member_ac_doc_typecode), XMLElement("DocumentIdentity", XMLATTRIBUTES('true' as "xsi:nil"))),
                                     XMLElement("SeriesDocIdentity", member_ac_doc_series),
                                     XMLElement("NumberDocIdentity", member_ac_doc_number),
                                     XMLElement("IssuedDocument", member_ac_doc_whom),
                                     nvl2(member_ac_doc_date, XMLElement("DateIssuance", to_char(member_ac_doc_date, 'yyyy-mm-dd')), XMLElement("DateIssuance", XMLATTRIBUTES('true' as "xsi:nil")))),
                          --Ip
                          xmltype(GetEmptyTag(3)),
                          --Ur
                          xmltype(GetEmptyTag(1)))
        into lRes
        from imp_members imm
        where imm.log_id = plogid
        and imm.member_id = pmemberid
        order by imm.member_id;
      when 3 then
        SELECT XMLElement("AdditionalPersonInfo",
                          XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                          XMLElement("PersonType", 3),
                          xmltype(GetEmptyTag(2)),
                          --Ip
                          XMLElement("AdditionalInformationIp",
                                     XMLElement("URAddress",
                                                nvl2(member_reg_counrycode, XMLElement("Country", member_reg_counrycode), XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil"))),
                                                XMLElement("Area", member_reg_area),
                                                XMLElement("District", member_reg_region),
                                                XMLElement("Town", member_reg_sity),
                                                XMLElement("Street", member_reg_street),
                                                XMLElement("HomeNumber", member_reg_house),
                                                XMLElement("OfficeNumber", member_reg_office),
                                                XMLElement("PostalCode", member_reg_postcode),
                                                XMLElement("AddressNotStruct", null)),
                                     XMLElement("ACAddress",
                                                nvl2(member_seat_counrycode, XMLElement("Country", member_seat_counrycode), XMLElement("Country", XMLATTRIBUTES('true' as "xsi:nil"))),
                                                XMLElement("Area", member_seat_area),
                                                XMLElement("District", member_seat_region),
                                                XMLElement("Town", member_seat_sity),
                                                XMLElement("Street", member_seat_street),
                                                XMLElement("HomeNumber", member_seat_house),
                                                XMLElement("OfficeNumber", member_seat_office),
                                                XMLElement("PostalCode", member_seat_postcode),
                                                XMLElement("AddressNotStruct", null)),
                                     XMLElement("FirstName", member_ac_secondname),
                                     XMLElement("SecondName", member_ac_firstname),
                                     XMLElement("MiddleName", member_ac_middlename),
                                     XMLElement("PlaceBirdth", member_ac_birth_place),
                                     nvl2(member_ac_birth_date, XMLElement("DateBirdth", to_char(member_ac_birth_date, 'yyyy-mm-dd')), XMLElement("DateBirdth", XMLATTRIBUTES('true' as "xsi:nil"))),
                                     nvl2(member_ac_doc_typecode, XMLElement("DocumentIdentity", member_ac_doc_typecode), XMLElement("DocumentIdentity", XMLATTRIBUTES('true' as "xsi:nil"))),
                                     XMLElement("SeriesDocIdentity", member_ac_doc_series),
                                     XMLElement("NumberDocIdentity", member_ac_doc_number),
                                     XMLElement("IssuedDocument", member_ac_doc_whom),
                                     nvl2(member_ac_doc_date, XMLElement("DateIssuance", to_char(member_ac_doc_date, 'yyyy-mm-dd')), XMLElement("DateIssuance", XMLATTRIBUTES('true' as "xsi:nil")))),

                          --Ur
                          xmltype(GetEmptyTag(1)))
        into lRes
        from imp_members imm
        where imm.log_id = plogid
        and imm.member_id = pmemberid
        order by imm.member_id;
      else
        SELECT XMLElement("AdditionalPersonInfo", XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"), XMLElement("PersonType", 0), xmltype(GetEmptyTag(2)), xmltype(GetEmptyTag(3)), xmltype(GetEmptyTag(1)))
        into lRes
        from dual;
        --Ip

    end case;

    return lRes.getclobval();
  exception
    when others then
      return lRes.getclobval();
  end;

  function GetMembersXML(plogid number) return CLOB is
    lRes xmltype;
  begin
    SELECT XMLElement("ParticipantsList", NULL)
    INTO lRes
    from dual;

    SELECT XMLElement("ParticipantsList",
                      XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                      XMLAgg(XMLElement("Participant",
                                        nvl2(imm.MEMBER_ROLE, XMLElement("ParticipantOperation", imm.MEMBER_ROLE), XMLElement("ParticipantOperation", XMLATTRIBUTES('true' as "xsi:nil"))),
                                        nvl2(imm.MEMBER_KIND, XMLElement("ParticipantsView", imm.MEMBER_KIND), XMLElement("ParticipantsView", XMLATTRIBUTES('true' as "xsi:nil"))),
                                        nvl2(imm.member_type, XMLElement("ParticipantsType", imm.member_type), XMLElement("ParticipantsType", XMLATTRIBUTES('true' as "xsi:nil"))),
                                        XMLElement("OKED", imm.member_oked),
                                        nvl2(imm.member_foreign, XMLElement("ForeignPerson", imm.member_foreign), XMLElement("ForeignPerson", XMLATTRIBUTES('true' as "xsi:nil"))),
                                        nvl2(imm.member_residence, XMLElement("MemberCommunity", decode(imm.member_residence, 0, 'false', 1, 'true')), XMLElement("MemberCommunity", XMLATTRIBUTES('true' as "xsi:nil"))),
                                        nvl2(imm.member_residence_countrycode, XMLElement("MemberCommunitySityCode", imm.member_residence_countrycode), XMLElement("MemberCommunitySityCode", XMLATTRIBUTES('true' as "xsi:nil"))),
                                        XMLElement("ForeignAdditionalField", imm.member_foreign_add),
                                        XMLElement("RNN", imm.member_taxcode),
                                        XMLElement("Email", imm.MEMBER_EMAIL),
                                        XMLElement("OKPO", imm.member_okpo),
                                        XMLElement("IndividualIssue", imm.Member_MainCode),
                                        XMLElement("PhoneNumber", imm.MEMBER_PHONE),
                                        XMLElement("BankCode", imm.member_bank_code),
                                        XMLElement("BankCity", imm.member_bank_city),
                    XMLElement("BankOffshoreAddr", imm.MEMBER_BANK_OFFSHORE_ADDR),
                                        XMLElement("CorrespondentBankName", imm.member_bank_name),
                                        XMLElement("CorrespondentBankAccountNumber", imm.member_bank_account),
                                        XMLElement("CorrespondentBankAddress", imm.member_bank_address),
                                        XMLElement("AdditionalInformation", imm.MEMBER_COMMENTS),
                                        XMLElement("MoneyTransSys", imm.money_trans_sys),
                                        xmltype(GetFoundersXML(plogid, imm.member_id)),
                                        xmltype(GetAdditionalInfoXML(plogid, imm.member_type, imm.member_id)))))

    INTO lRes
    from imp_members imm
    where imm.log_id = plogid
    order by imm.member_id;

    return lRes.getclobval();
  end;

  function GetMessInfoXML(plogid number) return CLOB is
    lRes xmltype;
  begin
    select XMLElement("MessageInformation", NULL)
    INTO lRes
    from dual;

    select XMLElement("MessageInformation",
                      XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),

                      XMLElement("ReportsType", 1),
                      XMLElement("MessageNumber", pkg_messages_cfm.GenerateMessageNumber),
                      XMLElement("LastModifyDate", TO_CHAR(sysdate(), 'yyyy-mm-dd')),
                      nvl2(oper_idview, XMLElement("IDViewOperation", oper_idview), XMLElement("IDViewOperation", XMLATTRIBUTES('true' as "xsi:nil"))),
                      nvl2(oper_idtype, XMLElement("IDTypeOperation", oper_idtype), XMLElement("IDTypeOperation", XMLATTRIBUTES('true' as "xsi:nil"))),
                      XMLElement("OperationNumber", oper_number),
                      XMLElement("DocOperationName", oper_reason),
                      nvl2(oper_doc_date, XMLElement("DocOperationDate", to_char(oper_doc_date, 'yyyy-mm-dd')), XMLElement("DocOperationDate", XMLATTRIBUTES('true' as "xsi:nil"))),
                      XMLElement("DocOperationNumber", oper_doc_number),
                      nvl2(oper_currency_code, XMLElement("CurrencyCode", oper_currency_code), XMLElement("CurrencyCode", XMLATTRIBUTES('true' as "xsi:nil"))),
                      XMLElement("AmountCurrency", oper_currency_amount),
                      XMLElement("AmountCurrencyTenge", oper_tenge_amount),
                      nvl2(mess_oper_status, XMLElement("OperationStatuses", mess_oper_status), XMLElement("OperationStatuses", XMLATTRIBUTES('true' as "xsi:nil"))),
                      nvl2(MESS_REASON_CODE, XMLElement("SubmissionsBasises", MESS_REASON_CODE), XMLElement("SubmissionsBasises", XMLATTRIBUTES('true' as "xsi:nil"))),
                      nvl2(MESS_SUSPIC_CODE, XMLElement("SuspicionsCriterians", MESS_SUSPIC_CODE), XMLElement("SuspicionsCriterians", XMLATTRIBUTES('true' as "xsi:nil"))),
                      nvl2(oper_susp_first, XMLElement("SuspicionFirst", oper_susp_first), XMLElement("SuspicionFirst", XMLATTRIBUTES('true' as "xsi:nil"))),
                      nvl2(oper_susp_second, XMLElement("SuspicionSecond", oper_susp_second), XMLElement("SuspicionSecond", XMLATTRIBUTES('true' as "xsi:nil"))),
                      nvl2(oper_susp_third, XMLElement("SuspicionThird", oper_susp_third), XMLElement("SuspicionThird", XMLATTRIBUTES('true' as "xsi:nil"))),
                      XMLElement("DescriptionDifficulties", OPER_DIFFICULTIES),
                      XMLElement("MoreInformation", OPER_DOPINFO),
                      XMLElement("ParticipantCount", oper_members_count),
                      XMLElement("MerchTypes", imi.oper_merch_types),
                      XMLElement("MerchReginfo", imi.oper_merch_reginfo),
                      XMLElement("ReferCount", imi.oper_refers_count))

    INTO lRes
    from imp_messinfo imi
    where imi.log_id = plogid;

    return lRes.getclobval();
  exception
    when others then
      return lRes.getclobval();
  end;
  --
  function refers_2_xml(p_log_id in NUMBER) return xmltype as
    v_result xmltype;
  begin
    v_result := null;

    SELECT XMLElement("References",
                      XMLAgg(XMLElement("Reference",
                                        XMLElement("ReferenceId", ta.referid),
                                        XMLElement("ReferenceOperationNumber", ta.refer_doc_oper),
                                        XMLElement("ReferenceDocOperationDate", to_char(ta.refer_doc_date, 'dd.mm.yyyy')),
                                        XMLElement("ReferencerDocOperationNumber", ta.refer_doc_num)))) AS xmltype
    INTO v_result
    FROM imp_refer ta
    WHERE ta.log_id = p_log_id;

    return v_result;
  end;
  --
  function CreateImportXML(plogid number) return CLOB is
    result CLOB;
    lRes   xmltype;
    lXML   xmltype;

    lPersonalData CLOB;
    lMessInfo     CLOB;
    lMembers      CLOB;
  begin
    lMessInfo := GetMessInfoXML(plogid);
    lMembers  := GetMembersXML(plogid);
    select

     XMLElement("Root",
                XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi", 'http://www.w3.org/2001/XMLSchema' as "xmlns:xsd"),
                pkg_rqst_cfm.rqst_personal_data,
                XMLType(lMessInfo),
                refers_2_xml(plogid),
                XMLType(lMembers),
                XMLElement("Version", '52FF370C-8B35-42da-9B9A-B48F44F10C6F'),
                XMLElement("DocumentUniqueIdentifier", sys_guid()))

    INTO lRes
    from dual;

    lXML   := SYS.XMLType.CreateXML('<?xml version="1.0" encoding="windows-1251"?>' || lRes.getclobval());
    Result := lXML.getclobval();
    return Result;
  end;

  function GetMessInfoXML_2(plogid number) return CLOB is
    lRes xmltype;
  begin
    select XMLElement("MessageInformation", NULL)
    INTO lRes
    from dual;

    select XMLElement("MessageInformation",
                      XMLElement("DocumentType", 1),
                      XMLElement("MessageNumber", pkg_messages_cfm.GenerateMessageNumber),
                      XMLElement("LastModifyDate", TO_CHAR(sysdate(), 'dd.mm.yyyy')),
                      XMLElement("TransactionDate", TO_CHAR(nvl(Oper_Trans_Date, mess_Trans_Date), 'dd.mm.yyyy hh24:mi:ss')),
                      XMLElement("MessTransDate", TO_CHAR(nvl(Oper_Trans_Date, mess_Trans_Date), 'dd.mm.yyyy hh24:mi:ss')),
                      XMLElement("ViewOperationId", oper_idview),
                      XMLElement("EknpId", XMLATTRIBUTES(pkg_common.GetBool(oper_isnotidtyped) as "IsEknpNotSetup"), oper_idtype),
                      XMLElement("OperationNumber", oper_number),
                      XMLElement("DocOperationReason", oper_reason),
                      XMLElement("DocOperationDate", to_char(oper_doc_date, 'dd.mm.yyyy')),
                      XMLElement("DocOperationNumber", oper_doc_number),
                      XMLElement("CurrencyCodeId", oper_currency_code),
                      XMLElement("AmountCurrency", oper_currency_amount),
                      XMLElement("AmountCurrencyTenge", oper_tenge_amount),
                      XMLElement("OperationStatusId", mess_oper_status),
                      XMLElement("ReasonFilingId", MESS_REASON_CODE),
                      XMLElement("SuspicionsCriterians", MESS_SUSPIC_CODE),
                      XMLElement("SuspicionFirst", oper_susp_first),
                      XMLElement("SuspicionSecond", oper_susp_second),
                      XMLElement("SuspicionThird", oper_susp_third),
                      XMLElement("DescriptionDifficulties", OPER_DIFFICULTIES),
                      XMLElement("MoreInformation", OPER_DOPINFO),
                      XMLElement("ParticipantCount", oper_members_count),
                      XMLElement("MerchTypes", imi.oper_merch_types),
                      XMLElement("MerchReginfo", imi.oper_merch_reginfo),
                      XMLElement("ReferCount", imi.oper_refers_count))

    INTO lRes
    from imp_messinfo imi
    where imi.log_id = plogid;

    return lRes.getclobval();
  exception
    when others then
      return lRes.getclobval();
  end;

  function GetAccountsXML_2(plogid    number,
                            pmemberid number) return CLOB is
    lRes xmltype;
  begin
    SELECT XMLElement("CorrespondentsInformations", NULL)
    INTO lRes
    from dual;

    SELECT XMLElement("CorrespondentsInformations",
                      XMLAgg(XMLElement("CorrespondentInformation",
                                        --          nvl2(imm.MEMBER_ROLE,XMLElement("ParticipantOperation",imm.MEMBER_ROLE),XMLElement("ParticipantOperation",XMLATTRIBUTES('true' as "xsi:nil"))),
                                        XMLElement("AccountNumber", iac.accountnumber),
                                        XMLElement("BankName", iac.bankname),
                                        XMLElement("BankCode", iac.bankcode),
                                        XMLElement("BankAddress", iac.bankaddress))) --CorrespondentBank
                      )
    INTO lRes
    from imp_accounts iac
    where iac.log_id = plogid
    and iac.memberid = pmemberid
    order by iac.accountid;

    return lRes.getclobval();
  end;
  function GetFounderInfoXML_2(plogid     number,
                               pmemberid  number,
                               pfounderid number) return clob is
    lRes xmltype;
  begin
    SELECT XMLElement("Founder", NULL)
    INTO lRes
    from dual;

    select XMLElement("Founder", XMLElement("Name", imf.founder_ur_name), XMLElement("MemberCommunityCityCode", founder_ur_residence_c_code))
    into lRes
    from imp_found imf
    where imf.log_id = plogid
    and imf.member_id = pmemberid
    and imf.founder_id = pfounderid;
    return lRes.getclobval();
  exception
    when others then
      return lRes.getclobval();
  end;

  function GetFoundersXML_2(plogid    number,
                            pmemberid number) return xmltype is
    lRes    CLOB;
    lResxml xmltype;
  begin
    SELECT empty_clob()
    INTO lRes
    from dual;

    SELECT

     XMLForest(XMLAgg(nvl2(GetFounderInfoXml_2(plogid, imf.member_id, imf.founder_id), xmltype(GetFounderInfoXml_2(plogid, imf.member_id, imf.founder_id)), null)) as "Founders").getclobval()
    INTO lRes
    from imp_found imf
    where imf.log_id = plogid
    and imf.member_id = pmemberid
    order by imf.founder_id;

    IF LRES IS NULL THEN

      lResxml := null;
    else
      lResxml := xmltype(lres);
    END IF;

    return lResxml;
  exception
    when no_data_found then
      return null;
  end;

  function GetAdditionalInfoXML_2(plogid      number,
                                  pmembertype number,
                                  pmemberid   number) return clob is
    lRes xmltype;
  begin
    SELECT XMLElement("AdditionalPersonInfo", NULL)
    INTO lRes
    from dual;

    case pmembertype
      when 1 then
        SELECT XMLElement("AdditionalPersonInfo",
                          XMLElement("PersonType", 1),

                          XMLElement("AdditionalInformationUr",
                                     XMLElement("URAddress",
                                                XMLElement("Country", member_reg_counrycode),
                                                XMLElement("Area", member_reg_area),
                                                XMLElement("District", member_reg_region),
                                                XMLElement("Town", member_reg_sity),
                                                XMLElement("Street", member_reg_street),
                                                XMLElement("HomeNumber", member_reg_house),
                                                XMLElement("OfficeNumber", member_reg_office)

                                                ),
                                     XMLElement("ACAddress",
                                                XMLElement("Country", member_seat_counrycode),
                                                XMLElement("Area", member_seat_area),
                                                XMLElement("District", member_seat_region),
                                                XMLElement("Town", member_seat_sity),
                                                XMLElement("Street", member_seat_street),
                                                XMLElement("HomeNumber", member_seat_house),
                                                XMLElement("OfficeNumber", member_seat_office)

                                                ),
                                     XMLElement("FullName", XMLATTRIBUTES(pkg_common.GetBool(member_isnotnamed) as "IsFullNameSetup"), member_ur_name),

                                     XMLElement("FirstHead", member_ur_fisthead_name)))
        into lRes
        from imp_members imm
        where imm.log_id = plogid
        and imm.member_id = pmemberid
        order by imm.member_id;
      when 2 then
        SELECT XMLElement("AdditionalPersonInfo",
                          XMLElement("PersonType", 2),
                          XMLElement("AdditionalInformationAc",
                                     XMLElement("URAddress",
                                                XMLElement("Country", member_reg_counrycode),
                                                XMLElement("Area", member_reg_area),
                                                XMLElement("District", member_reg_region),
                                                XMLElement("Town", member_reg_sity),
                                                XMLElement("Street", member_reg_street),
                                                XMLElement("HomeNumber", member_reg_house),
                                                XMLElement("OfficeNumber", member_reg_office)

                                                ),
                                     XMLElement("ACAddress",
                                                XMLElement("Country", member_seat_counrycode),
                                                XMLElement("Area", member_seat_area),
                                                XMLElement("District", member_seat_region),
                                                XMLElement("Town", member_seat_sity),
                                                XMLElement("Street", member_seat_street),
                                                XMLElement("HomeNumber", member_seat_house),
                                                XMLElement("OfficeNumber", member_seat_office)

                                                ),
                                     XMLElement("FIO", XMLATTRIBUTES(pkg_common.GetBool(member_isnotnamed) as "IsFioNotSetup"), member_ur_name),

                                     XMLElement("PlaceBirdth", member_ac_birth_place),
                                     XMLElement("DateBirdth", to_char(member_ac_birth_date, 'dd.mm.yyyy')),
                                     XMLElement("DocumentIdentity", member_ac_doc_typecode),
                                     XMLElement("SeriesDocIdentity", member_ac_doc_series),
                                     XMLElement("NumberDocIdentity", member_ac_doc_number),
                                     XMLElement("DocumentIssued", member_ac_doc_whom),
                                     XMLElement("DateIssuance", to_char(member_ac_doc_date, 'dd.mm.yyyy'))

                                     ))
        into lRes
        from imp_members imm
        where imm.log_id = plogid
        and imm.member_id = pmemberid
        order by imm.member_id;
      when 3 then
        SELECT XMLElement("AdditionalPersonInfo",
                          XMLElement("PersonType", 3),
                          XMLElement("AdditionalInformationIp",
                                     XMLElement("URAddress",
                                                XMLElement("Country", member_reg_counrycode),
                                                XMLElement("Area", member_reg_area),
                                                XMLElement("District", member_reg_region),
                                                XMLElement("Town", member_reg_sity),
                                                XMLElement("Street", member_reg_street),
                                                XMLElement("HomeNumber", member_reg_house),
                                                XMLElement("OfficeNumber", member_reg_office)

                                                ),
                                     XMLElement("ACAddress",
                                                XMLElement("Country", member_seat_counrycode),
                                                XMLElement("Area", member_seat_area),
                                                XMLElement("District", member_seat_region),
                                                XMLElement("Town", member_seat_sity),
                                                XMLElement("Street", member_seat_street),
                                                XMLElement("HomeNumber", member_seat_house),
                                                XMLElement("OfficeNumber", member_seat_office)

                                                ),
                                     XMLElement("FIO", XMLATTRIBUTES(pkg_common.GetBool(member_isnotnamed) as "IsFioNotSetup"), member_ur_name),

                                     XMLElement("PlaceBirdth", member_ac_birth_place),
                                     XMLElement("DateBirdth", to_char(member_ac_birth_date, 'dd.mm.yyyy')),
                                     XMLElement("DocumentIdentity", member_ac_doc_typecode),
                                     XMLElement("SeriesDocIdentity", member_ac_doc_series),
                                     XMLElement("NumberDocIdentity", member_ac_doc_number),
                                     XMLElement("DocumentIssued", member_ac_doc_whom),
                                     XMLElement("DateIssuance", to_char(member_ac_doc_date, 'dd.mm.yyyy'))

                                     ))

        into lRes
        from imp_members imm
        where imm.log_id = plogid
        and imm.member_id = pmemberid
        order by imm.member_id;
      else
        SELECT XMLElement("AdditionalPersonInfo", XMLElement("PersonType", 0))
        into lRes
        from dual;
        --Ip

    end case;

    return lRes.getclobval();
  exception
    when others then
      return lRes.getclobval();
  end;

  function GetMembersXML_2(plogid number) return CLOB is
    lRes xmltype;
  begin
    SELECT XMLElement("ParticipantsList", NULL)
    INTO lRes
    from dual;

    SELECT XMLElement("Participants",
                      XMLAgg(XMLElement("Participant",
                                        --          nvl2(imm.MEMBER_ROLE,XMLElement("ParticipantOperation",imm.MEMBER_ROLE),XMLElement("ParticipantOperation",XMLATTRIBUTES('true' as "xsi:nil"))),
                                        XMLElement("MemberId", imm.member_membercode),
                                        XMLElement("ParticipantsView", imm.MEMBER_KIND),
                                        XMLElement("ParticipantsType", imm.member_type),
                                        XMLElement("IsClientSubject", imm.member_isclient),
                                        XMLElement("MemberCommunityCityCode", member_residence_countrycode),
                                        XMLElement("ForeignPerson", imm.member_foreign),

                                        --CorrespondentBank
                                        XMLElement("CorrespondentBank",

                                                   XMLElement("AccountNumber", imm.member_bank_account),
                                                   XMLElement("Name", imm.member_bank_name),
                                                   XMLElement("Code", imm.member_bank_code),
                                                   XMLElement("BankCity", imm.member_bank_city),
                                                   XMLElement("BankAddress", imm.member_bank_address),
                           XMLElement("BankOffshoreAddr", imm.MEMBER_BANK_OFFSHORE_ADDR),
                                                   xmltype(GetAccountsXML_2(plogid, imm.member_id))

                                                   ),
                                        XMLElement("RNN", imm.member_taxcode),
                                        XMLElement("OKED", imm.member_oked),
                                        XMLElement("IndividualIssue", imm.Member_MainCode),
                                        XMLElement("PhoneNumber", imm.MEMBER_PHONE),
                                        XMLElement("Email", imm.MEMBER_EMAIL),
                                        XMLElement("AdditionalInformation", imm.MEMBER_COMMENTS),
                                        XMLElement("MoneyTransSys", imm.money_trans_sys),

                                        XMLForest(Extract(GetFoundersXML_2(plogid, imm.member_id), '/Founders/*') as "Founders"),

                                        xmltype(GetAdditionalInfoXML_2(plogid, imm.member_type, imm.member_id)))))
    INTO lRes
    from imp_members imm
    where imm.log_id = plogid
    order by imm.member_id;

    return lRes.getclobval();
  end;

  function CreateImportXML_2(plogid number) return CLOB is
    result CLOB;
    lRes   xmltype;
    lXML   xmltype;

    lMessInfo CLOB;
    lMembers  CLOB;
  begin
    lMessInfo := GetMessInfoXML_2(plogid);
    lMembers  := GetMembersXML_2(plogid);
    select

     XMLElement("Root",
                XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi", 'http://www.w3.org/2001/XMLSchema' as "xmlns:xsd"),
                pkg_rqst_cfm.rqst_personal_data,
                XMLType(lMessInfo),
                refers_2_xml(plogid),
                XMLType(lMembers),
                XMLElement("Version", 'E5505800-A19B-47ed-AF5F-9A8BAF169E52'),
                XMLElement("DocumentUniqueIdentifier", sys_guid()))

    INTO lRes
    from dual;

    lXML   := SYS.XMLType.CreateXML('<?xml version="1.0" encoding="windows-1251"?>' || lRes.getclobval());
    Result := lXML.getclobval();
    return Result;
  end;

  function GetAdditionalInfoXML_3(plogid      number,
                                  pmembertype number,
                                  pmemberid   number) return clob is
    lRes xmltype;

  begin

    SELECT XMLElement("AdditionalPersonInfo", NULL)
    INTO lRes
    from dual;
    case pmembertype
      when 1 then
        SELECT XMLElement("AdditionalPersonInfo",
                          XMLElement("PersonType", 1),
                          XMLElement("AdditionalInformationUr",

                                        XMLElement("URAddress",
                                                   XMLElement("Country", member_reg_counrycode),
                                                   XMLElement("Area", XMLATTRIBUTES(member_reg_area_code as "Code"), member_reg_area),
                                                   XMLElement("District", XMLATTRIBUTES(member_reg_region_code as "Code"), member_reg_region),
                                                   XMLElement("Town", XMLATTRIBUTES(member_reg_sity_code as "Code"), member_reg_sity),
                                                   XMLElement("Street", XMLATTRIBUTES(member_reg_street_code as "Code"), member_reg_street),
                                                   XMLElement("HomeNumber", XMLATTRIBUTES(member_reg_house_code as "Code"), member_reg_house),
                                                   XMLElement("OfficeNumber", XMLATTRIBUTES(member_reg_office_code as "Code"), member_reg_office)),

                                        XMLElement("ACAddress",
                                                   XMLElement("Country", member_seat_counrycode),
                                                   XMLElement("Area", XMLATTRIBUTES(member_seat_area_code as "Code"), member_seat_area),
                                                   XMLElement("District", XMLATTRIBUTES(member_seat_region_code as "Code"), member_seat_region),
                                                   XMLElement("Town", XMLATTRIBUTES(member_seat_sity_code as "Code"), member_seat_sity),
                                                   XMLElement("Street", XMLATTRIBUTES(member_seat_street_code as "Code"), member_seat_street),
                                                   XMLElement("HomeNumber", XMLATTRIBUTES(member_seat_house_code as "Code"), member_seat_house),
                                                   XMLElement("OfficeNumber", XMLATTRIBUTES(member_seat_office_code as "Code"), member_seat_office)),

                                     XMLElement("ParticipantOPF", imm.member_ur_opf_code),
                                     XMLElement("FullName", XMLATTRIBUTES(pkg_common.GetBool(member_isnotnamed) as "IsFullNameSetup"), member_ur_name),
                                     XMLElement("FirstHead", XMLElement("FirstName", imm.member_ur_fisthead_firstname), XMLElement("SecondName", imm.member_ur_fisthead_secondname), XMLElement("MiddleName", imm.member_ur_fisthead_middlename))))

        into lRes
        from imp_members imm
        where imm.log_id = plogid
        and imm.member_id = pmemberid
        order by imm.member_id;
      when 2 then
        SELECT XMLElement("AdditionalPersonInfo",
                          XMLElement("PersonType", 2),
                          XMLElement("AdditionalInformationAc",

                                        XMLElement("URAddress",
                                                   XMLElement("Country", member_reg_counrycode),
                                                   XMLElement("Area", XMLATTRIBUTES(member_reg_area_code as "Code"), member_reg_area),
                                                   XMLElement("District", XMLATTRIBUTES(member_reg_region_code as "Code"), member_reg_region),
                                                   XMLElement("Town", XMLATTRIBUTES(member_reg_sity_code as "Code"), member_reg_sity),
                                                   XMLElement("Street", XMLATTRIBUTES(member_reg_street_code as "Code"), member_reg_street),
                                                   XMLElement("HomeNumber", XMLATTRIBUTES(member_reg_house_code as "Code"), member_reg_house),
                                                   XMLElement("OfficeNumber", XMLATTRIBUTES(member_reg_office_code as "Code"), member_reg_office)),

                                        XMLElement("ACAddress",
                                                   XMLElement("Country", member_seat_counrycode),
                                                   XMLElement("Area", XMLATTRIBUTES(member_seat_area_code as "Code"), member_seat_area),
                                                   XMLElement("District", XMLATTRIBUTES(member_seat_region_code as "Code"), member_seat_region),
                                                   XMLElement("Town", XMLATTRIBUTES(member_seat_sity_code as "Code"), member_seat_sity),
                                                   XMLElement("Street", XMLATTRIBUTES(member_seat_street_code as "Code"), member_seat_street),
                                                   XMLElement("HomeNumber", XMLATTRIBUTES(member_seat_house_code as "Code"), member_seat_house),
                                                   XMLElement("OfficeNumber", XMLATTRIBUTES(member_seat_office_code as "Code"), member_seat_office)),

                                     XMLElement("FIO",
                                                XMLATTRIBUTES(pkg_common.GetBool(member_isnotnamed) as "IsFioNotSetup"),
                                                XMLElement("FirstName", imm.member_ac_firstname),
                                                XMLElement("SecondName", imm.member_ac_secondname),
                                                XMLElement("MiddleName", imm.member_ac_middlename)),

                                     XMLElement("PlaceBirdth", member_ac_birth_place),
                                     XMLElement("DateBirdth", to_char(member_ac_birth_date, 'dd.mm.yyyy')),
                                     XMLElement("DocumentIdentity", member_ac_doc_typecode),
                                     XMLElement("SeriesDocIdentity", member_ac_doc_series),
                                     XMLElement("NumberDocIdentity", member_ac_doc_number),
                                     XMLElement("DocumentIssued", member_ac_doc_whom),
                                     XMLElement("DateIssuance", to_char(member_ac_doc_date, 'dd.mm.yyyy'))

                                     ))
        into lRes
        from imp_members imm
        where imm.log_id = plogid
        and imm.member_id = pmemberid
        order by imm.member_id;
      when 3 then
        SELECT XMLElement("AdditionalPersonInfo",
                          XMLElement("PersonType", 3),
                          XMLElement("AdditionalInformationIp",

                                        XMLElement("URAddress",
                                                   XMLElement("Country", member_reg_counrycode),
                                                   XMLElement("Area", XMLATTRIBUTES(member_reg_area_code as "Code"), member_reg_area),
                                                   XMLElement("District", XMLATTRIBUTES(member_reg_region_code as "Code"), member_reg_region),
                                                   XMLElement("Town", XMLATTRIBUTES(member_reg_sity_code as "Code"), member_reg_sity),
                                                   XMLElement("Street", XMLATTRIBUTES(member_reg_street_code as "Code"), member_reg_street),
                                                   XMLElement("HomeNumber", XMLATTRIBUTES(member_reg_house_code as "Code"), member_reg_house),
                                                   XMLElement("OfficeNumber", XMLATTRIBUTES(member_reg_office_code as "Code"), member_reg_office)),

                                        XMLElement("ACAddress",
                                                   XMLElement("Country", member_seat_counrycode),
                                                   XMLElement("Area", XMLATTRIBUTES(member_seat_area_code as "Code"), member_seat_area),
                                                   XMLElement("District", XMLATTRIBUTES(member_seat_region_code as "Code"), member_seat_region),
                                                   XMLElement("Town", XMLATTRIBUTES(member_seat_sity_code as "Code"), member_seat_sity),
                                                   XMLElement("Street", XMLATTRIBUTES(member_seat_street_code as "Code"), member_seat_street),
                                                   XMLElement("HomeNumber", XMLATTRIBUTES(member_seat_house_code as "Code"), member_seat_house),
                                                   XMLElement("OfficeNumber", XMLATTRIBUTES(member_seat_office_code as "Code"), member_seat_office)),

                                     XMLElement("FIO",
                                                XMLATTRIBUTES(pkg_common.GetBool(member_isnotnamed) as "IsFioNotSetup"),
                                                XMLElement("FirstName", imm.member_ac_firstname),
                                                XMLElement("SecondName", imm.member_ac_secondname),
                                                XMLElement("MiddleName", imm.member_ac_middlename)),

                                     XMLElement("ParticipantOPF", imm.member_ur_opf_code),
                                     XMLElement("PlaceBirdth", member_ac_birth_place),
                                     XMLElement("DateBirdth", to_char(member_ac_birth_date, 'dd.mm.yyyy')),
                                     XMLElement("DocumentIdentity", member_ac_doc_typecode),
                                     XMLElement("SeriesDocIdentity", member_ac_doc_series),
                                     XMLElement("NumberDocIdentity", member_ac_doc_number),
                                     XMLElement("DocumentIssued", member_ac_doc_whom),
                                     XMLElement("DateIssuance", to_char(member_ac_doc_date, 'dd.mm.yyyy'))

                                     ))

        into lRes
        from imp_members imm
        where imm.log_id = plogid
        and imm.member_id = pmemberid
        order by imm.member_id;
      else
        SELECT XMLElement("AdditionalPersonInfo", XMLElement("PersonType", 0))
        into lRes
        from dual;
        --Ip

    end case;

    return lRes.getclobval();
  exception
    when others then
      return lRes.getclobval();
  end;
  function GetFounderInfoXML_3(plogid       number,
                               pfoundertype number,
                               pmemberid    number,
                               pfounderid   number) return clob is
    lRes xmltype;
  begin
    SELECT XMLElement("Founder", NULL)
    INTO lRes
    from dual;
    case pfoundertype
      when 1 then
        select XMLElement("Founder",
                          XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                          XMLElement("FounderType", pfoundertype),
                          XMLElement("FounderOPF", imf.founder_ur_opf_code),
                          XMLElement("Name", imf.founder_ur_name),
                          XMLElement("MemberCommunityCityCode", imf.founder_ur_residence_c_code))

        into lRes
        from imp_found imf
        where imf.log_id = plogid
        and imf.member_id = pmemberid
        and imf.founder_id = pfounderid;
      when 2 then
        select XMLElement("Founder",
                          XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                          XMLElement("FounderType", pfoundertype),
                          XMLElement("FirstName", imf.founder_ac_firstname),
                          XMLElement("SecondName", imf.founder_ac_secondname),
                          XMLElement("MiddleName", imf.founder_ac_middlename),
                          XMLElement("MemberCommunityCityCode", imf.founder_ur_residence_c_code))

        into lRes
        from imp_found imf
        where imf.log_id = plogid
        and imf.member_id = pmemberid
        and imf.founder_id = pfounderid;
      when 3 then
        select XMLElement("Founder",
                          XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi"),
                          XMLElement("FounderType", pfoundertype),
                          XMLElement("FirstName", imf.founder_ac_firstname),
                          XMLElement("SecondName", imf.founder_ac_secondname),
                          XMLElement("MiddleName", imf.founder_ac_middlename),
                          XMLElement("MemberCommunityCityCode", imf.founder_ur_residence_c_code))

        into lRes
        from imp_found imf
        where imf.log_id = plogid
        and imf.member_id = pmemberid
        and imf.founder_id = pfounderid;
    end case;

    return lRes.getclobval();
  exception
    when others then
      return lRes.getclobval();
  end;

  function GetFoundersXML_3(plogid    number,
                            pmemberid number) return CLOB is
    lRes xmltype;
  begin
    SELECT XMLElement("FoundersList", NULL)
    INTO lRes
    from dual;

    SELECT XMLElement("Founders", XMLAgg(XMLtype(GetFounderInfoXml_3(plogid, imf.founder_type, imf.member_id, imf.founder_id))))
    INTO lRes
    from imp_found imf
    where imf.log_id = plogid
    and imf.member_id = pmemberid
    order by imf.founder_id;

    return lRes.getclobval();
  exception
    when no_data_found then
      return lRes.getclobval();
  end;

  function GetMembersXML_3(plogid number) return CLOB is
    lRes xmltype;
  begin
    SELECT XMLElement("ParticipantsList", NULL)
    INTO lRes
    from dual;

    SELECT XMLElement("Participants",
                      XMLAgg(XMLElement("Participant",
                                        --          nvl2(imm.MEMBER_ROLE,XMLElement("ParticipantOperation",imm.MEMBER_ROLE),XMLElement("ParticipantOperation",XMLATTRIBUTES('true' as "xsi:nil"))),
                                        XMLElement("MemberId", imm.member_membercode),
                                        XMLElement("ParticipantsView", imm.MEMBER_KIND),
                                        XMLElement("ParticipantsType", imm.member_type),
                                        XMLElement("IsClientSubject", imm.member_isclient),
                                        XMLElement("MemberCommunityCityCode", member_residence_countrycode),
                                        XMLElement("ForeignPerson", imm.member_foreign),

                                        --CorrespondentBank
                                        XMLElement("CorrespondentBank",
                                                   XMLElement("AccountNumber", imm.member_bank_account),
                                                   XMLElement("Name", imm.member_bank_name),
                                                   XMLElement("Code", imm.member_bank_code),
                                                   XMLElement("BankCity", imm.member_bank_city),
                                                   XMLElement("BankAddress", imm.member_bank_address),
                           XMLElement("BankOffshoreAddr", imm.MEMBER_BANK_OFFSHORE_ADDR),
                                                   xmltype(GetAccountsXML_2(plogid, imm.member_id))

                                                   ),
                                        XMLElement("RNN", imm.member_taxcode),
                                        XMLElement("OKED", imm.member_oked),
                                        XMLElement("IndividualIssue", imm.Member_MainCode),
                                        XMLElement("PhoneNumber", imm.MEMBER_PHONE),
                                        XMLElement("Email", imm.MEMBER_EMAIL),
                                        XMLElement("AdditionalInformation", imm.MEMBER_COMMENTS),
                                        XMLElement("MoneyTransSys", imm.money_trans_sys),
                                        xmltype(GetFoundersXML_3(plogid, imm.member_id)),

                                        xmltype(GetAdditionalInfoXML_3(plogid, imm.member_type, imm.member_id)))))
    INTO lRes
    from imp_members imm
    where imm.log_id = plogid
    order by imm.member_id;

    return lRes.getclobval();
  end;

  function CreateImportXML_3(plogid number) return CLOB is
    result CLOB;
    lRes   xmltype;
    lXML   xmltype;

    lMessInfo CLOB;
    lMembers  CLOB;
  begin
    lMessInfo := GetMessInfoXML_2(plogid);
    lMembers  := GetMembersXML_3(plogid);
    select XMLElement("Root",
                      XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi", 'http://www.w3.org/2001/XMLSchema' as "xmlns:xsd"),
                      pkg_rqst_cfm.rqst_personal_data,
                      XMLType(lMessInfo),
                      refers_2_xml(plogid),
                      XMLType(lMembers),
                      XMLElement("Version", 'C6EC3F8D-2BE1-46A9-841B-5CF1130F0A12'),
                      XMLElement("DocumentUniqueIdentifier", sys_guid()))

    INTO lRes
    from dual;

    lXML   := SYS.XMLType.CreateXML('<?xml version="1.0" encoding="windows-1251"?>' || lRes.getclobval());
    Result := lXML.getclobval();
    return Result;
  end;

end PKG_Import;
/


