/*
* Автор: Галкин А.И.
* Дата: 2013-07-29
* Задача: http://jira.softage.ru/jira/browse/SDFO-70
* Назначение: Результат слияния пакетов базы с веткой SDFO-2012
* Изменяются объекты:
*/

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

declare
	filename      varchar2(256) := 'sfm.database-update.2013-07-29.ReintegrateBranch2012 -r331.sql';
	purpose       varchar2(4000) := 'Результат слияния пакетов базы с веткой SDFO-2012';
	script_exists number := 0;
begin

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

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

	/*
	****** Begin update script ******
	*/
		-- Транзакционный апдейт
		-- execute immediate '';
	/*
	****** End update script ******
	*/
	commit;

exception
	when others then
		rollback;
		raise;
end;

/

CREATE OR REPLACE PACKAGE       "PKG_COMMON" as
  function toClOb(pBlob blob) return clob;
  function GetBool(param in number) return varchar2;
  function IsRightCodeVal(plogid     number,
                          pTableName varchar2,
                          pFieldName varchar2,
                          pCodeType  number,
                          pException out varchar2) return number;
  function GetFormattedGuid(pguid varchar2,
                            pres  out varchar2) return number;
  function GetSimpleGuid(pGuid varchar2) return varchar2;
  function DecodeBase64(txt in clob) return varchar2;
  procedure LogWork(pLogText in varchar2);
  function ConvertToNumber(val varchar2) return number;
  function BoolToNumber(boolname in varchar2) return number;
  procedure InsOrUpdMessagesListTable(ServerType in varchar2);  
end PKG_Common;
/

  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       "PKG_KATOHOLDING" as

  --GetKatoList
  function GetKatoList(pResCursor out sys_refcursor) return number is
    Result number default 0;
  begin
    open pResCursor for
      select k.ab,
             k.cd,
             k.ef,
             k.hij,
             k.k,
             k.kaz_name,
             k.rus_name,
             k.soato,
             k.te,
             k.teparent
        from KATO k;
    return Result;
  exception
    when others then
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  'PKG_KatoHolding.GetKatoList');
      Result := -1; --Общая ошибка
      return Result;
  end GetKatoList;

  --GetKatoName
  function GetKatoName(pTeNumber in number, pNameType in number)
    return nvarchar2 is
    Result KATO.Rus_Name%TYPE default null;
  begin
    case pNameType
      when 1 then
        select k.rus_name
          into Result
          from KATO k
         where k.te = pTeNumber;
      when 2 then
        select k.kaz_name
          into Result
          from KATO k
         where k.te = pTeNumber;
      else
        Result := null;
    end case;
    return Result;
  exception
    when no_data_found then
      Result := null;
      return Result;
    when others then
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  'PKG_KatoHolding.GetKatoName');
      Result := null; --Общая ошибка
      return Result;
  end GetKatoName;

  --GetPathByTeNumber
  function GetPathByTeNumber(pTeNumber in varchar2, pNameType in number)
    return nvarchar2 is
    Result    nvarchar2(1000 CHAR) default null;
    vTeNumber number default pTeNumber;
    vName     KATO.Rus_Name%TYPE;
    vKazName  KATO.kaz_Name%TYPE;
    i         number default 0;
    MAX_COUNT constant number := 10;
    DIVIDER   constant nvarchar2(10 CHAR) := ' / ';
  begin
    case pNameType
      when 1 then
        while vTeNumber != 0 and i < MAX_COUNT loop
          select k.rus_name
            into vName
            from KATO k
           where k.te = vTeNumber;
          if Result is not null then
            Result := vName || DIVIDER || Result;
          else
            Result := vName;
          end if;
          select k.teparent
            into vTeNumber
            from KATO k
           where k.te = vTeNumber;
          i := i + 1;
        end loop;
      when 2 then
        while vTeNumber != 0 and i < MAX_COUNT loop
          select k.kaz_name
            into vKazName
            from KATO k
           where k.te = vTeNumber;
          if Result is not null then
            Result := vKazName || DIVIDER || Result;
          else
            Result := vKazName;
          end if;
          select k.teparent
            into vTeNumber
            from KATO k
           where k.te = vTeNumber;
          i := i + 1;
        end loop;
      else
        Result := null; --Неверный параметр типа имени населенного пункта
    end case;
    return Result;
  exception
    when no_data_found then
      Result := null;
      return Result;
    when others then
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  'PKG_KatoHolding.GetPathByTeNumber');
      Result := null; --Общая ошибка
      return Result;
  end GetPathByTeNumber;

  --FindByNameOrTenumber
  function FindByNameOrTenumber(pKatoName  in varchar2 default null,
                                pNameType  in number default null,
                                pTeNumber  in number default null,
                                pResCursor out sys_refcursor) return number is
    MAX_ROW_COUNT constant integer := 100;
    MAX_STR_LEN   constant integer := 3;
    Result number default 0;
  begin
    if pTeNumber is not null then
      open pResCursor for
        select k.k,
               decode(pNameType, 1, k.rus_name, 2, k.kaz_name, k.rus_name) as pname,
               k.soato,
               k.te,
               decode(pNameType,
                      1,
                      GetPathByTeNumber(k.te, 1),
                      2,
                      GetPathByTeNumber(k.te, 2),
                      GetPathByTeNumber(k.te, 1)) as path
          from KATO k
         where k.te = pTeNumber;
    else
      if length(pKatoName) < MAX_STR_LEN then
        Result := -416; --Длина строки должна быть не менее MAX_ROW_COUNT символов
      else
        case pNameType
          when 1 then
            open pResCursor for
              select k.k,
                     k.rus_name as pname,
                     k.soato,
                     k.te,
                     GetPathByTeNumber(k.te, 1) as path
                from KATO k
               where instr(k.rus_name, pKatoName) > 0
                 and ROWNUM <= MAX_ROW_COUNT
               order by k.rus_name;
          when 2 then
            open pResCursor for
              select k.k,
                     k.kaz_name as pname,
                     k.soato,
                     k.te,
                     GetPathByTeNumber(k.te, 2) as path
                from KATO k
               where instr(k.kaz_name, pKatoName) > 0
                 and ROWNUM <= MAX_ROW_COUNT
               order by k.kaz_name;
          else
            Result := -415; --Неверный параметр типа имени населенного пункта
        end case;
      end if;
    end if;
    return Result;
  exception
    when others then
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  'PKG_KatoHolding.FindByNameOrTenumber');
      Result := -1; --Общая ошибка
      return Result;
  end FindByNameOrTenumber;

  --GetRootList
  function GetRootList(pResCursor out sys_refcursor) return number is
    Result number default 0;
  begin
    open pResCursor for
      WITH t AS
       (SELECT c.te,
               c.teparent,
               c.rus_name,
               c.kaz_name,
               c.k,
               c.soato,
               decode(c.altermode, -1, 0, 1) as isenabled,
               0 as pos
          FROM KATO c
         where c.teparent = 0

        UNION ALL

        SELECT c.te,
               c.teparent,
               c.rus_name,
               c.kaz_name,
               c.k,
               c.soato,
               decode(c.altermode, -1, 0, 1) as isenabled,
               1 as pos
          FROM KATO c
         where c.teparent in
               (select b.te from KATO b where b.teparent = 0)

        UNION ALL

        SELECT c.te,
               c.teparent,
               c.rus_name,
               c.kaz_name,
               c.k,
               c.soato,
               decode(c.altermode, -1, 0, 1) as isenabled,
               2 as pos
          FROM KATO c
         where c.teparent in
               (select b.te
                  from KATO b
                 where b.teparent in
                       (select b.te from KATO b where b.teparent = 0))

        UNION ALL

        SELECT c.te,
               c.teparent,
               c.rus_name,
               c.kaz_name,
               c.k,
               c.soato,
               decode(c.altermode, -1, 0, 1) as isenabled,
               3 as pos
          FROM KATO c
         where c.teparent in
               (select b.te
                  from KATO b
                 where b.teparent in
                       (select b.te
                          from KATO b
                         where b.teparent in
                               (select b.te
                                  from KATO b
                                 where b.teparent = 0)))

        )
      select * from t order by pos;

    return Result;
  exception
    when others then
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  'PKG_KatoHolding.GetRootList');
      Result := -1; --Общая ошибка
      return Result;
  end GetRootList;

  --GetRootList2
  function GetRootList2(pResCursor out sys_refcursor) return number is
    Result number default 0;
  begin
    open pResCursor for
      select t.te,
             t.teparent,
             t.rus_name,
             t.kaz_name,
             t.k,
             t.soato,
             decode(t.altermode, -1, 0, 1) as isenabled,
             decode(to_char(t.teparent),
                    '0',
                    0,
                    (select to_char(t.teparent)
                       from dual
                      where to_char(t.teparent) like '%0000000'),
                    1,
                    (select to_char(t.teparent)
                       from dual
                      where to_char(t.teparent) like '%00000'),
                    2,
                    (select to_char(t.teparent)
                       from dual
                      where to_char(t.teparent) like '%000'),
                    3) as pos
        from Kato t
       order by pos;
    return Result;
  exception
    when others then
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  'PKG_KatoHolding.GetRootList2');
      Result := -1; --Общая ошибка
      return Result;
  end GetRootList2;

  function GetKATOsListByType(pListType  in number,
                              pLang      in number default 1,
                              pKATOId    in number default null,
                              pResCursor out sys_refcursor) return number is
    Result number default 0;
    vlang  number default 1;

  begin
    select decode(pkg_main.GetUserLangSettings,
                  'Russian',
                  1,
                  'Kazakh',
                  2,
                  pLang)
      into vlang
      from dual;

    if pListType = 1 then
      --Области и города областного значения
      open pResCursor for -- select * from db_ar.ates where typeate_id =10
        SELECT kato.te as id,
               decode(vlang, 2, kato.kaz_name, kato.rus_name) as kato_name
          from kato
         where (to_number(ab) between 71 and 99 and
               to_number(cd) in (0, 10))
            or (to_number(ab) between 11 and 69 and to_number(cd) = 0)
         order by decode(vlang, 2, kato.kaz_name, kato.rus_name);
    elsif pListType = 2 then
      --Районы и ??города районного значения??
      open pResCursor for
        SELECT kato.te as id,
               decode(vlang, 2, kato.kaz_name, kato.rus_name) as kato_name
          from kato
         where ((to_number(ab) between 71 and 99 and
               to_number(cd) between 11 and 29 and
               to_number(ef) in (0, 10)) or (to_number(ab) between 11 and 69 and
               to_number(cd) between 10 and 29 and
               TO_number(ef) in (0, 10)) or
               (to_number(ab) between 11 and 69 and
               to_number(cd) between 31 and 99 and TO_number(ef) = 0))
           and kato.teparent = pKATOId
         order by decode(vlang, 2, kato.kaz_name, kato.rus_name);
    elsif pListType = 3 then
      --Населенные пункты
      open pResCursor for
        SELECT kato.te as id,
               decode(vlang, 2, kato.kaz_name, kato.rus_name) as kato_name
          from kato
         where (to_number(ab) between 11 and 69 and
               to_number(cd) between 10 and 29 and
               to_number(ef) between 11 and 19 and to_number(hij) = 100)
            or (to_number(ab) between 11 and 69 and
               to_number(cd) between 31 and 99 and
               to_number(ef) between 20 and 30 and to_number(hij) = 100)
            or (to_number(ab) between 11 and 99 and
               to_number(cd) between 10 and 99 and
               TO_number(ef) between 30 and 90 and to_number(hij) = 100)
            or to_number(hij) not in (0, 100)
         start with kato.teparent = pKATOId
        connect by prior kato.te = kato.teparent
         order by decode(vlang, 2, kato.kaz_name, kato.rus_name);
    else
      null;
    end if;
    return Result;
  exception
    when others then
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  'PKG_ISARHolding.GetATEListByType');
      Result := -1; --Общая ошибка
      return Result;
  end GetKATOsListByType;

end PKG_KatoHolding;
/

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_code := pkg_common.ConvertToNumber(pkg_messages_xml.getsingleval(pNode, 'MessageInformation/AmountCurrency'));
    --??? 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_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_bank_offshore_addr := pkg_messages_xml.getsingleval(pnode, 'CorrespondentBankOffshoreAddress');
    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 '' then   
       pInfoPath := pAcInfoPath;
        when null 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 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');
    if pMember.MEMBER_BANK_OFFSHORE_ADDR is not null then pMember.MEMBER_BANK_IS_OFFSHORE := 1;
     end if;
    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
        when pFounnder.Founder_Type = 1 then
          pFounnder.Founder_Ur_Opf_Code := pkg_messages_xml.getsingleval(pnode, 'FounderOPF');
          pFounnder.founder_ur_name     := pkg_messages_xml.getsingleval(pnode, 'Name');
        when pFounnder.Founder_Type = 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 pFounnder.Founder_Type = 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');
         when pFounnder.Founder_Type >3 then
          pFounnder.Founder_Ur_Opf_Code := pkg_messages_xml.getsingleval(pnode, 'FounderType');
          pFounnder.founder_ur_name     := pkg_messages_xml.getsingleval(pnode, 'Name');
          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()'), 41003),
                       '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/ViewOperationId/text()',
                       pkg_analytic.getshortdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/ViewOperationId/text()'), 41004),

                       'Root/MessageInformation/MerchTypes/text()',
                       pkg_analytic.getshortdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/MerchTypes/text()'), 41055),
                       
                       'Root/MessageInformation/EknpId/text()',
                       pkg_analytic.getshortdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/EknpId/text()'), 41017),
                      'Root/MessageInformation/CurrencyCodeId/text()',
                       pkg_analytic.getshortdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/CurrencyCodeId/text()'), 41018),
                      'Root/MessageInformation/DocOperationReason/text()',
                       pkg_analytic.getdescription(extractvalue(pxmlsch1, 'Root/MessageInformation/DocOperationReason/text()'), 41015),
                       '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()'), 41019),
                           '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/BankOffshoreAddr/text()',
                           pkg_analytic.getshortdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/BankOffshoreAddr/text()'), 41071),
                           'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/BankAddress/text()',
                           pkg_analytic.getdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/CorrespondentBank/BankAddress/text()'), 41019),
                           '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()'), 41019),
                           '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()'), 41019),
                           '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()'), 41019),
                           '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()'), 41019),
                           '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()'), 41019),
                           '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()'), 41019),
                                       'Root/Participants/Participant[' || to_char(i) || ']/MoneyTransSys/text()',
                           pkg_analytic.getshortdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/MoneyTransSys/text()'), 41070),
                           '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()'), 41003),
                          '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()'),40100)
                           --     '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()'),40100)
                           )
          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()'),
                                                           41019))
              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()'), 41019),
                               'Root/Participants/Participant[' || to_char(i) || ']/Founders/Founder[' || to_char(j) || ']/FounderType/text()',
                               pkg_analytic.getshortdescription(extractvalue(pxmlsch, 'Root/Participants/Participant[' || to_char(i) || ']/Founders/Founder[' || to_char(j) || ']/FounderType/text()'), 41003))
              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 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 tempval;
  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, 16) 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;
        
      when 16 then
        vMessid := vMess_cfm.Mess_Parentid;
        if vmessid <> -1 then
            result := ChangeStatus(pMessID, 50, 1);
            result := ChangeStatus(vMessId, 40, 40);
        end if;
    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,
                 currency_info.analyticname   as CurrencyName,
                 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)
          left join analyticcodes currency_info
          on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

          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,
                 currency_info.analyticname   as CurrencyName,
                 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)
          left join analyticcodes currency_info
          on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

          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,
                 currency_info.analyticname   as CurrencyName,
                 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)
          left join analyticcodes currency_info
          on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

          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,
                     currency_info.analyticname   as CurrencyName,
                     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)
              left join analyticcodes currency_info
              on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)


              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,
                     currency_info.analyticname   as CurrencyName,
                     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)
              left join analyticcodes currency_info
              on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

              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,
                     currency_info.analyticname   as CurrencyName,
                     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)
              left join analyticcodes currency_info
              on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

              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,
                 currency_info.analyticname  as CurrencyInfo,
                 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)
          left join analyticcodes currency_info
          on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

          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,
                 currency_info.analyticname   as CurrencyName,
                 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)
          left join analyticcodes currency_info
          on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

          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,
                 currency_info.analyticname   as CurrencyName,
                 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)
          left join analyticcodes currency_info
          on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)


          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,
                     currency_info.analyticname   as CurrencyName,
                     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)
              left join analyticcodes currency_info
              on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)


              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,
                     currency_info.analyticname   as CurrencyName,
                     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)
              left join analyticcodes currency_info
              on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

              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,
                     currency_info.analyticname   as CurrencyName,
                     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)
              left join analyticcodes currency_info
              on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)


              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,
                 currency_info.analyticname   as CurrencyName,
                 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)
          left join analyticcodes currency_info
          on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

          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,
                 currency_info.analyticname   as CurrencyName,
                 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)
          left join analyticcodes currency_info
          on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

          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,
             currency_info.analyticname as CurrencyName,
             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)
      left join analyticcodes currency_info
      on (mc_exec.oper_currency_code = currency_info.analyticcode and currency_info.analytictype = 41018)

      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
        -- Исправить на версию 2 после тестирования
        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;
          elsif suspicreason = 4 then
            result := 3;
          elsif suspicreason = 5 then
            result := 3;
          elsif suspicreason = 6 then
            result := 2;
          end if;
        end if;
      else
        result := 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()'), 41003),
                       'Root/OrganisationData/AdditionalAcData[@IsAc=''True'']/DocumentIdentity/text()',
                       pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/OrganisationData/AdditionalAcData[@IsAc=''True'']/DocumentIdentity/text()'), 40100)
                       --  '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()'), 41003),
                           'Root/OrganisationData/Founders/Founder[' || to_char(i) || ']/ResidenceCode/text()',
                           pkg_analytic.GetDescription(extractvalue(PXMLSCH, 'Root/OrganisationData/Founders/Founder[' || to_char(i) || ']/ResidenceCode/text()'), 41019))
          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 BODY "KFM"."PKG_PASSPORT_CFM" as

  function UpdatePassport(pCFMCODE           in number,
                          pMAINCODE          in varchar2,
                          pTAXCODE           in varchar2,
                          pOKPO              in varchar2,
                          pOKED              in varchar2,
                          pFULLNAME          in varchar2,
                          pSHORTNAME         in varchar2,
                          pREGISTR_DATE      in date,
                          pREGGISTR_NUMBER   in varchar2,
                          pREGISTR_WHO       in varchar2,
                          pREG_KATO          in varchar2,
                          pREG_STREET        in varchar2,
                          pREG_HOUSE         in varchar2,
                          pREG_OFFICE        in varchar2,
                          pREG_POSTINDEX     in varchar2,
                          pREG_DIRECTORY     in varchar2,
                          pREG_AREA          in varchar2,
                          pREG_DISTRICT      in varchar2,
                          pREG_CITY          in varchar2,
                          pBankCode          in varchar2,
                          pFasti_name        in varchar2,
                          pREG_AREA_CODE     in number default null,
                          pREG_DISTRICT_CODE in number default null,
                          pREG_CITY_CODE     in number default null,
                          pREG_STREET_CODE   in number default null,
                          pREG_HOUSE_CODE    in number default null,
                          pREG_OFFICE_CODE   in number default null,
                          pCFMTYPE           in NUMBER default null,
                          pORGCODE           in NUMBER default null,
                          pSECONDNAME        in VARCHAR2 default null,
                          pFIRSTNAME         in VARCHAR2 default null,
                          pMIDDLENAME        in VARCHAR2 default null,
                          pAC_DOC_TYPECODE   in NUMBER default null,
                          pAC_DOC_NUMBER     in VARCHAR2 default null,
                          pAC_DOC_SERIES     in VARCHAR2 default null,
                          pAC_DOC_WHOM       in VARCHAR2 default null,
                          pAC_DOC_DATE       in DATE default null)
    return number is
    Result      number default 0;
    pPassportId number default null;

  begin

    update passport_cfm
       set CFMCODE           = pCFMCODE,
           MAINCODE          = pMAINCODE,
           TAXCODE           = pTAXCODE,
           OKPO              = pOKPO,
           OKED              = pOKED,
           FULLNAME          = pFULLNAME,
           SHORTNAME         = pSHORTNAME,
           REGISTR_DATE      = pREGISTR_DATE,
           REGGISTR_NUMBER   = pREGGISTR_NUMBER,
           REGISTR_WHO       = pREGISTR_WHO,
           REG_KATO          = pREG_KATO,
           REG_STREET        = pREG_STREET,
           REG_HOUSE         = pREG_HOUSE,
           REG_OFFICE        = pREG_OFFICE,
           REG_POSTINDEX     = pREG_POSTINDEX,
           REG_DIRECTORY     = pREG_DIRECTORY,
           REG_AREA          = pREG_AREA,
           REG_DISTRICT      = pREG_DISTRICT,
           REG_CITY          = pREG_CITY,
           BANKCODE          = pBankcode,
           FASTI_NAME        = pfasti_name,
           REG_AREA_CODE     = pREG_AREA_CODE,
           REG_DISTRICT_CODE = pREG_DISTRICT_CODE,
           REG_CITY_CODE     = pREG_CITY_CODE,
           REG_STREET_CODE   = pREG_STREET_CODE,
           REG_HOUSE_CODE    = pREG_HOUSE_CODE,
           REG_OFFICE_CODE   = pREG_OFFICE_CODE,
           CFMTYPE           = pCFMTYPE,
           ORGCODE           = pORGCODE,
           SECONDNAME        = pSECONDNAME,
           FIRSTNAME         = pFIRSTNAME,
           MIDDLENAME        = pMIDDLENAME,
           AC_DOC_TYPECODE   = pAC_DOC_TYPECODE,
           AC_DOC_NUMBER     = pAC_DOC_NUMBER,
           AC_DOC_SERIES     = pAC_DOC_SERIES,
           AC_DOC_WHOM       = pAC_DOC_WHOM,
           AC_DOC_DATE       = pAC_DOC_DATE,
           PASSPORT_STATUS   = 1 --     данные только изменились
     where (PASSPORTID = 1);

    insert into passport_cfm_history
      (CFMCODE,
       MAINCODE,
       TAXCODE,
       OKPO,
       OKED,
       FULLNAME,
       SHORTNAME,
       REGISTR_DATE,
       REGGISTR_NUMBER,
       REGISTR_WHO,
       REG_KATO,
       REG_STREET,
       REG_HOUSE,
       REG_OFFICE,
       REG_POSTINDEX,
       REG_DIRECTORY,
       REG_AREA,
       REG_DISTRICT,
       REG_CITY,
       BANKCODE,
       FASTI_NAME,
       REG_AREA_CODE,
       REG_DISTRICT_CODE,
       REG_CITY_CODE,
       REG_STREET_CODE,
       REG_HOUSE_CODE,
       REG_OFFICE_CODE,
       CFMTYPE,
       ORGCODE,
       SECONDNAME,
       FIRSTNAME,
       MIDDLENAME,
       AC_DOC_TYPECODE,
       AC_DOC_NUMBER,
       AC_DOC_SERIES,
       AC_DOC_WHOM,
       AC_DOC_DATE,
       alter_date)
    values
      (pCFMCODE,
       pMAINCODE,
       pTAXCODE,
       pOKPO,
       pOKED,
       pFULLNAME,
       pSHORTNAME,
       pREGISTR_DATE,
       pREGGISTR_NUMBER,
       pREGISTR_WHO,
       pREG_KATO,
       pREG_STREET,
       pREG_HOUSE,
       pREG_OFFICE,
       pREG_POSTINDEX,
       pREG_DIRECTORY,
       pREG_AREA,
       pREG_DISTRICT,
       pREG_CITY,
       pBANKCODE,
       pFASTI_NAME,
       pREG_AREA_CODE,
       pREG_DISTRICT_CODE,
       pREG_CITY_CODE,
       pREG_STREET_CODE,
       pREG_HOUSE_CODE,
       pREG_OFFICE_CODE,
       pCFMTYPE,
       pORGCODE,
       pSECONDNAME,
       pFIRSTNAME,
       pMIDDLENAME,
       pAC_DOC_TYPECODE,
       pAC_DOC_NUMBER,
       pAC_DOC_SERIES,
       pAC_DOC_WHOM,
       pAC_DOC_DATE,
       SYSDATE);


    pkg_audits.WriteUserAudit(7, 'pkg_passport_cfm.UpdatePassport', null);
    return Result;

  exception
    when others then
      Result := -2000; --Попытка добавить неверные по формату  данные в таблицу или иная ошибка
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  ' PKG_PASSPORT.UpdatePassport');
      return Result;
  end UpdatePassport;

  function SetPassport(pCFMCODE           in number,
                       pMAINCODE          in varchar2,
                       pTAXCODE           in varchar2,
                       pOKPO              in varchar2,
                       pOKED              in varchar2,
                       pFULLNAME          in varchar2,
                       pSHORTNAME         in varchar2,
                       pREGISTR_DATE      in date,
                       pREGGISTR_NUMBER   in varchar2,
                       pREGISTR_WHO       in varchar2,
                       pREG_KATO          in varchar2,
                       pREG_STREET        in varchar2,
                       pREG_HOUSE         in varchar2,
                       pREG_OFFICE        in varchar2,
                       pREG_POSTINDEX     in varchar2,
                       pREG_DIRECTORY     in varchar2,
                       pREG_AREA          in varchar2,
                       pREG_DISTRICT      in varchar2,
                       pREG_CITY          in varchar2,
                       pBankCode          in varchar2,
                       pFasti_name        in varchar2,
                       pREG_AREA_CODE     in number default null, -- изменить обязательно XXX
                       pREG_DISTRICT_CODE in number default null, -- изменить обязательно XXX
                       pREG_CITY_CODE     in number default null,
                       pREG_STREET_CODE   in number default null, -- изменить обязательно XXX
                       pREG_HOUSE_CODE    in number default null, -- изменить обязательно XXX
                       pREG_OFFICE_CODE   in number default null,
                       pCFMTYPE           in NUMBER default 1,
                       pORGCODE           in NUMBER default null, -- изменить обязательно XXX
                       pSECONDNAME        in VARCHAR2 default null,
                       pFIRSTNAME         in VARCHAR2 default null,
                       pMIDDLENAME        in VARCHAR2 default null,
                       pAC_DOC_TYPECODE   in NUMBER default null,
                       pAC_DOC_NUMBER     in VARCHAR2 default null,
                       pAC_DOC_SERIES     in VARCHAR2 default null,
                       pAC_DOC_WHOM       in VARCHAR2 default null,
                       pAC_DOC_DATE       in DATE default null

                       ) return number is
    Result         number default 0;
    result1        number default 0;
    vpassportcount number default 0;
    vcountCahanged number default 0;
    vOldPassport   passport_cfm%rowtype;
    vNewPassport   passport_cfm%rowtype;
    pPassportId    number default null;

  begin
    if (pMAINCODE is null or pCFMCODE is null or pORGCODE is null or
       pFULLNAME is null) then
      return - 2020; -- Не задано ни одно из ключевых значений для Организции, такие как ИИН/БИН, ОПФ, Код СФМ
    elsif (pREG_AREA_CODE is null or pREG_DISTRICT_CODE is null) then
      result := -2021;

    end if;

    select count(*) into vpassportcount from passport_cfm;
    if vpassportcount = 1 then
      select count(*)
        into vcountCahanged
        from passport_cfm t
       where t.passportid = 1
         and CFMCODE = pCFMCODE
         and MAINCODE = pMAINCODE
         and TAXCODE = pTAXCODE
         and OKPO = pOKPO
         and OKED = pOKED
         and FULLNAME = pFULLNAME
         and SHORTNAME = pSHORTNAME
         and REGISTR_DATE = pREGISTR_DATE
         and REGGISTR_NUMBER = pREGGISTR_NUMBER
         and REGISTR_WHO = pREGISTR_WHO
         and REG_KATO = pREG_KATO
         and REG_STREET = pREG_STREET
         and REG_HOUSE = pREG_HOUSE
         and REG_OFFICE = pREG_OFFICE
         and REG_POSTINDEX = pREG_POSTINDEX
         and REG_DIRECTORY = pREG_DIRECTORY
         and REG_AREA = pREG_AREA
         and REG_DISTRICT = pREG_DISTRICT
         and REG_CITY = pREG_CITY
         and BANKCODE = pBankcode
         and FASTI_NAME = pfasti_name
         and REG_AREA_CODE = pREG_AREA_CODE
         and REG_DISTRICT_CODE = pREG_DISTRICT_CODE
         and REG_CITY_CODE = pREG_CITY_CODE
         and REG_STREET_CODE = pREG_STREET_CODE
         and REG_HOUSE_CODE = pREG_HOUSE_CODE
         and REG_OFFICE_CODE = pREG_OFFICE_CODE
         and CFMTYPE = pCFMTYPE
         and ORGCODE = pORGCODE
         and SECONDNAME = pSECONDNAME
         and FIRSTNAME = pFIRSTNAME
         and MIDDLENAME = pMIDDLENAME
         and AC_DOC_TYPECODE = pAC_DOC_TYPECODE
         and AC_DOC_NUMBER = pAC_DOC_NUMBER
         and AC_DOC_SERIES = pAC_DOC_SERIES
         and AC_DOC_WHOM = pAC_DOC_WHOM
         and AC_DOC_DATE = pAC_DOC_DATE;
      /* select t.* into vOldPassport from  passport_cfm t where t.passportid=1;
      select 1,pCFMCODE, pMAINCODE, pTAXCODE, pOKPO, pOKED, pFULLNAME, pSHORTNAME,
                              pREGISTR_DATE, pREGGISTR_NUMBER, pREGISTR_WHO, pREG_KATO, pREG_STREET,
                              pREG_HOUSE, pREG_OFFICE, pREG_POSTINDEX, pREG_DIRECTORY,pREG_AREA, pREG_DISTRICT, pREG_CITY,pBANKCODE,pFASTI_NAME,
                              pREG_AREA_CODE,pREG_DISTRICT_CODE,pREG_CITY_CODE,pREG_STREET_CODE,pREG_HOUSE_CODE,pREG_OFFICE_CODE,t.passport_status,
                              pCFMTYPE,pORGCODE,
                              pSECONDNAME, pFIRSTNAME , pMIDDLENAME , pAC_DOC_TYPECODE , pAC_DOC_NUMBER , pAC_DOC_SERIES, pAC_DOC_WHOM ,pAC_DOC_DATE
             into vNewPassport from passport_cfm t where t.passportid=1;
      if vOldPassport.*=vNewPassport.*
         then return -2023;
      end if; */
      if vcountCahanged = 1 then
        return - 2023;
      end if;
      result1 := UpdatePassport(pCFMCODE,
                                pMAINCODE,
                                pTAXCODE,
                                pOKPO,
                                pOKED,
                                pFULLNAME,
                                pSHORTNAME,
                                pREGISTR_DATE,
                                pREGGISTR_NUMBER,
                                pREGISTR_WHO,
                                pREG_KATO,
                                pREG_STREET,
                                pREG_HOUSE,
                                pREG_OFFICE,
                                pREG_POSTINDEX,
                                pREG_DIRECTORY,
                                pREG_AREA,
                                pREG_DISTRICT,
                                pREG_CITY,
                                pBANKCODE,
                                pFASTI_NAME,
                                pREG_AREA_CODE,
                                pREG_DISTRICT_CODE,
                                pREG_CITY_CODE,
                                pREG_STREET_CODE,
                                pREG_HOUSE_CODE,
                                pREG_OFFICE_CODE,
                                pCFMTYPE,
                                pORGCODE,
                                pSECONDNAME,
                                pFIRSTNAME,
                                pMIDDLENAME,
                                pAC_DOC_TYPECODE,
                                pAC_DOC_NUMBER,
                                pAC_DOC_SERIES,
                                pAC_DOC_WHOM,
                                pAC_DOC_DATE);
      if result1 <> 0 then
        return result1;
      end if;
    else
      insert into passport_cfm
        (PASSPORTID,
         CFMCODE,
         MAINCODE,
         TAXCODE,
         OKPO,
         OKED,
         FULLNAME,
         SHORTNAME,
         REGISTR_DATE,
         REGGISTR_NUMBER,
         REGISTR_WHO,
         REG_KATO,
         REG_STREET,
         REG_HOUSE,
         REG_OFFICE,
         REG_POSTINDEX,
         REG_DIRECTORY,
         REG_AREA,
         REG_DISTRICT,
         REG_CITY,
         BANKCODE,
         FASTI_NAME,
         REG_AREA_CODE,
         REG_DISTRICT_CODE,
         REG_CITY_CODE,
         REG_STREET_CODE,
         REG_HOUSE_CODE,
         REG_OFFICE_CODE,
         CFMTYPE,
         ORGCODE,
         SECONDNAME,
         FIRSTNAME,
         MIDDLENAME,
         AC_DOC_TYPECODE,
         AC_DOC_NUMBER,
         AC_DOC_SERIES,
         AC_DOC_WHOM,
         AC_DOC_DATE)
      values
        (1,
         pCFMCODE,
         pMAINCODE,
         pTAXCODE,
         pOKPO,
         pOKED,
         pFULLNAME,
         pSHORTNAME,
         pREGISTR_DATE,
         pREGGISTR_NUMBER,
         pREGISTR_WHO,
         pREG_KATO,
         pREG_STREET,
         pREG_HOUSE,
         pREG_OFFICE,
         pREG_POSTINDEX,
         pREG_DIRECTORY,
         pREG_AREA,
         pREG_DISTRICT,
         pREG_CITY,
         pBANKCODE,
         pFASTI_NAME,
         pREG_AREA_CODE,
         pREG_DISTRICT_CODE,
         pREG_CITY_CODE,
         pREG_STREET_CODE,
         pREG_HOUSE_CODE,
         pREG_OFFICE_CODE,
         pCFMTYPE,
         pORGCODE,
         pSECONDNAME,
         pFIRSTNAME,
         pMIDDLENAME,
         pAC_DOC_TYPECODE,
         pAC_DOC_NUMBER,
         pAC_DOC_SERIES,
         pAC_DOC_WHOM,
         pAC_DOC_DATE);
    end if;
    insert into passport_cfm_history
      (CFMCODE,
       MAINCODE,
       TAXCODE,
       OKPO,
       OKED,
       FULLNAME,
       SHORTNAME,
       REGISTR_DATE,
       REGGISTR_NUMBER,
       REGISTR_WHO,
       REG_KATO,
       REG_STREET,
       REG_HOUSE,
       REG_OFFICE,
       REG_POSTINDEX,
       REG_DIRECTORY,
       REG_AREA,
       REG_DISTRICT,
       REG_CITY,
       BANKCODE,
       FASTI_NAME,
       REG_AREA_CODE,
       REG_DISTRICT_CODE,
       REG_CITY_CODE,
       REG_STREET_CODE,
       REG_HOUSE_CODE,
       REG_OFFICE_CODE,
       CFMTYPE,
       ORGCODE,
       SECONDNAME,
       FIRSTNAME,
       MIDDLENAME,
       AC_DOC_TYPECODE,
       AC_DOC_NUMBER,
       AC_DOC_SERIES,
       AC_DOC_WHOM,
       AC_DOC_DATE,
       alter_date)
    values
      (pCFMCODE,
       pMAINCODE,
       pTAXCODE,
       pOKPO,
       pOKED,
       pFULLNAME,
       pSHORTNAME,
       pREGISTR_DATE,
       pREGGISTR_NUMBER,
       pREGISTR_WHO,
       pREG_KATO,
       pREG_STREET,
       pREG_HOUSE,
       pREG_OFFICE,
       pREG_POSTINDEX,
       pREG_DIRECTORY,
       pREG_AREA,
       pREG_DISTRICT,
       pREG_CITY,
       pBANKCODE,
       pFASTI_NAME,
       pREG_AREA_CODE,
       pREG_DISTRICT_CODE,
       pREG_CITY_CODE,
       pREG_STREET_CODE,
       pREG_HOUSE_CODE,
       pREG_OFFICE_CODE,
       pCFMTYPE,
       pORGCODE,
       pSECONDNAME,
       pFIRSTNAME,
       pMIDDLENAME,
       pAC_DOC_TYPECODE,
       pAC_DOC_NUMBER,
       pAC_DOC_SERIES,
       pAC_DOC_WHOM,
       pAC_DOC_DATE,
       SYSDATE)
    returning PassportId into pPassportId;
    insert into passport_cfm_stages_history
      (passportid, status, alter_date, request_id, last_answer_id, userid)
    values
      (pPassportId, 1, SYSDATE, null, null, pkg_users.GetCurrentUserId);

    pkg_audits.WriteUserAudit(7, 'pkg_passport_cfm.SetPassport', null);
    Return Result;

  exception
    when others then
      Result := -2000; --Попытка добавить неверные по формату  данные в таблицу или иная ошибка
      pkg_exceptions.AddException(sqlcode,
                                  sqlerrm,
                                  ' PKG_PASSPORT.SetPassport');
      return Result;
  end SetPassport;

  function GetPassport(vPassportCur out sys_refcursor) return number is
    Result number := 0;
  begin

    open vPassportCur for
      select CFMCODE,
             MAINCODE,
             TAXCODE,
             OKPO,
             OKED,
             FULLNAME,
             SHORTNAME,
             REGISTR_DATE,
             REGGISTR_NUMBER,
             REGISTR_WHO,
             REG_KATO,
             REG_STREET,
             REG_HOUSE,
             REG_OFFICE,
             REG_POSTINDEX,
             REG_DIRECTORY,
             REG_AREA,
             REG_DISTRICT,
             REG_CITY,
             BANKCODE,
             FASTI_NAME,
             REG_AREA_CODE,
             REG_DISTRICT_CODE,
             REG_CITY_CODE,
             REG_STREET_CODE,
             REG_HOUSE_CODE,
             REG_OFFICE_CODE,
             cfmtype,
             orgcode,
             secondname,
             firstname,
             middlename,
             ac_doc_typecode,
             ac_doc_number,
             ac_doc_series,
             ac_doc_whom,
             ac_doc_date,
             systemid
        from passport_cfm;
    return Result;
  end;

  function SetDirectory(pREG_DIRECTORY in varchar2) return number is
    Result number default 0;
  begin
    update passport_cfm
       set REG_DIRECTORY = pREG_DIRECTORY
     where PASSPORTID = 1;
    return Result;
  end;

  function GetDirectory(pREG_DIRECTORY out varchar2) return number is
    Result number default 0;
  begin
    select REG_DIRECTORY
      into pREG_DIRECTORY
      from passport_cfm
     where passportid = 1;
    return Result;
  end;

  function GetAdditionalAcData_1(pcfmtype in number) return clob is
    pxml clob;

  begin
    --алексей 2012.10.23
    case pcfmtype
      when 1 then
        /*
              select  XMLElement("AdditionalAcData",XMLATTRIBUTES('False' as "IsAc"),null).getclobval()
                into pxml from dual;
        */
        select XMLElement("AdditionalAcData", XMLATTRIBUTES('False' as "IsAc"), XMLElement("FirstName", firstname), XMLElement("SecondName", secondname), XMLElement("MiddleName", middlename), XMLElement("DocumentIdentity", ac_doc_typecode), XMLElement("SeriesDocIdentity", ac_doc_series), XMLElement("NumberDocIdentity", ac_doc_number), XMLElement("DocumentIssued", ac_doc_whom), XMLElement("DateIssuance", to_char(ac_doc_date, 'dd.mm.yyyy')))
               .getclobval()
          into pxml
          from passport_cfm
         where passportid = 1;
      else
        select XMLElement("AdditionalAcData", XMLATTRIBUTES('True' as "IsAc"), XMLElement("FirstName", firstname), XMLElement("SecondName", secondname), XMLElement("MiddleName", middlename), XMLElement("DocumentIdentity", ac_doc_typecode), XMLElement("SeriesDocIdentity", ac_doc_series), XMLElement("NumberDocIdentity", ac_doc_number), XMLElement("DocumentIssued", ac_doc_whom), XMLElement("DateIssuance", to_char(ac_doc_date, 'dd.mm.yyyy')))
               .getclobval()
          into pxml
          from passport_cfm
         where passportid = 1;
    end case;
    return pxml;
  end;

  function GetFoundersData_1 return clob is
    pxml   clob;
    qryCtx DBMS_XMLGEN.CTXHANDLE;
  begin
    /*select  XMLElement("Founders",XMLATTRIBUTES('True' as "IsAc"),
            XMLElement("FirstName",firstname) ,
            XMLElement("SecondName",secondname),
            XMLElement("MiddleName",middlename),
            XMLElement("DocumentIdentity",ac_doc_typecode),
            XMLElement("SeriesDocIdentity",ac_doc_series),
            XMLElement("NumberDocIdentity",ac_doc_number),
            XMLElement("DocumentIssued",ac_doc_whom),
            XMLElement("DateIssuance",ac_doc_date)
            )
    into pxml from passport_cfm where passportid=1;*/

    /*qryCtx := DBMS_XMLGEN.NEWCONTEXT('select  founder_type as "FounderType",
                                            founder_orgcode as "OpfCode",
                                            founder_ur_name as "UrName",
                                            case founder_type
                                             when 1 then
                                               ''''
                                             else
                                              XMLAGG(XMLConcat(XMLElement("FirstName",founder_ac_firstname),
                                              XMLElement("SecondName",founder_ac_secondname),
                                              XMLElement("MiddleName",founder_ac_middlename)
                                              )).getclobval()

                                            end as "AdditionalAcData"
                                      from founders_cfm')
                                          ;
    DBMS_XMLGEN.setRowTag(qryCtx, 'Founder');
    DBMS_XMLGEN.setRowSetTag(qryCtx, 'Founders');*/
    select XMLElement("Founders", XMLAgg(XMLElement("Founder",
           --          nvl2(imm.MEMBER_ROLE,XMLElement("ParticipantOperation",imm.MEMBER_ROLE),XMLElement("ParticipantOperation",XMLATTRIBUTES('true' as "xsi:nil"))),
           XMLElement("FounderType", founder_type), XMLElement("OpfCode", founder_orgcode), XMLElement("UrName", founder_ur_name),case
            founder_type
             when 1 then
              XMLElement("AdditionalAcData",
                         XMLATTRIBUTES('False' as
                                       "IsAc"),
                         '')
             else
              XMLElement("AdditionalAcData",
                         XMLATTRIBUTES('True' as
                                       "IsAc"),
                         XMLForest(founder_ac_firstname as
                                   "FirstName",
                                   founder_ac_secondname as
                                   "SecondName",
                                   founder_ac_middlename as
                                   "MiddleName"))
           end, XMLElement("ResidenceCode", founder_residence_c_code))))
           .getclobval()
      INTO pxml
      from founders_cfm;
    return pxml;
  end;

  function GetUsersData_1 return clob is
    pxml   clob;
    qryCtx DBMS_XMLGEN.CTXHANDLE;

  begin
    /*  qryCtx := DBMS_XMLGEN.NEWCONTEXT('select firstname   as "FirstName",
                                            lastname    as "SecondName",
                                            middlename  as "MiddleName",
                                            pers_number as "IndividualNumber",
                                            jobname as "JobName",
                                            phones  as "Phone",
                                            emails as "Email",
                                            sertificate as "Certificate",
                                            sertificate_name as "CertificateName"
                                      from users  u
                                      where
                                      exists (select 1 from user_roles ur where ur.userid = u.userid and
                                                                                bitand(ur.roleid,4)=4 and
                                                                                sysdate between ur.datebegin and ur.dateend)
                                      and u.isenable = 1')
                                          ;
    DBMS_XMLGEN.setRowTag(qryCtx, 'Person');
    DBMS_XMLGEN.setRowSetTag(qryCtx, 'Persons');

    pxml   := DBMS_XMLGEN.GETXMLTYPE(qryCtx, DBMS_XMLGEN.NONE);  */

    select XMLElement("Persons", XMLAgg(XMLElement("Person",
           --          nvl2(imm.MEMBER_ROLE,XMLElement("ParticipantOperation",imm.MEMBER_ROLE),XMLElement("ParticipantOperation",XMLATTRIBUTES('true' as "xsi:nil"))),
           XMLElement("FirstName", firstname), XMLElement("SecondName", lastname), XMLElement("MiddleName", middlename), XMLElement("IndividualNumber", pers_number), XMLElement("JobName", jobname), XMLElement("Phone", phones), XMLElement("Email", emails), XMLElement("Certificate", XMLATTRIBUTES(sertificate_name as "Name", sertificate_size as "Size"), sertificate))))
           .getclobval()
      INTO pxml
      from users u
     where exists (select 1
              from user_roles ur
             where ur.userid = u.userid
               and bitand(ur.roleid, 4) = 4
               and sysdate between ur.datebegin and ur.dateend)
       and u.isenable = 1;

    return pxml;
  end;

  function GetPassportXML_1(pOUTXML out clob) return number is
    lRes              clob;
    lXML              xmltype;
    pCfmType          number;
    lAdditionalAcData clob;
    lFoundersData     clob;
    lUsersData        clob;
    resultValidate    clob;

    result number;
  begin

    begin
      select cfmtype into pCFMtype from passport_cfm where passportid = 1;
    exception
      when others then
        pkg_exceptions.AddException(sqlcode,
                                    sqlerrm,
                                    ' PKG_PASSPORT.GetPassportXML_1');
        return - 2001; ---Не заданы ключевые данные об организации: ИИН/БИН, РНН
    end;

    lAdditionalAcData := GetAdditionalAcData_1(pCfmType);
    lFoundersData     := GetFoundersData_1;
    lUsersData        := GetUsersData_1;
    select XMLElement("Root", XMLElement("OrganisationData",

           /* XMLElement("Persons",
                (select XMLAgg(
                   XMLElement("Person",
           --          nvl2(imm.MEMBER_ROLE,XMLElement("ParticipantOperation",imm.MEMBER_ROLE),XMLElement("ParticipantOperation",XMLATTRIBUTES('true' as "xsi:nil"))),
                      XMLElement("FirstName",dbms_xmlgen.CONVERT(firstname, dbms_xmlgen.ENTITY_ENCODE)),
                      XMLElement("SecondName",dbms_xmlgen.CONVERT(lastname, dbms_xmlgen.ENTITY_ENCODE)),
                      XMLElement("MiddleName",dbms_xmlgen.CONVERT(middlename, dbms_xmlgen.ENTITY_ENCODE)),
                      XMLElement("IndividualNumber",dbms_xmlgen.CONVERT(pers_number, dbms_xmlgen.ENTITY_ENCODE)),
                      XMLElement("JobName",dbms_xmlgen.CONVERT(jobname, dbms_xmlgen.ENTITY_ENCODE)),
                      XMLElement("Phone",dbms_xmlgen.CONVERT(phones, dbms_xmlgen.ENTITY_ENCODE)),
                      XMLElement("Email",dbms_xmlgen.CONVERT(emails, dbms_xmlgen.ENTITY_ENCODE)),
                      XMLElement("Certificate",XMLATTRIBUTES(dbms_xmlgen.CONVERT(sertificate_name, dbms_xmlgen.ENTITY_ENCODE) as "Name",sertificate_size as "Size"),
                      pkg_common.toClOb(sertificate))
                     ))
                        from users  u    where
                                               exists (select 1 from user_roles ur where ur.userid = u.userid and
                                                                                         bitand(ur.roleid,4)=4 and
                                                                                         sysdate between ur.datebegin and ur.dateend)
                                               and u.isenable = 1)
                   ),
                  */

           XMLElement("SystemId", systemid), XMLElement("CfmCode", cfmcode), XMLElement("OpfCode", orgcode), XMLElement("OrgName", fullname), XMLElement("ShortName", shortname), XMLElement("RNN", taxcode), XMLElement("IINBIN", maincode), XMLElement("BIK", bankcode), XMLElement("OKED", oked), XMLElement("RegisterDate", to_char(registr_date, 'dd.mm.yyyy')), XMLElement("RegisterNumber", reggistr_number), XMLElement("RegisterAgency", registr_who), xmltype(lAdditionalAcData), XMLElement("PostalIndex", reg_postindex), XMLElement("Area", XMLATTRIBUTES(reg_area_code as "code"), reg_area), XMLElement("District", XMLATTRIBUTES(reg_district_code as "code"), reg_district), XMLElement("City", XMLATTRIBUTES(reg_city_code as "code"), reg_city), XMLElement("Street", XMLATTRIBUTES(reg_street_code as "code"), reg_street), XMLElement("House", XMLATTRIBUTES(reg_house_code as "code"), reg_house), XMLElement("Office", XMLATTRIBUTES(reg_office_code as "code"), reg_office), xmltype(lUsersData), xmltype(lFoundersData)

           ), XMLElement("Version", 'C5ACEF29-0D1D-4B2B-A11F-58BC2C45BD54'), XMLElement("DocumentUniqueIdentifier", sys_guid()))
           .getclobval()
      INTO lRes
      from passport_cfm
     where passportid = 1;

    lXML    := SYS.XMLType.CreateXML(lRes);
    pOUTXML := lXML.getclobval();

    resultValidate := pkg_messverifyprocs.VerifyMessageRegistration(pOUTXML,
                                                                    11,
                                                                    1);

    if length(resultValidate) <> 0 then
      pOutXML := resultValidate;
      return - 900;
    end if;
    return 0;
  end;

  function UpdatePassportData(pXML in clob) return number is
    result number default 0;
  begin
    update passport_cfm
       set SystemId =
           (select extractvalue(xmltype(pXML), '/Root/SystemId/text()')
              from dual)
     where passportid = 1
       and SystemId is null;
    return result;

  exception
    when others then
      return - 2035;
  end;

  function GetCfmId return number is
    result number default null;
  begin
    select systemid into result from passport_cfm where passportid = 1;
    return result;
  end;

end PKG_PASSPORT_CFM;
/
