// charact_mgr.cpp

#include "stdafx.h"
#include <aplNetStepData.h>
#include "dictionary.h"
#include "apl_api.h"
#include "SelectInstDlg.h"
#include "CharacteristicDlg.h"
#include "CharactGroupDlg.h"
#include "ItemCharacrDlg.h"
#include "choose_inst_dlg.h"
#include "DisAsmStatusDlg.h"
#include "CharacterysticTypeForced.h"
#include "DocChanges.h"
#include "UnitConvertionDlg.h"

const TCHAR * si_prefix_ISO[32] = {_T("atto"),  APL_NO_T("атто"),
                                _T("hecto"),  APL_NO_T("гекто"),
                                _T("giga"),  APL_NO_T("гига"),
                                _T("deca"),  APL_NO_T("дека"),
                                _T("deci"),  APL_NO_T("деци"),
                                _T("kilo"),  APL_NO_T("кило"),
                                _T("mega"),  APL_NO_T("мега"),
                                _T("micro"),  APL_NO_T("микро"),
                                _T("milli"),  APL_NO_T("милли"),
                                _T("nano"),  APL_NO_T("нано"),
                                _T("peta"),  APL_NO_T("пета"),
                                _T("pico"),  APL_NO_T("пико"),
                                _T("centi"),  APL_NO_T("санти"),
                                _T("tera"),  APL_NO_T("тера"),
                                _T("femto"),  APL_NO_T("фемто"),
                                _T("exa"),  APL_NO_T("экса")};

const TCHAR * si_unit_name_ISO[56]={_T("metre"),  APL_NO_T("метр"),
                                   _T("gram"),  APL_NO_T("грамм"),
                                   _T("second"),  APL_NO_T("секунда"),
                                   _T("ampere"),  APL_NO_T("ампер"),
                                   _T("kelvin"),  APL_NO_T("кельвин"),
                                   _T("mole"),  APL_NO_T("моль"),
                                   _T("lumen"),  APL_NO_T("люмен"),
                                   _T("becquerel"),  APL_NO_T("беккерель"),
                                   _T("watt"),  APL_NO_T("ватт"),
                                   _T("weber"),  APL_NO_T("вебер"),
                                   _T("volt"),  APL_NO_T("вольт"),
                                   _T("henry"),  APL_NO_T("генри"),
                                   _T("hertz"),  APL_NO_T("герц"),
                                   _T("degree_celsius"),  APL_NO_T("градус Цельсия"),
                                   _T("gray"),  APL_NO_T("грей"),
                                   _T("joule"),  APL_NO_T("джоуль"),
                                   _T("sievert"),  APL_NO_T("зиверт"),
                                   _T("candela"),  APL_NO_T("кандела"),
                                   _T("coulomb"),  APL_NO_T("кулон"),
                                   _T("lux"),  APL_NO_T("люкс"),
                                   _T("newton"),  APL_NO_T("ньютон"),
                                   _T("ohm"),  APL_NO_T("ом"),
                                   _T("pascal"),  APL_NO_T("паскаль"),
                                   _T("radian"),  APL_NO_T("радиан"),
                                   _T("siemens"),  APL_NO_T("сименс"),
                                   _T("steradian"),  APL_NO_T("стерадиан"),
                                   _T("tesla"),  APL_NO_T("тесла"),
                                   _T("farad"),  APL_NO_T("фарад")};

bool CaplCharacteristicManager::m_bUseVersions=true;


CaplStrStrMap si_unit_name_ISO_map, si_prefix_ISO_map;


void init_si_name_map()
{
	if(si_unit_name_ISO_map.GetSize()>0) return;
	int i;
	for(i=0;i<56;i+=2)
	{
		//si_unit_name_ISO_map.Add(si_unit_name_ISO[i],(long)si_unit_name_ISO[i+1]);
		const TCHAR *enname=si_unit_name_ISO[i];
		const TCHAR *runame=si_unit_name_ISO[i+1];
		si_unit_name_ISO_map.Add(enname,CaplTranslate::Translate(runame));
	}

	for(i=0;i<32;i+=2)
	{
		//si_prefix_ISO_map.Add(si_prefix_ISO[i],(long)si_prefix_ISO[i+1]);
		const TCHAR *enname=si_prefix_ISO[i];
		const TCHAR *runame=si_prefix_ISO[i+1];
		si_prefix_ISO_map.Add(enname,CaplTranslate::Translate(runame));
	}
}
//*************************************************************
bool CaplCharacteristicManager::Attach(CaplAPI *api)
{
	if(api==0) {Detach();return false;}
	CaplStepManager::Attach(api);

	CHECK_ZERO_ATTR(e_apl_unit, m_data->GetEntityBN(_T("apl_unit")));
	CHECK_ZERO_ATTR(e_apl_aggr_unit, m_data->GetEntityBN(_T("apl_aggregation_unit")));
	CHECK_ZERO_ATTR(e_apl_descript_unit, m_data->GetEntityBN(_T("apl_descriptive_unit")));
	CHECK_ZERO_ATTR(e_apl_time_unit, m_data->GetEntityBN(_T("apl_point_in_time_unit")));
	CHECK_ZERO_ATTR(e_apl_enum_unit, m_data->GetEntityBN(_T("apl_enumeration_unit")));
	CHECK_ZERO_ATTR(e_apl_monetary_unit, m_data->GetEntityBN(_T("apl_monetary_unit")));
	CHECK_ZERO_ATTR(e_apl_step_unit, m_data->GetEntityBN(_T("step_unit")));
	CHECK_ZERO_ATTR(e_apl_named_unit, m_data->GetEntityBN(_T("named_unit")));
	CHECK_ZERO_ATTR(e_apl_derived_unit, m_data->GetEntityBN(_T("derived_unit")));
	CHECK_ZERO_ATTR(e_apl_conv_base_unit, m_data->GetEntityBN(_T("conversion_based_unit")));
	CHECK_ZERO_ATTR(e_apl_alp_base_unit, m_data->GetEntityBN(_T("logistic_dependent_unit")));
	CHECK_ZERO_ATTR(e_mission_apl_alp_base_unit, m_data->GetEntityBN(_T("mission_logistic_dependent_unit")));
	CHECK_ZERO_ATTR(e_year_apl_alp_base_unit, m_data->GetEntityBN(_T("year_logistic_dependent_unit")));
	CHECK_ZERO_ATTR(e_flight_days_apl_alp_base_unit, m_data->GetEntityBN(_T("flight_days_logistic_dependent_unit")));
	CHECK_ZERO_ATTR(e_apl_cont_dep_unit, m_data->GetEntityBN(_T("context_dependent_unit")));
	CHECK_ZERO_ATTR(e_apl_change_charact, m_data->GetEntityBN(_T("apl_characteristic_change")));
	CHECK_ZERO_ATTR(e_apl_reference_comp_unit, m_data->GetEntityBN(_T("apl_reference_comp_unit")));
	CHECK_ZERO_ATTR(e_apl_reference_maint_unit, m_data->GetEntityBN(_T("apl_reference_maint_unit")));
	CHECK_ZERO_ATTR(e_apl_reference_proc_chart_unit, m_data->GetEntityBN(_T("apl_reference_proc_chart_unit")));

	CHECK_ZERO_ATTR(a_apl_change_charact_old_val,  m_data->GetAttrDefinition(e_apl_change_charact,_T("old_version")));
	CHECK_ZERO_ATTR(a_apl_change_charact_new_val,  m_data->GetAttrDefinition(e_apl_change_charact,_T("new_version")));
	CHECK_ZERO_ATTR(a_apl_change_charact_charact,  m_data->GetAttrDefinition(e_apl_change_charact,_T("characteristic")));
	CHECK_ZERO_ATTR(a_apl_change_charact_delta,  m_data->GetAttrDefinition(e_apl_change_charact,_T("delta")));
	CHECK_ZERO_ATTR(a_apl_change_charact_type,  m_data->GetAttrDefinition(e_apl_change_charact,_T("type")));
	CHECK_ZERO_ATTR(a_apl_change_charact_basis,  m_data->GetAttrDefinition(e_apl_change_charact,_T("basis")));

	CHECK_ZERO_ATTR(e_apl_si_unit, m_data->GetEntityBN(_T("si_unit")));
	CHECK_ZERO_ATTR(a_apl_unit_id, m_data->GetAttrDefinition(e_apl_unit,S::id));
	CHECK_ZERO_ATTR(a_apl_unit_name, m_data->GetAttrDefinition(e_apl_unit,S::name));
	CHECK_ZERO_ATTR(a_apl_unit_name_eng, m_data->GetAttrDefinitionBN(_T("apl_unit"), _T("name_eng")));
	CHECK_ZERO_ATTR(a_apl_unit_shown_id, m_data->GetAttrDefinitionBN(_T("apl_unit"), _T("shown_id")));
	CHECK_ZERO_ATTR(a_apl_unit_prefix, m_data->GetAttrDefinition(e_apl_si_unit,S::prefix));
	CHECK_ZERO_ATTR(a_apl_unit_descr, m_data->GetAttrDefinition(e_apl_unit,S::description));
	CHECK_ZERO_ATTR(a_apl_unit_code, m_data->GetAttrDefinition(e_apl_unit,S::code));

	CHECK_ZERO_ATTR(e_table_unit, m_data->GetEntityBN(_T("apl_table_unit")));
	CHECK_ZERO_ATTR(e_table_column, m_data->GetEntityBN(_T("apl_table_column")));
	CHECK_ZERO_ATTR(a_table_column_name, m_data->GetAttrDefinition(e_table_column,_T("name")));
	CHECK_ZERO_ATTR(a_table_column_unit, m_data->GetAttrDefinition(e_table_column,_T("unit")));

	CHECK_ZERO_ATTR(e_apl_charact, m_data->GetEntityBN(_T("apl_characteristic")));
	CHECK_ZERO_ATTR(a_apl_charact_id, m_data->GetAttrDefinition(e_apl_charact,S::id));
	CHECK_ZERO_ATTR(a_apl_charact_name, m_data->GetAttrDefinition(e_apl_charact,S::name));
	CHECK_ZERO_ATTR(a_apl_charact_unit, m_data->GetAttrDefinition(e_apl_charact,_T("unit")));
	CHECK_ZERO_ATTR(a_apl_charact_module, m_data->GetAttrDefinition(e_apl_charact,_T("editor_module")));
	CHECK_ZERO_ATTR(a_apl_charact_method, m_data->GetAttrDefinition(e_apl_charact,_T("editor_function")));
	CHECK_ZERO_ATTR(a_apl_charact_descr, m_data->GetAttrDefinition(e_apl_charact,_T("description")));
	CHECK_ZERO_ATTR(a_apl_charact_code, m_data->GetAttrDefinition(e_apl_charact,_T("code")));
	CHECK_ZERO_ATTR(a_apl_charact_dynamic ,  m_data->GetAttrDefinition(e_apl_charact,_T("dinamic")));
	CHECK_ZERO_ATTR(a_apl_charact_system ,  m_data->GetAttrDefinition(e_apl_charact,_T("system")));
	CHECK_ZERO_ATTR(a_apl_charact_GUID,  m_data->GetAttrDefinition(e_apl_charact,_T("guid")));
	CHECK_ZERO_ATTR(a_apl_charact_full_name,  m_data->GetAttrDefinition(e_apl_charact,_T("full_name")));
	CHECK_ZERO_ATTR(a_apl_charact_mask_input, m_data->GetAttrDefinition(e_apl_charact, _T("mask_input")));

	CHECK_ZERO_ATTR(e_apl_charact_union, m_data->GetEntityBN(_T("apl_characteristic_union")));
	CHECK_ZERO_ATTR(a_apl_charact_union_id, m_data->GetAttrDefinition(e_apl_charact_union,S::id));
	CHECK_ZERO_ATTR(a_apl_charact_union_name, m_data->GetAttrDefinition(e_apl_charact_union,S::name));
	CHECK_ZERO_ATTR(a_apl_charact_union_descr, m_data->GetAttrDefinition(e_apl_charact_union,S::description));
	CHECK_ZERO_ATTR(a_apl_charact_union_characteristics, m_data->GetAttrDefinition(e_apl_charact_union,_T("characteristics")));

	CHECK_ZERO_ATTR(e_apl_charact_value, m_data->GetEntityBN(_T("apl_characteristic_value")));

	CHECK_ZERO_ATTR(a_apl_charact_val_item, m_data->GetAttrDefinition(e_apl_charact_value,_T("item")));
	CHECK_ZERO_ATTR(a_apl_charact_val_base_item, m_data->GetAttrDefinition(e_apl_charact_value,_T("base_item")));
	CHECK_ZERO_ATTR(a_apl_charact_val_charact, m_data->GetAttrDefinition(e_apl_charact_value,_T("characteristic")));
	CHECK_ZERO_ATTR(a_apl_charact_val_type, m_data->GetAttrDefinition(e_apl_charact_value,_T("assignment_type")));
	CHECK_ZERO_ATTR(a_apl_charact_val_num, m_data->GetAttrDefinition(e_apl_charact_value,_T("number_of_measurement")));
	CHECK_ZERO_ATTR(a_apl_charact_val_scope, m_data->GetAttrDefinition(e_apl_charact_value,_T("scope")));
	CHECK_ZERO_ATTR(a_apl_charact_val_group, m_data->GetAttrDefinition(e_apl_charact_value,_T("group")));
	CHECK_ZERO_ATTR(a_apl_charact_val_function ,  m_data->GetAttrDefinition(e_apl_charact_value,_T("function")));
	CHECK_ZERO_ATTR(a_apl_charact_val_element,m_data->GetAttrDefinition(e_apl_charact_value,_T("element")))
	CHECK_ZERO_ATTR(a_apl_charact_val_system,m_data->GetAttrDefinition(e_apl_charact_value, _T("system")));
	CHECK_ZERO_ATTR(a_apl_charact_val_guid,m_data->GetAttrDefinition(e_apl_charact_value, _T("guid")));
	CHECK_ZERO_ATTR(a_apl_charact_val_notes,m_data->GetAttrDefinition(e_apl_charact_value, _T("notes")));

	CHECK_ZERO_ATTR(e_meas_value, m_data->GetEntityBN(_T("apl_measured_characteristic_value")));
	CHECK_ZERO_ATTR(e_descr_value, m_data->GetEntityBN(_T("apl_descriptive_characteristic_value")));
	CHECK_ZERO_ATTR(e_monet_value, m_data->GetEntityBN(_T("apl_monetary_characteristic_value")));
	CHECK_ZERO_ATTR(e_enum_value, m_data->GetEntityBN(_T("apl_enumeration_characteristic_value")));
	CHECK_ZERO_ATTR(e_time_val, m_data->GetEntityBN(_T("apl_point_in_time_characteristic_value")));
	CHECK_ZERO_ATTR(e_aggr_val, m_data->GetEntityBN(_T("apl_aggregation_characteristic_value")));
	CHECK_ZERO_ATTR(e_apl_reference_value, m_data->GetEntityBN(_T("apl_reference_value")));
	CHECK_ZERO_ATTR(e_table_val, m_data->GetEntityBN(_T("apl_table_characteristic_value")));

	CHECK_ZERO_ATTR(a_apl_charact_val_meas_val, m_data->GetAttrDefinition(e_meas_value,_T("val")));
	CHECK_ZERO_ATTR(a_apl_charact_val_meas_max, m_data->GetAttrDefinition(e_meas_value,_T("max_deviation")));
	CHECK_ZERO_ATTR(a_apl_charact_val_meas_min, m_data->GetAttrDefinition(e_meas_value,_T("min_deviation")));
	CHECK_ZERO_ATTR(a_apl_charact_val_descr_val, m_data->GetAttrDefinition(e_descr_value,_T("val")));
	CHECK_ZERO_ATTR(a_apl_charact_val_enum_val, m_data->GetAttrDefinition(e_enum_value,_T("val")));
	CHECK_ZERO_ATTR(a_apl_charact_val_monet_val, m_data->GetAttrDefinition(e_monet_value,_T("val")));
	CHECK_ZERO_ATTR(a_apl_charact_val_time_val_s, m_data->GetAttrDefinition(e_time_val,_T("val_s")));
	CHECK_ZERO_ATTR(a_apl_charact_val_unit, m_data->GetAttrDefinition(e_time_val,_T("unit")));

	CHECK_ZERO_ATTR(e_charact_val_group, m_data->GetEntityBN(_T("apl_characteristic_value_group")));
	CHECK_ZERO_ATTR(a_charact_val_group_item, m_data->GetAttrDefinition(e_charact_val_group,_T("item")));
	CHECK_ZERO_ATTR(a_charact_val_group_def, m_data->GetAttrDefinition(e_charact_val_group,_T("definition")));
	
	CHECK_ZERO_ATTR(e_apl_charact_type, m_data->GetEntityBN(_T("apl_characteristic_assignment_type")));
	CHECK_ZERO_ATTR(a_apl_charact_type_name, m_data->GetAttrDefinition(e_apl_charact_type,_T("name")));
	
	CHECK_ZERO_ATTR(e_table_row, m_data->GetEntityBN(_T("apl_table_value_row")));
	CHECK_ZERO_ATTR(e_table_cell, m_data->GetEntityBN(_T("apl_table_value_cell")));
	CHECK_ZERO_ATTR(a_table_cell_column, m_data->GetAttrDefinition(e_table_cell,_T("column")));
	CHECK_ZERO_ATTR(a_table_cell_val, m_data->GetAttrDefinition(e_table_cell,_T("val")));

	CHECK_ZERO_ATTR(a_apl_charact_val_aggr_val, m_data->GetAttrDefinition(e_aggr_val,_T("values")));
	CHECK_ZERO_ATTR(a_apl_charact_val_table_val, m_data->GetAttrDefinition(e_table_val,_T("values")));
	CHECK_ZERO_ATTR(a_table_row_items, m_data->GetAttrDefinition(e_table_row,_T("items")));

	CHECK_ZERO_ATTR(a_apl_reference_val, m_data->GetAttrDefinition(e_apl_reference_value,_T("val")));
	CHECK_ZERO_ATTR(e_apl_reference_unit, m_data->GetEntityBN(_T("apl_reference_unit")));
	CHECK_ZERO_ATTR(a_apl_reference_types, m_data->GetAttrDefinition(e_apl_reference_unit,_T("types")));
	CHECK_ZERO_ATTR(a_apl_reference_base, m_data->GetAttrDefinition(e_apl_reference_unit,_T("base_items")));
	CHECK_ZERO_ATTR(a_apl_reference_format, m_data->GetAttrDefinition(e_apl_reference_unit,_T("show_format")));

	CHECK_ZERO_ATTR(e_apl_charact_group, m_data->GetEntityBN(_T("apl_characteristic_group")));
	CHECK_ZERO_ATTR(a_apl_charact_group_id, m_data->GetAttrDefinition(e_apl_charact_group,_T("id")));
	CHECK_ZERO_ATTR(a_apl_charact_group_name, m_data->GetAttrDefinition(e_apl_charact_group,_T("name")));
	CHECK_ZERO_ATTR(a_apl_charact_group_description, m_data->GetAttrDefinition(e_apl_charact_group,_T("description")));
	CHECK_ZERO_ATTR(a_apl_charact_group_content, m_data->GetAttrDefinition(e_apl_charact_group,_T("content")));
	CHECK_ZERO_ATTR(a_apl_charact_group_parent, m_data->GetAttrDefinition(e_apl_charact_group,_T("parent")));

	CHECK_ZERO_ATTR(e_apl_unit_group, m_data->GetEntityBN(_T("apl_unit_group")));
	CHECK_ZERO_ATTR(a_apl_unit_group_id, m_data->GetAttrDefinition(e_apl_unit_group,_T("id")));
	CHECK_ZERO_ATTR(a_apl_unit_group_name, m_data->GetAttrDefinition(e_apl_unit_group,_T("name")));
	CHECK_ZERO_ATTR(a_apl_unit_group_description, m_data->GetAttrDefinition(e_apl_unit_group,_T("description")));
	CHECK_ZERO_ATTR(a_apl_unit_group_content, m_data->GetAttrDefinition(e_apl_unit_group,_T("content")));
	CHECK_ZERO_ATTR(a_apl_unit_group_parent, m_data->GetAttrDefinition(e_apl_unit_group,_T("parent")));

	CHECK_ZERO_ATTR(e_apl_charact_union_group, m_data->GetEntityBN(_T("apl_characteristic_union_group")));
	CHECK_ZERO_ATTR(a_apl_charact_union_group_id, m_data->GetAttrDefinition(e_apl_charact_union_group,_T("id")));
	CHECK_ZERO_ATTR(a_apl_charact_union_group_name, m_data->GetAttrDefinition(e_apl_charact_union_group,_T("name")));
	CHECK_ZERO_ATTR(a_apl_charact_union_group_description, m_data->GetAttrDefinition(e_apl_charact_union_group,_T("description")));
	CHECK_ZERO_ATTR(a_apl_charact_union_group_content, m_data->GetAttrDefinition(e_apl_charact_union_group,_T("content")));
	CHECK_ZERO_ATTR(a_apl_charact_union_group_parent, m_data->GetAttrDefinition(e_apl_charact_union_group,_T("parent")));

//Версии
	CHECK_ZERO_ATTR(a_apl_charact_val_act_ver, m_data->GetAttrDefinition(e_apl_charact_value,_T("active_version")));
	CHECK_ZERO_ATTR(a_apl_charact_val_lock_ver, m_data->GetAttrDefinition(e_apl_charact_value,_T("locker_version")));

	CHECK_ZERO_ATTR(e_apl_charact_value_ver, m_data->GetEntityBN(_T("apl_characteristic_value_version")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_char_value, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("characteristic_value")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_author, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("author")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_start_date, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("start_date")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_end_date, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("end_date")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_version_num, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("number")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_base, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("base")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_item, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("item")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_charact, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("characteristic")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_scope, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("scope")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_num, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("number_of_measurement")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_type, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("assignment_type")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_is_changed, m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("is_value_changed")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_function , m_data->GetAttrDefinition(e_apl_charact_value_ver,_T("function")));
	
	CHECK_ZERO_ATTR(e_enum_value_ver, m_data->GetEntityBN(_T("apl_enumeration_characteristic_value_version")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_enum_val, m_data->GetAttrDefinition(e_enum_value_ver,_T("val")));

	CHECK_ZERO_ATTR(e_monet_value_ver, m_data->GetEntityBN(_T("apl_monetary_characteristic_value_version")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_monet_val, m_data->GetAttrDefinition(e_monet_value_ver,_T("val")));

	CHECK_ZERO_ATTR(e_meas_value_ver, m_data->GetEntityBN(_T("apl_measured_characteristic_value_version")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_meas_val, m_data->GetAttrDefinition(e_meas_value_ver,_T("val")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_meas_max, m_data->GetAttrDefinition(e_meas_value_ver,_T("max_deviation")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_meas_min, m_data->GetAttrDefinition(e_meas_value_ver,_T("min_deviation")));

	CHECK_ZERO_ATTR(e_apl_reference_value_ver, m_data->GetEntityBN(_T("apl_reference_value_version")));
	CHECK_ZERO_ATTR(a_apl_reference_val_ver_val, m_data->GetAttrDefinition(e_apl_reference_value_ver,_T("val")));

	CHECK_ZERO_ATTR(e_time_val_ver, m_data->GetEntityBN(_T("apl_point_in_time_characteristic_value_version")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_time_val_s, m_data->GetAttrDefinition(e_time_val_ver,_T("val_s")));

	CHECK_ZERO_ATTR(e_descr_value_ver, m_data->GetEntityBN(_T("apl_descriptive_characteristic_value_version")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_descr_val, m_data->GetAttrDefinition(e_descr_value_ver,_T("val")));

	CHECK_ZERO_ATTR(e_aggr_val_ver, m_data->GetEntityBN(_T("apl_aggregation_characteristic_value_version")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_aggr_val, m_data->GetAttrDefinition(e_aggr_val_ver,_T("values")));

	CHECK_ZERO_ATTR(e_table_val_ver, m_data->GetEntityBN(_T("apl_table_characteristic_value_version")));
	CHECK_ZERO_ATTR(a_apl_charact_val_ver_table_val, m_data->GetAttrDefinition(e_table_val_ver,_T("values")));
	CHECK_ZERO_ATTR(e_table_row_ver, m_data->GetEntityBN(_T("apl_table_value_row_version")));
	CHECK_ZERO_ATTR(a_table_row_ver_items, m_data->GetAttrDefinition(e_table_row_ver,_T("items")));
	CHECK_ZERO_ATTR(e_table_cell_ver, m_data->GetEntityBN(_T("apl_table_value_cell_version")));
	CHECK_ZERO_ATTR(a_table_cell_ver_column, m_data->GetAttrDefinition(e_table_cell_ver,_T("column")));
	CHECK_ZERO_ATTR(a_table_cell_ver_val, m_data->GetAttrDefinition(e_table_cell_ver,_T("val")));

	CHECK_ZERO_ATTR(e_apl_characteristic_and_type ,  api->m_data.GetEntityBN(_T("apl_characteristic_and_type")));
	//a_apl_characteristic_and_type_base_classifier ,  api->m_data.GetAttrDefinition(e_apl_characteristic_and_type, _T("base_item"));
	CHECK_ZERO_ATTR(a_apl_characteristic_and_type_base_item ,  api->m_data.GetAttrDefinition(e_apl_characteristic_and_type, _T("base_item")));
	CHECK_ZERO_ATTR(a_apl_characteristic_and_type_characteristic ,  api->m_data.GetAttrDefinition(e_apl_characteristic_and_type, _T("characteristic")));
	CHECK_ZERO_ATTR(a_apl_characteristic_and_type_type ,  api->m_data.GetAttrDefinition(e_apl_characteristic_and_type, _T("type")));
	CHECK_ZERO_ATTR(a_apl_characteristic_and_type_required ,  api->m_data.GetAttrDefinition(e_apl_characteristic_and_type, _T("required")));
	
	CHECK_ZERO_ATTR(e_apl_unit_convertion					, api->m_data.GetEntityBN(_T("apl_unit_convertion")));
	CHECK_ZERO_ATTR(a_apl_unit_convertion_item				, api->m_data.GetAttrDefinition(e_apl_unit_convertion,_T("item")));
	CHECK_ZERO_ATTR(a_apl_unit_convertion_base_unit			, api->m_data.GetAttrDefinition(e_apl_unit_convertion,_T("base_unit")));
	CHECK_ZERO_ATTR(a_apl_unit_convertion_add_unit			, api->m_data.GetAttrDefinition(e_apl_unit_convertion,_T("additional_unit")));
	CHECK_ZERO_ATTR(a_apl_unit_convertion_base_unit_koef	, api->m_data.GetAttrDefinition(e_apl_unit_convertion,_T("base_unit_koef")));
	CHECK_ZERO_ATTR(a_apl_unit_convertion_add_unit_koef		, api->m_data.GetAttrDefinition(e_apl_unit_convertion,_T("additional_unit_koef")));
	
	if (m_data->IsConnected() && m_AllAttrDefined)
	{
		CaplLoadData ld(m_data,DEF_SOURCE);
		int i=ld.AddQuery(_T('e'), 0, e_apl_charact_type,0, true,true);
		  //ld.AddQuery(_T('d'), i, 0,a_apl_charact_type_name, true);
		ld.LoadEx();
	}
	return m_AllAttrDefined;
}
//*************************************************************
bool CaplCharacteristicManager::LoadDictionary()
{
	if(m_data==0) return false;
	if(!m_data->IsConnected()) return false;
	if(e_apl_charact==0) return false;

	if(!m_data->IsConnected()) return true;
	
	int i,j;
	CaplAttr *attr;
	CaplLoadData ld(m_data,DEF_SOURCE);
	// ссылка
		// Чтение характеристик
		
	i=	ld.AddQuery(_T('e'), 0, e_apl_charact, 0, true,true);
	i=	ld.AddQuery(_T('e'), 0, e_apl_charact_union, 0, true,true);
		// типы характеристие
	i=	ld.AddQuery(_T('e'), 0, e_apl_charact_type, 0, true,true);
		//ld.AddQuery(_T('d'), i, 0, a_apl_charact_type_name, true);

		// Чтение единиц измерения
		//StatusString(APL_T("Чтение единиц измерения"));
		
	i=	ld.AddQuery(_T('e'), 0, e_apl_unit, 0, true,true);

		attr=m_data->GetAttrDefinition(e_apl_named_unit,_T("dimensions"));
		j=	ld.AddQuery(_T('d'), i, 0, attr, true,true);

		attr=m_data->GetAttrDefinition(e_apl_conv_base_unit,_T("conversion_factor"));
	j= ld.AddQuery(_T('d'), i, 0, attr, true,true);
		attr=m_data->GetAttrDefinition(e_apl_derived_unit,_T("elements"));
	j=ld.AddQuery(_T('d'), i, 0, attr, true,true);
		attr=m_data->GetAttrDefinition(e_table_unit,_T("columns"));
	j=ld.AddQuery(_T('d'), i, 0, attr, true,true);
	i=ld.AddQuery(_T('e'),0,e_apl_charact_group,0,true,true);
	i=ld.AddQuery(_T('e'),0,e_apl_unit_group,0,true,true);
	i=ld.AddQuery(_T('e'),0,e_apl_charact_union_group,0,true,true);
	i=ld.AddQuery(_T('e'),0,e_apl_characteristic_and_type,0,true,true);
	if(!ld.LoadEx(true,0, APL_T("Чтение характеристик")))
	{
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка чтения информации о характеристиках (MGR)"),MB_OK|MB_ICONSTOP);
		return false;
	}
#ifdef _DEBUG
//	m_data->SaveToTextFile(_T("d:\\_swh\\111.txt"));
#endif
	return true;
}

//*************************************************************
void CaplCharacteristicManager::Detach()
{
	m_data=0;

	a_apl_charact_mask_input = 0;
	e_apl_charact=0; a_apl_charact_id=0; a_apl_charact_name=0; a_apl_charact_descr=0;
	a_apl_charact_unit=0; a_apl_charact_module=0; a_apl_charact_method=0;a_apl_charact_full_name=0;
	a_apl_charact_code=0; a_apl_charact_dynamic = 0;a_apl_charact_system=0;a_apl_charact_GUID=0;

	e_apl_charact_union=0;
	a_apl_charact_union_id=0; a_apl_charact_union_name=0; a_apl_charact_union_descr=0;
	a_apl_charact_union_characteristics=0;


	e_apl_charact_value=0; 
	a_apl_charact_val_meas_val=0; a_apl_charact_val_meas_max=0; a_apl_charact_val_meas_min=0;
	a_apl_charact_val_descr_val=0; a_apl_charact_val_enum_val=0;
	a_apl_charact_val_monet_val=0; a_apl_charact_val_time_val_s=0;
	a_apl_charact_val_unit=0; a_apl_charact_val_notes=0;

	a_apl_charact_val_item=0;
	a_apl_charact_val_charact=0;
	a_apl_charact_val_type=0;
	a_apl_charact_val_num=0; a_apl_charact_val_scope=0;
	a_apl_charact_val_group=0;
	a_apl_charact_val_element = NULL;
	a_apl_charact_val_system = NULL;
	a_apl_charact_val_guid = 0;

	e_apl_charact_type=0;
	a_apl_charact_type_name=0;

	e_charact_val_group=0;
	a_charact_val_group_item=0;
	a_charact_val_group_def=0;

	e_apl_unit			=	0;
	e_apl_aggr_unit		=	0;
	e_apl_descript_unit	=	0;
	e_apl_time_unit		=	0;
	e_apl_enum_unit		=	0;
	e_apl_monetary_unit	=	0;
	e_apl_step_unit		=	0;
	e_apl_named_unit	=	0;
	e_apl_derived_unit	=	0;
	e_apl_conv_base_unit=	0;
	e_apl_alp_base_unit =   0;
	e_apl_si_unit		=	0;
	e_apl_cont_dep_unit	=	0;

	e_table_unit=0; e_table_column=0;

	a_apl_unit_id =0; a_apl_unit_name =0; a_apl_unit_shown_id = 0 ; a_apl_unit_descr =0; a_apl_unit_code =0;
	a_apl_unit_prefix = 0; a_apl_unit_name_eng = 0;

	e_apl_charact_value=0; e_meas_value=0; e_descr_value=0;
	e_enum_value=0; e_monet_value=0;

	e_aggr_val=0; e_time_val=0;
	e_table_val=0; e_table_row=0; e_table_cell=0;
	a_table_cell_column=0;	a_table_cell_val=0;
	a_apl_charact_val_table_val=0;
	a_table_row_items=0;
	a_apl_charact_val_aggr_val=0;

	e_apl_reference_value=0;
	a_apl_reference_val=0;
	e_apl_reference_unit=0;
	a_apl_reference_types=0; a_apl_reference_base=0; a_apl_reference_format=0;

	e_apl_charact_union_group = 0;
	a_apl_charact_union_group_id = 0;
	a_apl_charact_union_group_name =0;
	a_apl_charact_union_group_description = 0;
	a_apl_charact_union_group_content = 0;
	a_apl_charact_union_group_parent =0 ;

	e_apl_change_charact=0;
	e_apl_reference_comp_unit = 0;
	e_apl_reference_maint_unit = 0;
	e_apl_reference_proc_chart_unit = 0;

	a_apl_change_charact_old_val	= 0;
	a_apl_change_charact_new_val	= 0;
	a_apl_change_charact_charact	= 0;
	a_apl_change_charact_delta		= 0;
	a_apl_change_charact_type		= 0;
	a_apl_change_charact_basis		= 0;
}
//*************************************************************
CaplInstance *CaplCharacteristicManager::GetUnitById(const TCHAR * id)
{
	if (id==0)return 0;
	if (m_data==0)return 0;
	if (e_apl_unit==0) return 0;

	aplExtent ext;
	CaplAttrValue tst_value;

	tst_value.value.Set(id);
	tst_value.attr=a_apl_unit_id;
	m_data->NET_FindInstancesWithAttrValues(e_apl_unit,1,&tst_value,ext,false);
	if(ext.Size==0) return 0;
	
	CaplInstance *inst=ext[0];
	return inst;
}
//*************************************************************

CaplInstance *CaplCharacteristicManager::GetCharacteristicById(const TCHAR * id)
{
	if (id==0)return 0;
	if (m_data==0)return 0;
	if(e_apl_charact==0) return 0;

	aplExtent ext;
	CaplAttrValue tst_value;

	tst_value.value.Set(id);
	tst_value.attr=a_apl_charact_id;
	m_data->NET_FindInstancesWithAttrValues(e_apl_charact,1,&tst_value,ext,false);
	if(ext.Size==0) return 0;
	
	CaplInstance *inst=ext[0];
	return inst;
}

CaplInstance *CaplCharacteristicManager::GetCharacteristicBN(const TCHAR * name)
{
	if (name==0)return 0;
	if (m_data==0)return 0;
	if(e_apl_charact==0) return 0;

	aplExtent ext;
	CaplAttrValue tst_value;

	tst_value.value.Set(name);
	tst_value.attr=a_apl_charact_name;
	m_data->NET_FindInstancesWithAttrValues(e_apl_charact,1,&tst_value,ext,false);
	if(ext.Size==0) return 0;
	
	CaplInstance *inst=ext[0];
	return inst;
}
//*************************************************************
CaplInstance * CaplCharacteristicManager::GetInstCharacteristic
	(CaplInstance *inst,CaplInstance *characteristic)
{
	if (inst==0)return 0;
	if (inst->GetType()==0)return 0;
	if (m_data==0)return 0;
	if (characteristic==0)return 0;
	if (characteristic->GetType()==0)return 0;
	if(e_apl_charact==0) return 0;

	aplExtent ext_rel;
	CaplInstance *inst0;
	
	CaplAttrValue tst_values[2];
	tst_values[0].value.Set(inst);
	tst_values[0].attr=a_apl_charact_val_item;
	tst_values[1].value.Set(characteristic);
	tst_values[1].attr=a_apl_charact_val_charact;

	if(m_data->NET_FindInstancesWithAttrValues(e_apl_charact_value,2,&tst_values[0],ext_rel,false))
	{
		if(ext_rel.Size>0)
		{
			// Чтение из базы
			inst0=ext_rel[0];
			LoadCharacteristic(inst0);
			return inst0;
		}
	}
	return 0;
}
bool CaplCharacteristicManager::LoadCharacteristic(CaplInstance *val)
{
	if(m_data==0) return false;
	if(val==0) return false;
	if(val->GetType()==0) return false;
	if(val->GetAccessmode()>aplRO) return false;
	if(e_apl_charact==0) return false;
	
	aplExtent ext;
	ext.Add(val);
	return LoadCharacteristic(ext);
}

bool CaplCharacteristicManager::LoadCharacteristic(CaplAggr &aggr)
{
	if(m_data==0) return false;
	if(e_apl_charact==0) return false;
	
	aplExtent ext;
	for(int i=0;i<aggr.GetSize();i++)
	{
		CaplInstance *inst=0;
		aggr.GetByIndex(i,inst);
		if(!inst) continue;
		if(inst->GetAccessmode()>aplRO) continue;
		ext.Add(inst);
	}
	return LoadCharacteristic(ext);
}
//*************************************************************
bool CaplCharacteristicManager::LoadCharacteristic(aplExtent &ext,bool show_status_dlg)
{
	if(m_data==0) return false;
	if(e_apl_charact==0) return false;

	if(ext.GetSize()==0) return true;

	// Чтение из базы
	if(m_data->IsConnected())
	{
		CaplSetResourceHandle setres(module_inst);

		CDisAsmStatusDlg* dlg=0;
		if(show_status_dlg && m_api->m_data.m_IsWaitDlg) 
		{
			dlg= new CDisAsmStatusDlg;
			dlg->Create(IDD_DISASM_STATUS);
			dlg->m_name.SetWindowText( APL_T("Загружено атрибутов:"));
			dlg->ShowWindow(SW_SHOW);
		}
		CString buf;
		int all_l_count=0;

		int idx=0,i,j,n,z,l,u;

		CaplLoadData ld(m_data,DEF_SOURCE),ld_ver(m_data,DEF_SOURCE);
		bool load_val=false;
		bool load_val_ver=false;
		aplExtent ext_aggr_val;

		i=0;
		while(1)
		{
		    if(m_bContinue)
			{
				if(*m_bContinue==false) break;
			}
			if((idx==m_MaxItemsLoad)||(i>=ext.Size))
			{
				if(load_val)
				{
					//активная версия и локер
				  l=ld.AddQuery(_T('d'), 0, 0,a_apl_charact_val_lock_ver, true,true);
					ld.AddQuery(l,_T('d'), 0, 0,a_apl_charact_val_act_ver, true,true);
						ld.AddQuery(_T('d'), l, 0,a_apl_charact_val_ver_author, true,true);
						ld.AddQuery(_T('d'), l, 0,a_apl_charact_val_ver_char_value, true,true);
				  z=ld.AddQuery(_T('d'), l, 0,a_apl_reference_val_ver_val,true,true);
				  n=ld.AddQuery(_T('d'), l, 0,a_apl_charact_val_ver_table_val, true,true); 
				  j=ld.AddQuery(_T('d'), l, 0,a_apl_charact_val_ver_aggr_val, true,true);
						ld.AddQuery(_T('d'), j, 0,a_apl_charact_val_ver_aggr_val, true,true);
						ld.AddQuery(z,_T('d'), j, 0,a_apl_reference_val_ver_val,true,true);
						ld.AddQuery(n,_T('d'), j, 0,a_apl_charact_val_ver_table_val, true,true);
						// Содержимое таблиц
					  j=ld.AddQuery(_T('d'), n, 0,a_table_row_ver_items,   true,true);
								ld.AddQuery(_T('d'), j, 0,a_table_cell_ver_column, true,true);
							  u=ld.AddQuery(_T('d'), j, 0,a_table_cell_ver_val   , true,true); 
								  ld.AddQuery(_T('d'), u, 0,a_apl_charact_val_ver_aggr_val, true,true);
								  ld.AddQuery(z,_T('d'), u, 0,a_apl_reference_val_ver_val,true,true);
								  // Содержимое вложенных таблиц  
								  n=ld.AddQuery(_T('d'), u, 0,a_apl_charact_val_ver_table_val,   true,true);
									j=ld.AddQuery(_T('d'), n, 0,a_table_row_ver_items,   true,true);
											ld.AddQuery(_T('d'), j, 0,a_table_cell_ver_column, true,true);
										  u=ld.AddQuery(_T('d'), j, 0,a_table_cell_ver_val   , true,true);  
												ld.AddQuery(z,_T('d'), u, 0,a_apl_reference_val_ver_val,true,true);
												ld.AddQuery(_T('d'), u, 0,a_apl_charact_val_ver_aggr_val, true,true);

					// нулевой уровень
					ld.AddQuery(_T('d'), 0, 0,a_apl_charact_val_group, true,true);
					ld.AddQuery(z,_T('d'), 0, 0,a_apl_reference_val,true,true);			    //это ссылка нулевого уровня
				  n=ld.AddQuery(_T('d'), 0, 0,a_apl_charact_val_table_val, true,true);      //это таблица нулевого уровня
				  j=ld.AddQuery(_T('d'), 0, 0,a_apl_charact_val_aggr_val, true,true);	    //это аггр нулевого уровня
						ld.AddQuery(z,_T('d'), j, 0,a_apl_reference_val,true,true);		    //это ссылка первого уровня
						ld.AddQuery(_T('d'), j, 0,a_apl_charact_val_aggr_val, true,true);   //это аггр первого уровня в аггре
						ld.AddQuery(n,_T('d'), j, 0,a_apl_charact_val_table_val, true,true);//это таблица первого уровня в аггре
					
				  		// Содержимое таблиц (нулевого уровня и вложенных в аггр)
					  j=ld.AddQuery(_T('d'), n, 0,a_table_row_items,   true,true);
							ld.AddQuery(_T('d'), j, 0,a_table_cell_column, true,true);
						  u=ld.AddQuery(_T('d'), j, 0,a_table_cell_val   , true,true);	
								ld.AddQuery(z, _T('d'), u, 0,a_apl_reference_val,true,true);
								ld.AddQuery(_T('d'), u, 0,a_apl_charact_val_aggr_val, true,true);//это аггр первого уровня в таблице
								// Содержимое вложенных таблиц  
								n=ld.AddQuery(_T('d'), u, 0,a_apl_charact_val_table_val,   true,true);
								  j=ld.AddQuery(_T('d'), n, 0,a_table_row_items,   true,true);
										ld.AddQuery(_T('d'), j, 0,a_table_cell_column, true,true);
									  u=ld.AddQuery(_T('d'), j, 0,a_table_cell_val   , true,true);  
											ld.AddQuery(z,_T('d'), u, 0,a_apl_reference_val,true,true);
											ld.AddQuery(_T('d'), u, 0,a_apl_charact_val_aggr_val, true,true);//это аггр второго уровня в таблице в таблице

					ld.AddQuery(_T('d'), z, 0,m_api->m_prd_mgr.a_pdf_prd, true,true);
					ld.AddQuery(_T('d'), z, 0,m_api->m_doc_mgr.a_apl_doc_rev_doc, true,true);
					ld.LoadEx();
					ld.ClearQuery();
				}
				if(load_val_ver)
				{
					  ld_ver.AddQuery(_T('d'), 0, 0,a_apl_charact_val_ver_author, true,true);
					  ld_ver.AddQuery(_T('d'), 0, 0,a_apl_charact_val_ver_char_value, true,true);
					z=ld_ver.AddQuery(_T('d'), 0, 0,a_apl_reference_val_ver_val,true,true);
					n=ld_ver.AddQuery(_T('d'), 0, 0,a_apl_charact_val_ver_table_val, true,true);
					j=ld_ver.AddQuery(_T('d'), 0, 0,a_apl_charact_val_ver_aggr_val, true,true);
						ld_ver.AddQuery(z,_T('d'), j, 0,a_apl_reference_val_ver_val,true,true);
						ld_ver.AddQuery(_T('d'), j, 0,a_apl_charact_val_ver_aggr_val, true,true);
						ld_ver.AddQuery(n,_T('d'), j, 0,a_apl_charact_val_ver_table_val, true,true);
							// Содержимое таблиц
						  j=ld_ver.AddQuery(_T('d'), n, 0,a_table_row_ver_items,   true,true);
								ld_ver.AddQuery(_T('d'), j, 0,a_table_cell_ver_column, true,true);
							  u=ld_ver.AddQuery(_T('d'), j, 0,a_table_cell_ver_val   , true,true); 
								  ld_ver.AddQuery(_T('d'), u, 0,a_apl_charact_val_ver_aggr_val, true,true);
								  ld_ver.AddQuery(z,_T('d'), u, 0,a_apl_reference_val_ver_val,true,true);
								  // Содержимое вложенных таблиц  
								  n=ld_ver.AddQuery(_T('d'), u, 0,a_apl_charact_val_ver_table_val,   true,true);
									j=ld_ver.AddQuery(_T('d'), n, 0,a_table_row_ver_items,   true,true);
											ld_ver.AddQuery(_T('d'), j, 0,a_table_cell_ver_column, true,true);
										  u=ld_ver.AddQuery(_T('d'), j, 0,a_table_cell_ver_val   , true,true);  
												ld_ver.AddQuery(z,_T('d'), u, 0,a_apl_reference_val_ver_val,true,true);
												ld_ver.AddQuery(_T('d'), u, 0,a_apl_charact_val_ver_aggr_val, true,true);
					
					   // Ссылочные объекты
					  ld_ver.AddQuery(_T('d'), z, 0,m_api->m_prd_mgr.a_pdf_prd, true,true);
					  ld_ver.AddQuery(_T('d'), z, 0,m_api->m_doc_mgr.a_apl_doc_rev_doc, true,true);
					  ld_ver.LoadEx();
					  ld.ClearQuery();
				}
				all_l_count+=idx;
				if(dlg)
				{
					buf.Format(_T("%d"),int(((double)all_l_count/(double)ext.Size)*100));
					buf+=_T("%");
					dlg->m_count.SetWindowText(buf);	
				}	
				idx=0;
				load_val=false;
				load_val_ver=false;
			}
			if(i>=ext.Size) break;

			if(ext[i]==0) 
			{			
				i++;
				continue;
			}
			if(ext[i]->GetType()==0) 
			{			
				i++;
				continue;
			}
			if(ext[i]->GetId()==0) 
			{			
				i++;
				continue;
			}
			if(ext[i]->GetAccessmode()>aplRO) 
			{			
				i++;
				continue;
			}
			if(m_data->IsKindOf(ext[i],e_apl_charact_value))
			{
				if(ld.AddQuery(0,ext[i],true)!=-1)load_val=true;
			}
			else if(m_data->IsKindOf(ext[i],e_apl_charact_value_ver))
			{
				if(ld_ver.AddQuery(0,ext[i],true)!=-1)load_val_ver=true;
			}
			i++;
			idx++;

		}

		if(dlg)
		{
			dlg->ShowWindow(SW_HIDE);
			dlg->DestroyWindow();
			delete dlg;
		}
	}
	return true;
}

CaplInstance *CaplCharacteristicManager::FindCharacteristic(CaplInstance *item,CaplInstance *characreristic, CaplInstance *type,bool find_in_all_versions,bool load_from_bd)
{
	if (item==0)return 0;
	if (item->GetType()==0)return 0;
	if (characreristic==0)return 0;
	if (characreristic->GetType()==0)return 0;
	if (m_data==0)return 0;
	if(e_apl_charact_value==0) return 0;

	CaplInstance *val=0;
	{
		aplExtent ext;
		CaplAttrValue tst_value[3];
		tst_value[0].attr=a_apl_charact_val_charact;
		tst_value[0].value.Set(characreristic);
		tst_value[1].attr=a_apl_charact_val_item;
		tst_value[1].value.Set(item);
		tst_value[2].attr=a_apl_charact_val_type;
		tst_value[2].value.Set(type);
		if(item->GetId()!=0 && load_from_bd && m_data->IsDictLoad()){
			// Чтение из базы
			m_data->NET_FindInstancesWithAttrValues(e_apl_charact_value,3,&tst_value[0],ext,false);
		}else{
			// в локальном кеше
			m_data->FindInstancesWithAttrValuesInLocalCache(e_apl_charact_value,0,3,
				&tst_value[0],ext,false,false,false);
		}
		if(ext.Size>0) val=ext[0];
		if(ext.Size==0 && find_in_all_versions){
			tst_value[0].attr=a_apl_charact_val_charact;
			tst_value[0].value.Set(characreristic);
			tst_value[1].attr=a_apl_charact_val_base_item;
			tst_value[1].value.Set(item);
			tst_value[2].attr=a_apl_charact_val_type;
			tst_value[2].value.Set(type);
			if(item->GetId()!=0 && load_from_bd && m_data->IsDictLoad()){
				// Чтение из базы
				m_data->NET_FindInstancesWithAttrValues(e_apl_charact_value,3,&tst_value[0],ext,false);
			}else{
				// в локальном кеше
				m_data->FindInstancesWithAttrValuesInLocalCache(e_apl_charact_value,0,3,
					&tst_value[0],ext,false,false,false);
			}
			if(ext.Size>0) val=ext[0];
		}
	}
	return val;
}

//*************************************************************
bool CaplCharacteristicManager::DeleteAllAssociatedCharacteristic(CaplInstance *item)
{
	if(item==0) return false;
	if(item->GetType()==0) return false;
	if(item->GetAccessmode()>aplRO) return false;
	aplExtent out_ext,out_group;
	int i;

	FindAssociatedCharacteristic(item,out_ext,out_group,true,true,true,true);
	for(i=0;i<out_ext.GetSize();i++){
		DeleteCharacteristic(out_ext[i],true);
	}
	for(i=0;i<out_group.GetSize();i++){
		m_data->DeleteInstance(out_group[i]);
	}
	return true;
}

//*************************************************************
bool CaplCharacteristicManager::FindAssociatedCharacteristic(CaplInstance *inst, 
															 aplExtent &out_ext, aplExtent &out_group, 
															 bool load_table,bool find_in_all_versions,
															 bool from_base, bool with_system)
{
	out_ext.Clear();
	out_group.Clear();
	if(m_data==0) return false;
	if(inst==0) return false;
	if(inst->GetType()==0) return false;
	if(inst->GetAccessmode()>aplRO) return false;
	if(e_apl_charact==0) return false;

	int i;//,j,k,n,z;
	if(inst->GetId()!=0)
	{
		// Чтение из базы
		if(m_data->IsConnected() && from_base)
		{
			if(!m_data->IsKindOf(inst,m_api->m_bp_mgr.e_apl_bp_ver))
			{
				CaplLoadData ld(m_data,DEF_SOURCE);
				if(find_in_all_versions) i=ld.AddQuery(_T('b'), inst->GetId(), e_apl_charact_value,a_apl_charact_val_base_item, true,true);
				else					 i=ld.AddQuery(_T('b'), inst->GetId(), e_apl_charact_value,a_apl_charact_val_item, true,true);
				// Группы
				i=ld.AddQuery(_T('b'), inst->GetId(), e_charact_val_group,a_charact_val_group_item, true,true);
				ld.LoadEx();
			}

		}
	}
	aplExtent ext_ch_ref;
	CaplInstance *inst0;
	CaplAggr aggr;
	if(m_data->IsKindOf(inst,m_api->m_bp_mgr.e_apl_bp_ver)) 
	{
		m_data->GetAttr(inst,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
		for(int i=0;i<aggr.GetSize();i++)
		{
			aggr.GetByIndex(i,inst0);
			ext_ch_ref.Add(inst0);
		}
	}
	else
		m_data->GetEntityExtent(e_apl_charact_value,ext_ch_ref);
	
	CaplInstance* charact;
	bool bSystem;
	
	for(i=0;i<ext_ch_ref.Size;i++)
	{
		if(ext_ch_ref[i]->GetAccessmode()>aplRO) continue;
		if(!ext_ch_ref[i]->GetType()) continue;
		if(!m_data->IsKindOf(ext_ch_ref[i],e_apl_charact_value_ver)) 
		{
			if(find_in_all_versions) m_data->GetAttr(ext_ch_ref[i],a_apl_charact_val_base_item,inst0);
			else m_data->GetAttr(ext_ch_ref[i],a_apl_charact_val_item,inst0);
		}
		if(inst==inst0 || m_data->IsKindOf(ext_ch_ref[i],e_apl_charact_value_ver))
		{
			if(!with_system)
			{
				bSystem= false;
				m_data->GetAttr(ext_ch_ref[i], a_apl_charact_val_charact, charact);
				if(charact)m_data->GetAttr(charact, a_apl_charact_system, bSystem);
				if(bSystem) continue;
			}
			out_ext.Add(ext_ch_ref[i]);
		}
	}
	if(m_data->IsConnected() && from_base) LoadCharacteristic(out_ext);
	m_data->GetEntityExtent(e_charact_val_group,ext_ch_ref);
	CaplInstance *item=inst;
	if(m_data->IsKindOf(inst,m_api->m_bp_mgr.e_apl_bp_ver)) 
	{
		m_data->GetAttr(inst,m_api->m_bp_mgr.a_bp_ver_bp,item);	
	}
	for(i=0;i<ext_ch_ref.Size;i++)
	{
		if(ext_ch_ref[i]->GetAccessmode()>aplRO) continue;
		m_data->GetAttr(ext_ch_ref[i],a_charact_val_group_item,inst0);
		if(item==inst0)out_group.Add(ext_ch_ref[i]);
	}
	return true;
}

bool CaplCharacteristicManager::FindAssociatedCharacteristic(aplExtent &ext, 
															 aplExtent &out_ext, aplExtent &out_group, 
															 bool load_table,bool find_in_all_versions,
															 bool show_status_dlg, bool from_base, 
															 bool with_system)
{
	out_ext.Clear();
	out_group.Clear();
	if(ext.GetSize()==0)return true;
	if(!m_data) return false;
	int i;
	if(m_data->IsConnected() && from_base)
	{
		CaplLoadData ld(m_data,DEF_SOURCE);
		bool b_load=false;
		int l_count=0;
		CString buf;
		
		CaplSetResourceHandle setres(module_inst);

		CDisAsmStatusDlg* dlg=0;
		if(show_status_dlg && m_api->m_data.m_IsWaitDlg) 
		{
			dlg= new CDisAsmStatusDlg;
			dlg->Create(IDD_DISASM_STATUS);
			dlg->m_name.SetWindowText( APL_T("Обработано:"));
			dlg->ShowWindow(SW_SHOW);
		}
		
		int all_l_count=0;
		for(i=0;i<ext.GetSize();i++)
		{
			if(m_bContinue)
			{
				if(*m_bContinue==false) break;
			}
			if(ext[i]) 
				if(ext[i]->GetId()) 
					if(ext[i]->GetAccessmode()<aplNO) 
					{
						l_count++;
						ld.AddQuery(0,ext[i]);
						b_load=true;
					}
			if((l_count==m_MaxItemsLoad || i==ext.GetSize()-1) && b_load)
			{
				if(find_in_all_versions) ld.AddQuery(_T('r'), 0, e_apl_charact_value,a_apl_charact_val_base_item, true,true);
				else					 ld.AddQuery(_T('r'), 0, e_apl_charact_value,a_apl_charact_val_item, true,true);
				// Группы
				ld.AddQuery(_T('r'), 0, e_charact_val_group,a_charact_val_group_item, true,true);
				ld.LoadEx();
				ld.ClearQuery();
				all_l_count+=l_count;
				if(dlg)
				{
					buf.Format(_T("%d"),int(((double)all_l_count/(double)ext.Size)*100));
					buf+=_T("%");
					dlg->m_count.SetWindowText(buf);	
				}
				l_count=0;
				b_load=false;

			}
		}
		if(dlg)
		{
			dlg->ShowWindow(SW_HIDE);
			dlg->DestroyWindow();
			delete dlg;
		}
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}
	aplExtent ext_ref,ext_group;
	m_data->GetEntityExtent(e_apl_charact_value,ext_ref);
	m_data->GetEntityExtent(e_charact_val_group,ext_group);
	CaplInstance *inst0;
	CaplAggr aggr;
	aplExtent ext0(ext.GetSize());
	int count=0;
	for(i=0;i<ext.GetSize();i++)
	{
		if(m_bContinue)
		{
			if(*m_bContinue==false) break;
		}
		if(!ext[i]) continue;if(!ext[i]->GetType()) continue;if(ext[i]->GetAccessmode()>aplRO) continue;
		if(m_data->IsKindOf(ext[i],m_api->m_bp_mgr.e_apl_bp_ver)) 
		{
			m_data->GetAttr(ext[i],m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			for(int i=0;i<aggr.GetSize();i++)
			{
				aggr.GetByIndex(i,inst0);
				out_ext.Add(inst0);
			}
		}
		else
		{
			ext0.SetAt(count,ext[i]);
			count++;
		}
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}
	CSortClass::SortExtentByInst(ext0);
	int num;
	
	CaplInstance* charact;
	bool bSystem;

	for(i=0;i<ext_ref.Size;i++)
	{
		if(ext_ref[i]->GetAccessmode()>aplRO) continue;
		if(find_in_all_versions)  m_data->GetAttr(ext_ref[i],a_apl_charact_val_base_item,inst0);
		else m_data->GetAttr(ext_ref[i],a_apl_charact_val_item,inst0);
		num=aplQFindInstInExtent(ext0,inst0);
		if(num>-1)
		{
			if(!with_system)
			{
				bSystem= false;
				m_data->GetAttr(ext_ref[i], a_apl_charact_val_charact, charact);
				if(charact)m_data->GetAttr(charact, a_apl_charact_system, bSystem);
				if(bSystem) continue;
			}

			out_ext.Add(ext_ref[i]);
		}
	}
	for(i=0;i<ext_group.Size;i++)
	{
		if(ext_group[i]->GetAccessmode()>aplRO) continue;
		m_data->GetAttr(ext_group[i],a_charact_val_group_item,inst0);
		num=aplQFindInstInExtent(ext0,inst0);
		if(num>-1) out_group.Add(ext_group[i]);
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}
	if(m_data->IsConnected() && from_base) LoadCharacteristic(out_ext,show_status_dlg);
	return true;
}
//*************************************************************
bool CaplCharacteristicManager::FindAssociatedCharacteristic(CaplInstance *inst, aplExtent &out_ext, bool load_table, bool find_in_all_versions, bool show_status_dlg, bool from_base, bool with_system)
{
	aplExtent gr, ext;
	ext.Add(inst);
	return FindAssociatedCharacteristic(ext, out_ext, gr, load_table, find_in_all_versions, show_status_dlg, from_base, with_system);
}
//*************************************************************
bool CaplCharacteristicManager::FindAssociatedCharacteristic(aplExtent &ext, aplExtent &out_ext, bool load_table, bool find_in_all_versions, bool show_status_dlg, bool from_base, bool with_system)
{
	aplExtent gr;
	return FindAssociatedCharacteristic(ext, out_ext, gr,load_table, find_in_all_versions, show_status_dlg, from_base, with_system);
}
//*************************************************************
bool CaplCharacteristicManager::FindAssociatedCharacteristics(aplExtent &ext, aplExtent &out_ext, bool bFromBase)
{
	out_ext.Clear();
	if(ext.GetSize()==0) return true;
	if(m_api==NULL) return false;
	if(m_api->m_data.IsConnected() && bFromBase)
	{
		int block_size, cnt, count;
		int i, j;
		CString buf;
		CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
		block_size = ext.GetSize() > m_MaxItemsLoad*1.5 ? m_MaxItemsLoad : ext.GetSize();
		block_size = block_size>0?block_size:m_MaxItemsLoad;
		cnt = (ext.GetSize()-1)/block_size+1;
		
		CaplSetResourceHandle setres(module_inst);

		CDisAsmStatusDlg* dlg=0;
		//Добавлено Даровских
		//А если всякие всплывающие диалоги показывать не надо, то не надо ничего выводить.
		if(cnt>5 && m_api->m_data.m_IsWaitDlg) // если больше 5 блоков, выводим диалог
		{
			dlg= new CDisAsmStatusDlg;
			dlg->Create(IDD_DISASM_STATUS);
			dlg->m_name.SetWindowText( APL_T("Обработано партий:"));
			buf.Format( APL_T("0 из %i"), cnt);
			dlg->m_count.SetWindowText(buf);	
			dlg->ShowWindow(SW_SHOW);
			dlg->BringWindowToTop();
		}

		for(i=0; i<cnt; i++)
		{
			count = (i+1)*block_size<ext.GetSize() ? block_size : ext.GetSize()-(i*block_size);
			for(j=0; j<count; j++)
			{
				if(ext[i*block_size+j]==NULL) continue;
				if(ext[i*block_size+j]->GetId()==0) continue;
				ld.AddQuery(0, ext[i*block_size+j]);
			}
			if(ld.m_queries.Size == 0) continue;
			ld.AddQuery(_T('r'), 0, e_apl_charact_value, a_apl_charact_val_item, true, true);
			
			if(dlg)
			{
				buf.Format( APL_T("%i из %i"), i+1, cnt);
				dlg->m_count.SetWindowText(buf);	
				dlg->BringWindowToTop();
			}
			
			ld.LoadEx();
			ld.ClearQuery();
		}

		if(dlg)
		{
			dlg->ShowWindow(SW_HIDE);
			dlg->DestroyWindow();
			delete dlg;		
		}
	}
	aplExtent charact_vals;
	int i;
	CaplInstance *item;
	
	ext.Sort();
	m_api->m_data.GetEntityExtent(e_apl_charact_value, charact_vals);
	for(i=0; i<charact_vals.GetSize(); i++)
	{
		if(charact_vals[i]->GetAccessmode()>aplRO) continue;

		m_api->m_data.GetAttr(charact_vals[i], a_apl_charact_val_item, item);
		if(aplQFindInstInExtent(ext, item, false)>-1)
			out_ext.Add(charact_vals[i]);
	}
	return true;
}
//*************************************************************
bool CaplCharacteristicManager::FindAssociatedCharacteristics(CaplInstance *inst, aplExtent &out_ext, bool bFromBase)
{
	aplExtent ext;
	ext.Add(inst);
	return FindAssociatedCharacteristics(ext, out_ext, bFromBase);
}
//*************************************************************
bool CaplCharacteristicManager::GetGroupContents(CaplInstance *group,aplExtent &ext_out)
{
	if(!group) return false;
	if(m_data==0) return false;
	if(!m_data->IsConnected()) return false;
	if(group->GetAccessmode()>aplRO) return false;
	ext_out.Clear();
	aplExtent ext0;
	CaplInstance *inst;
	CaplInstance *group_item=0;
	m_data->GetAttr(group,a_charact_val_group_item,group_item);
	CaplInstance *bp_lock=0;
	CaplAggr char_ver_aggr;
	if(group_item)
	{
		if(m_data->IsKindOf(group_item,m_api->m_bp_mgr.e_bp))
		{
			bp_lock=m_api->m_bp_mgr.CheckMyLock(group_item,false);
			if(bp_lock) m_data->GetAttr(bp_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,char_ver_aggr);
		}
	}
	m_data->GetEntityExtent(e_apl_charact_value,ext0);
	for(int i=0;i<ext0.Size;i++)
	{
		m_data->GetAttr(ext0[i],a_apl_charact_val_group,inst);
		CaplInstance *char_item=0;
		m_data->GetAttr(ext0[i],a_apl_charact_val_item,char_item);
		if(bp_lock)
		{
			if(inst==group)
			{
				bool found=false;
				for(int j=0;j<char_ver_aggr.GetSize();j++)
				{
					CaplInstance *inst0=0;
					char_ver_aggr.GetByIndex(j,inst0);
					CaplInstance *char_val=0;
					if(inst0) m_data->GetAttr(inst0,a_apl_charact_val_ver_char_value,char_val);
					if(char_val==ext0[i]) {found=true;break;}
				}
				if(found) ext_out.Add(ext0[i]);
			}
		}
		else
			if(inst==group && char_item==group_item)ext_out.Add(ext0[i]);
	}
	return true;
}

CaplInstance *CaplCharacteristicManager::GetCharacteristicType(const TCHAR * type)
{
	if (type==0)return 0;
	if (m_data==0)return 0;
	if(e_apl_charact_type==0) return 0;

	aplExtent ext;
	CaplAttrValue tst_value;

	tst_value.value.Set(type);
	tst_value.attr=a_apl_charact_type_name;
	m_data->NET_FindInstancesWithAttrValues(e_apl_charact_type,1,&tst_value,ext,false);
	if(ext.Size==0) return 0;
	
	CaplInstance *inst=ext[0];
	return inst;
}
//*************************************************************
CaplInstance *CaplCharacteristicManager::CreateDescriptiveCharacteristic(CaplInstance *item,CaplInstance *characreristic, CaplInstance *type, const TCHAR *value)
{
	if (item==0)return 0;
	if (item->GetType()==0)return 0;
	if (characreristic==0)return 0;
	if (characreristic->GetType()==0)return 0;
	if (m_data==0)return 0;
	if(e_apl_charact_value==0) return 0;

	CaplInstance *bp_lock=0,*my_lock=0;
	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp))
	{
		my_lock=m_api->m_bp_mgr.CheckMyLock(item,false);
		bp_lock=m_api->m_bp_mgr.GetLock(item,false);
		if(bp_lock && !my_lock)	
		{
			if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Бизнес-процесс уже взят на редактирование!"));
			return 0;
		}
	}
	
	CaplInstance *val= NULL;

	if(m_TestUnique) val= FindCharacteristic(item, characreristic, type);

	if(val==0) val=m_data->CreateInstance(e_descr_value);
	if(val==0) return 0;

	m_data->PutAttr(val,a_apl_charact_val_descr_val,value);

	m_data->PutAttr(val,a_apl_charact_val_item,item);
	m_data->PutAttr(val,a_apl_charact_val_type,type);
	m_data->PutAttr(val,a_apl_charact_val_charact,characreristic);
	CaplInstance *new_char_ver=CreateCharValVersion(val,_T("0"));

	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp) && new_char_ver)
	{
		CaplAggr aggr;
		if(!my_lock) 
		{
			aplExtent ext_char,ext_group;
			m_api->m_charact_mgr.FindAssociatedCharacteristic(item,ext_char,ext_group,true);
			my_lock=m_api->m_bp_mgr.CreateBPVersion(item);
		}
		if(my_lock)
		{
			m_data->PutAttr(new_char_ver,a_apl_charact_val_ver_item,my_lock);
			m_data->GetAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			aggr.Add(new_char_ver);
			m_data->PutAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			m_api->m_data.PutAttr(val,m_api->m_charact_mgr.a_apl_charact_val_lock_ver,new_char_ver);
			m_api->m_data.PutAttr(new_char_ver,m_api->m_charact_mgr.a_apl_charact_val_ver_is_changed,true);
		}
	}
	if(m_AutoSave){ m_api->SaveChanges();}
	if(val && m_AutoUsurpire)
	{
		int AutoUzurpire;
		m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Автоматически становиться владельцем\\Автоматически становиться владельцем создаваемых характеристик"),AutoUzurpire,0);
		if(AutoUzurpire==1) 
		{
			if(!m_AutoSave) m_api->SaveChanges();
			aplExtent ext; ext.Add(val);
			m_data->NET_BecomeInstancesOwner(&ext);
		}
	}
	return val;
}
//*************************************************************
CaplInstance *CaplCharacteristicManager::CreateMeasuredCharacteristic(CaplInstance *item,CaplInstance *characreristic, CaplInstance *type, double value, double max_dev,  double min_dev)
{
	if (item==0)return 0;
	if (item->GetType()==0)return 0;
	if (characreristic==0)return 0;
	if (characreristic->GetType()==0)return 0;
	if (m_data==0)return 0;
	if(e_apl_charact_value==0) return 0;

	CaplInstance *bp_lock=0,*my_lock=0;
	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp))
	{
		my_lock=m_api->m_bp_mgr.CheckMyLock(item,false);
		bp_lock=m_api->m_bp_mgr.GetLock(item,false);
		if(bp_lock && !my_lock)	
		{
			if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Бизнес-процесс уже взят на редактирование!"));
			return 0;
		}
	}

	CaplInstance *val= NULL;
	if(m_TestUnique)val= FindCharacteristic(item,characreristic,type);

	if(val==0) val=m_data->CreateInstance(e_meas_value);
	if(val==0) return 0;
	m_data->PutAttr(val,a_apl_charact_val_meas_val,value);
	m_data->PutAttr(val,a_apl_charact_val_meas_max,max_dev);
	m_data->PutAttr(val,a_apl_charact_val_meas_min,min_dev);

	m_data->PutAttr(val,a_apl_charact_val_item,item);
	m_data->PutAttr(val,a_apl_charact_val_type,type);
	m_data->PutAttr(val,a_apl_charact_val_charact,characreristic);
	CaplInstance *new_char_ver=CreateCharValVersion(val,_T("0"));

	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp) && new_char_ver)
	{
		CaplAggr aggr;
		if(!my_lock) 
		{
			aplExtent ext_char,ext_group;
			m_api->m_charact_mgr.FindAssociatedCharacteristic(item,ext_char,ext_group,true);
			my_lock=m_api->m_bp_mgr.CreateBPVersion(item);
		}
		if(my_lock)
		{
			m_data->PutAttr(new_char_ver,a_apl_charact_val_ver_item,my_lock);
			m_data->GetAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			aggr.Add(new_char_ver);
			m_data->PutAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			m_api->m_data.PutAttr(val,m_api->m_charact_mgr.a_apl_charact_val_lock_ver,new_char_ver);
			m_api->m_data.PutAttr(new_char_ver,m_api->m_charact_mgr.a_apl_charact_val_ver_is_changed,true);
		}
	}
	if(m_AutoSave){m_api->SaveChanges();}
	if(val && m_AutoUsurpire)
	{
		int AutoUzurpire;
		m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Автоматически становиться владельцем\\Автоматически становиться владельцем создаваемых характеристик"),AutoUzurpire,0);
		if(AutoUzurpire==1) 
		{
			if(!m_AutoSave) m_api->SaveChanges();
			aplExtent ext; ext.Add(val);
			m_data->NET_BecomeInstancesOwner(&ext);
		}
	}
	return val;
}
//*************************************************************
CaplInstance *CaplCharacteristicManager::CreateMonetaryCharacteristic(CaplInstance *item,CaplInstance *characreristic, CaplInstance *type, double value)
{
	if (item==0)return 0;
	if (item->GetType()==0)return 0;
	if (characreristic==0)return 0;
	if (characreristic->GetType()==0)return 0;
	if (m_data==0)return 0;
	if(e_apl_charact_value==0) return 0;

	CaplInstance *bp_lock=0,*my_lock=0;
	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp))
	{
		my_lock=m_api->m_bp_mgr.CheckMyLock(item,false);
		bp_lock=m_api->m_bp_mgr.GetLock(item,false);
		if(bp_lock && !my_lock)	
		{
			if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Бизнес-процесс уже взят на редактирование!"));
			return 0;
		}
	}

	CaplInstance *val= NULL;
	if(m_TestUnique) val= FindCharacteristic(item,characreristic,type);

	if(val==0) val=m_data->CreateInstance(e_monet_value);
	if(val==0) return 0;
	m_data->PutAttr(val,a_apl_charact_val_monet_val,value);

	m_data->PutAttr(val,a_apl_charact_val_item,item);
	m_data->PutAttr(val,a_apl_charact_val_type,type);
	m_data->PutAttr(val,a_apl_charact_val_charact,characreristic);
	CaplInstance *new_char_ver=CreateCharValVersion(val,_T("0"));

	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp) && new_char_ver)
	{
		CaplAggr aggr;
		if(!my_lock) 
		{
			aplExtent ext_char,ext_group;
			m_api->m_charact_mgr.FindAssociatedCharacteristic(item,ext_char,ext_group,true);
			my_lock=m_api->m_bp_mgr.CreateBPVersion(item);
		}
		if(my_lock)
		{
			m_data->PutAttr(new_char_ver,a_apl_charact_val_ver_item,my_lock);
			m_data->GetAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			aggr.Add(new_char_ver);
			m_data->PutAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			m_api->m_data.PutAttr(val,m_api->m_charact_mgr.a_apl_charact_val_lock_ver,new_char_ver);
			m_api->m_data.PutAttr(new_char_ver,m_api->m_charact_mgr.a_apl_charact_val_ver_is_changed,true);
		}
	}
	if(val && m_AutoUsurpire)
	{
		int AutoUzurpire;
		m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Автоматически становиться владельцем\\Автоматически становиться владельцем создаваемых характеристик"),AutoUzurpire,0);
		if(AutoUzurpire==1) 
		{
			if(!m_AutoSave) m_api->SaveChanges();
			aplExtent ext; ext.Add(val);
			m_data->NET_BecomeInstancesOwner(&ext);
		}
	}
	return val;
}
//*************************************************************
CaplInstance *CaplCharacteristicManager::CreateEnumerationCharacteristic(CaplInstance *item,CaplInstance *characreristic, CaplInstance *type, const TCHAR *value)
{
	if (item==0)return 0;
	if (item->GetType()==0)return 0;
	if (characreristic==0)return 0;
	if (characreristic->GetType()==0)return 0;
	if (m_data==0)return 0;
	if(e_apl_charact_value==0) return 0;

	CaplInstance *bp_lock=0,*my_lock=0;
	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp))
	{
		my_lock=m_api->m_bp_mgr.CheckMyLock(item,false);
		bp_lock=m_api->m_bp_mgr.GetLock(item,false);
		if(bp_lock && !my_lock)	
		{
			if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Бизнес-процесс уже взят на редактирование!"));
			return 0;
		}
	}

	CaplInstance *val= NULL;
	if(m_TestUnique) val= FindCharacteristic(item,characreristic,type);

	if(val==0) val=m_data->CreateInstance(e_enum_value);
	if(val==0) return 0;
	m_data->PutAttr(val,a_apl_charact_val_enum_val,value);

	m_data->PutAttr(val,a_apl_charact_val_item,item);
	m_data->PutAttr(val,a_apl_charact_val_type,type);
	m_data->PutAttr(val,a_apl_charact_val_charact,characreristic);
	CaplInstance *new_char_ver=CreateCharValVersion(val,_T("0"));

	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp) && new_char_ver)
	{
		CaplAggr aggr;
		if(!my_lock) 
		{
			aplExtent ext_char,ext_group;
			m_api->m_charact_mgr.FindAssociatedCharacteristic(item,ext_char,ext_group,true);
			my_lock=m_api->m_bp_mgr.CreateBPVersion(item);
		}
		if(my_lock)
		{
			m_data->PutAttr(new_char_ver,a_apl_charact_val_ver_item,my_lock);
			m_data->GetAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			aggr.Add(new_char_ver);
			m_data->PutAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			m_api->m_data.PutAttr(val,m_api->m_charact_mgr.a_apl_charact_val_lock_ver,new_char_ver);
			m_api->m_data.PutAttr(new_char_ver,m_api->m_charact_mgr.a_apl_charact_val_ver_is_changed,true);

		}
	}
	if(val && m_AutoUsurpire)
	{
		int AutoUzurpire;
		m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Автоматически становиться владельцем\\Автоматически становиться владельцем создаваемых характеристик"),AutoUzurpire,0);
		if(AutoUzurpire==1) 
		{
			if(!m_AutoSave) m_api->SaveChanges();
			aplExtent ext; ext.Add(val);
			m_data->NET_BecomeInstancesOwner(&ext);
		}
	}
	return val;
}
//*************************************************************
CaplInstance* CaplCharacteristicManager::CreateAggrCharacteristicValue(CaplInstance *item,CaplInstance *characreristic, CaplInstance *type, aplExtent& value)
{
	if (item==0)return 0;
	if (item->GetType()==0)return 0;
	if (characreristic==0)return 0;
	if (characreristic->GetType()==0)return 0;
	if (m_data==0)return 0;

	CaplInstance *bp_lock=0,*my_lock=0;
	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp))
	{
		my_lock=m_api->m_bp_mgr.CheckMyLock(item,false);
		bp_lock=m_api->m_bp_mgr.GetLock(item,false);
		if(bp_lock && !my_lock)	
		{
			if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Бизнес-процесс уже взят на редактирование!"));
			return 0;
		}
	}

	CaplInstance *nVal= NULL;
	if(m_TestUnique) nVal= FindCharacteristic(item,characreristic,type);
	if(nVal==0) nVal = m_data->CreateInstance(e_aggr_val);
	m_data->PutAttr(nVal,a_apl_charact_val_item,item);
	m_data->PutAttr(nVal,a_apl_charact_val_type,type);
	m_data->PutAttr(nVal,a_apl_charact_val_charact,characreristic);

	//Заполняем значениями
	CaplInstance* unit, *elem_type;
	m_data->GetAttr(characreristic, a_apl_charact_unit, unit);
	m_data->GetAttrBN(unit, _T("element_type"), elem_type);
	CaplInstance* val;
	CaplAggr Values;
	for(int i=0; i<value.Size; i++)
	{
		val = NULL;
		if(m_data->IsKindOf(elem_type, e_apl_reference_unit))
		{
			val=m_data->CreateInstance(e_apl_reference_value);
			m_data->PutAttr(val,a_apl_reference_val,value[i]);
			m_data->PutAttr(val,a_apl_charact_val_item, (CaplInstance*)0);
			m_data->PutAttr(val,a_apl_charact_val_type,type);
			m_data->PutAttr(val,a_apl_charact_val_charact,(CaplInstance*)0);
			m_data->PutAttr(val,a_apl_charact_val_unit, elem_type);
			CaplInstance *new_char_ver=CreateCharValVersion(val,_T("0"));
		}
		else {if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Не реализовано для данного типа объектов!"));}
		Values.Add(val);
	}
	m_data->PutAttrBN(nVal, _T("values"), Values);

	CaplInstance *new_char_ver=CreateCharValVersion(nVal,_T("0"));
	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp) && new_char_ver)
	{
		CaplAggr aggr;
		if(!my_lock) 
		{
			aplExtent ext_char,ext_group;
			m_api->m_charact_mgr.FindAssociatedCharacteristic(item,ext_char,ext_group,true);
			my_lock=m_api->m_bp_mgr.CreateBPVersion(item);
		}
		if(my_lock)
		{
			m_data->PutAttr(new_char_ver,a_apl_charact_val_ver_item,my_lock);
			m_data->GetAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			aggr.Add(new_char_ver);
			m_data->PutAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			m_api->m_data.PutAttr(val,m_api->m_charact_mgr.a_apl_charact_val_lock_ver,new_char_ver);
			m_api->m_data.PutAttr(new_char_ver,m_api->m_charact_mgr.a_apl_charact_val_ver_is_changed,true);
		}
	}
	
	return nVal;
}
//*************************************************************
CaplInstance *CaplCharacteristicManager::CreateDateTimeCharacteristic(CaplInstance *item,CaplInstance *characreristic, CaplInstance *type, COleDateTime &value)
{
	CString  buf;
	aplDate2String(value,buf);
	return CreateDateTimeCharacteristic(item,characreristic,type,buf);
}
//*************************************************************
CaplInstance *CaplCharacteristicManager::CreateDateTimeCharacteristic(CaplInstance *item,CaplInstance *characreristic, CaplInstance *type, const TCHAR *s_value)
{
	if (item==0)return 0;
	if (item->GetType()==0)return 0;
	if (characreristic==0)return 0;
	if (characreristic->GetType()==0)return 0;
	if (m_data==0)return 0;
	if(e_apl_charact_value==0) return 0;

	CaplInstance *bp_lock=0,*my_lock=0;
	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp))
	{
		my_lock=m_api->m_bp_mgr.CheckMyLock(item,false);
		bp_lock=m_api->m_bp_mgr.GetLock(item,false);
		if(bp_lock && !my_lock)	
		{
			if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Бизнес-процесс уже взят на редактирование!"));
			return 0;
		}
	}

	CaplInstance *val= NULL;
	if(m_TestUnique) val= FindCharacteristic(item,characreristic,type);

	if(val==0) val=m_data->CreateInstance(e_time_val);
	if(val==0) return 0;
	m_data->PutAttr(val,a_apl_charact_val_time_val_s,s_value);

	m_data->PutAttr(val,a_apl_charact_val_item,item);
	m_data->PutAttr(val,a_apl_charact_val_type,type);
	m_data->PutAttr(val,a_apl_charact_val_charact,characreristic);
	CaplInstance *new_char_ver=CreateCharValVersion(val,_T("0"));

	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp) && new_char_ver)
	{
		CaplAggr aggr;
		if(!my_lock) 
		{
			aplExtent ext_char,ext_group;
			m_api->m_charact_mgr.FindAssociatedCharacteristic(item,ext_char,ext_group,true);
			my_lock=m_api->m_bp_mgr.CreateBPVersion(item);
		}
		if(my_lock)
		{
			m_data->PutAttr(new_char_ver,a_apl_charact_val_ver_item,my_lock);
			m_data->GetAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			aggr.Add(new_char_ver);
			m_data->PutAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			m_api->m_data.PutAttr(val,m_api->m_charact_mgr.a_apl_charact_val_lock_ver,new_char_ver);
			m_api->m_data.PutAttr(new_char_ver,m_api->m_charact_mgr.a_apl_charact_val_ver_is_changed,true);
		}
	}
	if(val && m_AutoUsurpire)
	{
		int AutoUzurpire;
		m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Автоматически становиться владельцем\\Автоматически становиться владельцем создаваемых характеристик"),AutoUzurpire,0);
		if(AutoUzurpire==1) 
		{
			if(!m_AutoSave) m_api->SaveChanges();
			aplExtent ext; ext.Add(val);
			m_data->NET_BecomeInstancesOwner(&ext);
		}
	}

	return val;
}

//*************************************************************
CaplInstance *CaplCharacteristicManager::CreateReferenceCharacteristic(CaplInstance *item,CaplInstance *characreristic, CaplInstance *type, CaplInstance *value)
{
	if (item==0)return 0;
	if (item->GetType()==0)return 0;
	if (characreristic==0)return 0;
	if (characreristic->GetType()==0)return 0;
	if (m_data==0)return 0;
	if(e_apl_charact_value==0) return 0;

	CaplInstance *bp_lock=0,*my_lock=0;
	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp))
	{
		my_lock=m_api->m_bp_mgr.CheckMyLock(item,false);
		bp_lock=m_api->m_bp_mgr.GetLock(item,false);
		if(bp_lock && !my_lock)	
		{
			if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Бизнес-процесс уже взят на редактирование!"));
			return 0;
		}
	}

	CaplInstance *val= NULL;
	if(m_TestUnique) val= FindCharacteristic(item,characreristic,type);

	if(val==0) val=m_data->CreateInstance(e_apl_reference_value);
	if(val==0) return 0;
	m_data->PutAttr(val,a_apl_reference_val,value);

	m_data->PutAttr(val,a_apl_charact_val_item,item);
	m_data->PutAttr(val,a_apl_charact_val_type,type);
	m_data->PutAttr(val,a_apl_charact_val_charact,characreristic);
	CaplInstance *new_char_ver=CreateCharValVersion(val,_T("0"));

	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp) && new_char_ver)
	{
		CaplAggr aggr;
		if(!my_lock) 
		{
			aplExtent ext_char,ext_group;
			m_api->m_charact_mgr.FindAssociatedCharacteristic(item,ext_char,ext_group,true);
			my_lock=m_api->m_bp_mgr.CreateBPVersion(item);
		}
		if(my_lock)
		{
			m_data->PutAttr(new_char_ver,a_apl_charact_val_ver_item,my_lock);
			m_data->GetAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			aggr.Add(new_char_ver);
			m_data->PutAttr(my_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
			m_api->m_data.PutAttr(val,m_api->m_charact_mgr.a_apl_charact_val_lock_ver,new_char_ver);
			m_api->m_data.PutAttr(new_char_ver,m_api->m_charact_mgr.a_apl_charact_val_ver_is_changed,true);

		}
	}
	if(val && m_AutoUsurpire)
	{
		int AutoUzurpire;
		m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Автоматически становиться владельцем\\Автоматически становиться владельцем создаваемых характеристик"),AutoUzurpire,0);
		if(AutoUzurpire==1) 
		{
			if(!m_AutoSave) m_api->SaveChanges();
			aplExtent ext; ext.Add(val);
			m_data->NET_BecomeInstancesOwner(&ext);
		}
	}
	return val;
}
//*************************************************************
bool CaplCharacteristicManager::GetUnitName(CaplInstance *unit, CString &buf, bool bAlwaysReturnName)
{
	buf=_T("");
	if(m_data==0) return false;
	if(unit==0) return false;

	CString buf1;
	if(!m_api->m_show.m_show_charactId_or_name && !bAlwaysReturnName)
		m_data->GetAttr(unit,a_apl_unit_id,buf);
	else
	{
		m_data->GetAttr(unit,a_apl_unit_name,buf);

		if(m_data->IsKindOf(unit,e_apl_si_unit))
		{
			if(0==si_unit_name_ISO_map.GetSize()) init_si_name_map();
			buf1=buf;
			CString sTmp;
			m_data->GetAttr(unit,a_apl_unit_prefix,buf);
			if(!buf.IsEmpty())
			{
				//TCHAR *rus_pref=(TCHAR*)si_prefix_ISO_map.GetP(buf);
				//if(rus_pref!=0) buf=rus_pref;
				sTmp=si_prefix_ISO_map.Get(buf,true);
				if(sTmp!=_T("")) buf=sTmp;
			}
			//TCHAR *rus_name=(TCHAR*)si_unit_name_ISO_map.GetP(buf1);
			//if(rus_name!=0) buf+=rus_name; else buf+=buf1;
			sTmp=si_unit_name_ISO_map.Get(buf1);
			if(sTmp!=_T("")) buf+=sTmp; else buf+=buf1;
			
			/*int i;
			for(i=0;i<56;i+=2)
			{
				if(buf==si_unit_name_ISO[i])
				{
					buf=si_unit_name_ISO[i+1];
					break;
				}
			}
			
			m_data->GetAttrBN(unit,S::prefix,buf1);
			for(i=0;i<32;i+=2)
			{
				if(buf1==si_prefix_ISO[i])
				{
					buf1=si_prefix_ISO[i+1];
					break;
				}
			}
			buf1+=buf;buf=buf1;
			*/
		}
	}
	return true;
}
//*************************************************************
bool CaplCharacteristicManager::AppendExtReferenceValues(CaplInstance *val, aplExtent &ext)
{
	if(m_data==0) return false;
	if(val==0) return false;
	if(val->GetType()==0) return false;
	if(val->GetAccessmode()>aplRO) return false;
	
	CaplInstance *inst,*inst1;
	if(m_data->IsKindOf(val,e_apl_reference_value))
	{
		m_data->GetAttr(val,a_apl_reference_val,inst1);
		if(inst1!=0)ext.Add(inst1);
	}	
	else if(m_data->IsKindOf(val,e_aggr_val))
	{
		CaplAggr aggr0;
		m_data->GetAttr(val,a_apl_charact_val_aggr_val,aggr0);
		for(int i11=0;i11<aggr0.GetSize();i11++)
		{
			aggr0.GetByIndex(i11,inst);
			if(inst!=0) AppendExtReferenceValues( inst,ext);
		}
	}
	else if(m_data->IsKindOf(val,e_table_val))
	{
		CaplAggr aggr0;
		m_data->GetAttr(val,a_apl_charact_val_table_val,aggr0);
		for(int i11=0;i11<aggr0.GetSize();i11++)
		{
			aggr0.GetByIndex(i11,inst);
			if(inst!=0)
			{
				//ext.Add(inst);
				AppendExtReferenceValues( inst,ext);
			}
		}
	}
	else if(m_data->IsKindOf(val,e_table_row))
	{
		CaplAggr aggr0;
		m_data->GetAttr(val,a_table_row_items,aggr0);
		for(int i11=0;i11<aggr0.GetSize();i11++)
		{
			aggr0.GetByIndex(i11,inst);
			if(inst!=0)
			{
				CaplInstance *cell;
				m_data->GetAttr(inst,a_table_cell_val,cell);
				if(cell!=0) AppendExtReferenceValues( cell,ext);
			}
		}
	}
	return true;
}
//*************************************************************
bool CaplCharacteristicManager::CheckOutGroup(CaplInstance *group)
{
	if(!group) return false;
	if(group->GetAccessmode()>aplRO) return false;
	if(!m_data->IsKindOf(group,e_charact_val_group)) return false;
	CaplInstance *group_item=0;
	m_data->GetAttr(group,a_charact_val_group_item,group_item);
	if(!group_item) return false;
	if(m_data->IsKindOf(group_item,m_api->m_bp_mgr.e_bp))
	{
		if(m_api->m_bp_mgr.GetLock(group_item,false)) return false;
		m_api->m_bp_mgr.CheckOutWithRequest(group_item);
		if(!m_api->m_bp_mgr.CheckMyLock(group_item,false)) return false;
	}
	else
	{
		aplExtent ext;
		GetGroupContents(group,ext);
		for(int i=0;i<ext.GetSize();i++)
			if(!GetLock(ext[i],false)) CheckOut(ext[i]);
	}
	return true;
}
//*************************************************************
bool CaplCharacteristicManager::CheckInGroup(CaplInstance *group)
{
	if(!group) return false;
	if(group->GetAccessmode()>aplRO) return false;
	if(!m_data->IsKindOf(group,e_charact_val_group)) return false;
	CaplInstance *group_item=0;
	m_data->GetAttr(group,a_charact_val_group_item,group_item);
	if(!group_item) return false;
	if(m_data->IsKindOf(group_item,m_api->m_bp_mgr.e_bp))
	{
		if(!m_api->m_bp_mgr.CheckMyLock(group_item,false)) return false;
		m_api->m_bp_mgr.CheckInWithRequest(group_item);
		if(m_api->m_bp_mgr.CheckMyLock(group_item,false)) return false;
	}
	else
	{
		aplExtent ext;
		GetGroupContents(group,ext);
		for(int i=0;i<ext.GetSize();i++)
			if(CheckMyLock(ext[i],false)) CheckIn(ext[i]);
	}
	return true;
}
//*************************************************************
bool CaplCharacteristicManager::UndoCheckOutGroup(CaplInstance *group,bool ask_before_undo)
{
	if(!group) return false;
	if(group->GetAccessmode()>aplRO) return false;
	if(!m_data->IsKindOf(group,e_charact_val_group)) return false;
	CaplInstance *group_item=0;
	m_data->GetAttr(group,a_charact_val_group_item,group_item);
	if(!group_item) return false;
	if(m_data->IsKindOf(group_item,m_api->m_bp_mgr.e_bp))
	{
		if(!m_api->m_bp_mgr.CheckMyLock(group_item,false)) return false;
		m_api->m_bp_mgr.UndoCheckOutWithRequest(group_item);
		if(m_api->m_bp_mgr.CheckMyLock(group_item,false)) return false;
	}
	else
	{
		if(ask_before_undo && m_api->m_ModeInteractive)
			if(IDNO==AfxMessageBox( APL_T("Вы действительно хотите отменить редактирование ?"), MB_YESNO|MB_ICONQUESTION)) return false;
		aplExtent ext;
		GetGroupContents(group,ext);
		for(int i=0;i<ext.GetSize();i++)
			if(CheckMyLock(ext[i],false)) UndoCheckOut(ext[i],false);
	}
	return true;
}
//*************************************************************
bool CaplCharacteristicManager::PrintCharacteristicValue(CaplInstance *val,CaplInstance *unit,CString &buf, bool full_print)
{
	buf=_T("");
	if(m_data==0) return false;
	if(m_api==0) return false;
	if(val==0) return false;
	if(val->GetType()==0) return false;
	if(val->GetAccessmode()>aplRO) return false;
	
	if(!m_api->m_show.m_charact_value) return true;
	if(!m_api->m_show.m_charact_unit) unit = 0;
	if(m_data->IsKindOf(val,e_apl_charact_value) && m_bUseVersions)
	{
		CaplInstance *lock=CheckMyLock(val,false);
		if(lock) val=lock;
	}

	if(m_data->IsKindOf(val,e_meas_value))
	{
		double rval;
		CString buf1, sval;
		m_data->GetAttr(val, a_apl_charact_val_meas_val, rval);

		sval.Format(_T("%f"), rval);
		sval.TrimRight(_T('0'));
		sval.TrimRight(_T('.'));		
		sval.TrimRight(_T(','));

		GetUnitName(unit,buf1);		
		buf.Format(_T("%s %s"), sval, LPCTSTR(buf1));
	}
	else if(m_data->IsKindOf(val,e_descr_value)) 
		m_data->GetAttr(val,a_apl_charact_val_descr_val,buf);
	else if(m_data->IsKindOf(val,e_enum_value))
		m_data->GetAttr(val,a_apl_charact_val_enum_val,buf);
	else if(m_data->IsKindOf(val,e_monet_value))
	{
		double rval=0;
		CString buf1, sval;
		m_data->GetAttr(val,a_apl_charact_val_monet_val,rval);

		sval.Format(_T("%f"), rval);
		sval.TrimRight(_T('0'));
		sval.TrimRight(_T('.'));	
		sval.TrimRight(_T(','));

		GetUnitName(unit,buf1);		
		buf.Format(_T("%s %s"), sval, LPCTSTR(buf1));
	}
	else if(m_data->IsKindOf(val,e_time_val))
	{
		COleDateTime odt;
		CString buf1;
		CaplInstance *inst1=0;
		m_data->GetAttr(val,a_apl_charact_val_time_val_s,buf1);
		if(aplString2Date(buf1,odt)) buf=odt.Format(_T("%d.%m.%Y  %H:%M:%S"));
	}	
	else if(m_data->IsKindOf(val,e_apl_reference_value))
	{
		//if(full_print)
		{
			CaplInstance *inst1=0;
			m_data->GetAttr(val,a_apl_reference_val,inst1);
			if(inst1!=0) 
			{
				CaplInstance *unit_val= 0;
				CString format;
//				m_data->GetAttr(val,a_apl_charact_val_unit,unit_val);
				if(unit_val!=0)m_data->GetAttr(unit_val,a_apl_reference_format,format);
				if(format==_T(""))GetItemName(inst1,buf);
				else
				{
					CaplInstance *main_inst,*ver;
					CString buf_tmp;
					if(m_data->IsKindOfBN(inst1,S::pdf))
					{
						ver=inst1;
						m_data->GetAttrBN(inst1,S::of_product,main_inst);
					}
					else if(m_data->IsKindOfBN(inst1,S::apl_document_revision))
					{
						ver=inst1;
						m_data->GetAttrBN(inst1,S::of_document,main_inst);
					}
					else if(m_data->IsKindOf(inst1,m_api->m_prd_inst_mgr.e_prd_inst))
					{
						m_api->m_prd_inst_mgr.LoadPrdInstInfo(inst1);
						CaplInstance *pdf;
						m_data->GetAttr(inst1,m_api->m_prd_inst_mgr.a_prd_inst_pdf,pdf);
						m_api->m_prd_mgr.LoadPrdInfo(pdf);
						m_api->GetItemName(inst1,format);
						main_inst = 0;
						ver = 0;
					}
					else { main_inst=inst1; ver=0;}

					if(main_inst!=0)
					{
						if(main_inst->GetType()!=0)
						{
							if(format.Find(_T("%id%"))>=0)
							{
								CaplAttr *attr=m_data->GetAttrDefinition(main_inst->GetType(),_T("id"));
								if(attr!=0)
								{
									m_data->GetAttr(main_inst,attr,buf_tmp);
									format.Replace(_T("%id%"),buf_tmp);
								}
								else format.Replace(_T("%id%"),_T(""));
							}
							if(format.Find(_T("%name%"))>=0)
							{
								if(m_data->IsKindOf(main_inst, m_api->m_appr_mgr.e_person))
									m_api->m_appr_mgr.GetPersonName(main_inst, buf_tmp);
								else
									m_data->GetAttrBN(main_inst,_T("name"),buf_tmp);
								format.Replace(_T("%name%"),buf_tmp);
							}
						}
					}
					if(ver!=0)
					{
						if(format.Find(_T("%ver%"))>=0)
						{
							m_data->GetAttrBN(ver,_T("id"),buf_tmp);
							format.Replace(_T("%ver%"),buf_tmp);
						}
					} else format.Replace(_T("%ver%"),_T(""));
					buf=format;
				}
			}
			else buf=_T("NULL");
		}
		//else buf=_T("REF");
	}	
	else if(m_data->IsKindOf(val,e_aggr_val))
	{
		CaplAggr aggr0;
		m_data->GetAttr(val,a_apl_charact_val_aggr_val,aggr0);
		if(full_print)
		{
			buf=_T("( ");
			CString buf1;
			for(int i11=0;i11<aggr0.GetSize();i11++)
			{
				buf1=_T("?");
				CaplInstance *inst=0;
				aggr0.GetByIndex(i11,inst);
				if(inst!=0)
				{
					if(inst==val) buf1=_T("@");
					else PrintCharacteristicValue( inst,0,buf1);
					if(i11!=0) buf+=_T(", ");
					buf+=buf1;
				}
			}
			buf+=_T(" )");
		}
		else buf.Format( APL_T("%i строк"),aggr0.GetSize());
	}
	else if(m_data->IsKindOf(val,e_table_val))
	{
		CaplAggr aggr0;
		m_data->GetAttr(val,a_apl_charact_val_table_val,aggr0);
		if(full_print)
		{
			buf=_T("( ");
			CString buf1;
			for(int i11=0;i11<aggr0.GetSize();i11++)
			{
				buf1=_T("?");
				CaplInstance *inst=0;
				aggr0.GetByIndex(i11,inst);
				if(inst!=0)
				{
					if(inst==val) buf1=_T("@");
					else PrintCharacteristicValue( inst,0,buf1);
					if(i11!=0) buf+=_T(", ");
					buf+=buf1;
				}
			}
			buf+=_T(" )");
		}

		else buf.Format( APL_T("%i строк"),aggr0.GetSize());
	}
	else if(m_data->IsKindOf(val,e_table_row))
	{
		buf=_T("( ");
		CaplAggr aggr0;
		m_data->GetAttr(val,a_table_row_items,aggr0);
		CString buf1;
		for(int i11=0;i11<aggr0.GetSize();i11++)
		{
			buf1=_T("?");
			CaplInstance *inst=0;
			aggr0.GetByIndex(i11,inst);
			if(inst!=0)
			{
				CaplInstance *cell;
				m_data->GetAttr(inst,a_table_cell_val,cell);
				if(cell) PrintCharacteristicValue( cell,0,buf1);
				if(i11!=0) buf+=_T(", ");
				buf+=buf1;
			}
		}
		buf+=_T(" )");
	}
	else if(m_data->IsKindOf(val,e_meas_value_ver))
	{
		double rval= 0;
		CString buf1, sval;
		m_data->GetAttr(val,a_apl_charact_val_ver_meas_val,rval);

		sval.Format(_T("%f"), rval);
		sval.TrimRight(_T('0'));
		sval.TrimRight(_T('.'));		
		sval.TrimRight(_T(','));
		
		GetUnitName(unit,buf1);		
		buf.Format(_T("%s %s"), sval, LPCTSTR(buf1));
	}
	else if(m_data->IsKindOf(val,e_descr_value_ver)) 
		m_data->GetAttr(val,a_apl_charact_val_ver_descr_val,buf);
	else if(m_data->IsKindOf(val,e_enum_value_ver))
		m_data->GetAttr(val,a_apl_charact_val_ver_enum_val,buf);
	else if(m_data->IsKindOf(val,e_monet_value_ver))
	{
		double rval=0;
		CString buf1, sval;
		m_data->GetAttr(val,a_apl_charact_val_ver_monet_val,rval);

		sval.Format(_T("%f"), rval);
		sval.TrimRight(_T('0'));
		sval.TrimRight(_T('.'));
		sval.TrimRight(_T(','));

		GetUnitName(unit,buf1);		
		buf.Format(_T("%s %s"), sval, LPCTSTR(buf1));
	}
	else if(m_data->IsKindOf(val,e_time_val_ver))
	{
		COleDateTime odt;
		CString buf1;
		CaplInstance *inst1=0;
		m_data->GetAttr(val,a_apl_charact_val_ver_time_val_s,buf1);
		if(aplString2Date(buf1,odt)) buf=odt.Format(_T("%d.%m.%Y  %H:%M:%S"));
	}	
	else if(m_data->IsKindOf(val,e_apl_reference_value_ver))
	{
		//if(full_print)
		{
			CaplInstance *inst1=0;
			m_data->GetAttr(val,a_apl_reference_val_ver_val,inst1);
			if(inst1!=0) 
			{
				CaplInstance *unit_val=0;
				CString format;
				//m_data->GetAttr(val,a_apl_charact_ver_val_unit,unit_val);
				if(unit_val!=0)m_data->GetAttr(unit_val,a_apl_reference_format,format);
				if(format==_T(""))GetItemName(inst1,buf);
				else
				{
					CaplInstance *main_inst,*ver;
					CString buf_tmp;
					if(m_data->IsKindOfBN(inst1,S::pdf))
					{
						ver=inst1;
						m_data->GetAttrBN(inst1,S::of_product,main_inst);
					}
					else if(m_data->IsKindOfBN(inst1,S::apl_document_revision))
					{
						ver=inst1;
						m_data->GetAttrBN(inst1,S::of_document,main_inst);
					}
					else { main_inst=inst1; ver=0;}

					if(main_inst!=0)
					{
						if(main_inst->GetType()!=0)
						{
							if(format.Find(_T("%id%"))>=0)
							{
								CaplAttr *attr=m_data->GetAttrDefinition(main_inst->GetType(),_T("id"));
								if(attr!=0)
								{
									m_data->GetAttr(main_inst,attr,buf_tmp);
									format.Replace(_T("%id%"),buf_tmp);
								}
								else format.Replace(_T("%id%"),_T(""));
							}
							if(format.Find(_T("%name%"))>=0)
							{
								if(m_data->IsKindOf(main_inst, m_api->m_appr_mgr.e_person))
									m_api->m_appr_mgr.GetPersonName(main_inst, buf_tmp);
								else
									m_data->GetAttrBN(main_inst,_T("name"),buf_tmp);
								format.Replace(_T("%name%"),buf_tmp);
							}
						}
					}
					if(ver!=0)
					{
						if(format.Find(_T("%ver%"))>=0)
						{
							m_data->GetAttrBN(ver,_T("id"),buf_tmp);
							format.Replace(_T("%ver%"),buf_tmp);
						}
					} else format.Replace(_T("%ver%"),_T(""));
					buf=format;
				}
			}
			else buf=_T("NULL");
		}
		//else buf=_T("REF");
	}
	else if(m_data->IsKindOf(val,e_aggr_val_ver))
	{
		CaplAggr aggr0;
		m_data->GetAttr(val,a_apl_charact_val_ver_aggr_val,aggr0);
		if(full_print)
		{
			buf=_T("( ");
			CString buf1;
			for(int i11=0;i11<aggr0.GetSize();i11++)
			{
				buf1=_T("?");
				CaplInstance *inst=0;
				aggr0.GetByIndex(i11,inst);
				if(inst!=0)
				{
					if(inst==val) buf1=_T("@");
					else PrintCharacteristicValue( inst,0,buf1);
					if(i11!=0) buf+=_T(", ");
					buf+=buf1;
				}
			}
			buf+=_T(" )");
		}
		else buf.Format( APL_T("%i строк"),aggr0.GetSize());
	}
	else if(m_data->IsKindOf(val,e_table_val_ver))
	{
		CaplAggr aggr0;
		m_data->GetAttr(val,a_apl_charact_val_ver_table_val,aggr0);
		if(full_print)
		{
			buf=_T("( ");
			CString buf1;
			for(int i11=0;i11<aggr0.GetSize();i11++)
			{
				buf1=_T("?");
				CaplInstance *inst=0;
				aggr0.GetByIndex(i11,inst);
				if(inst!=0)
				{
					if(inst==val) buf1=_T("@");
					else PrintCharacteristicValue( inst,0,buf1);
					if(i11!=0) buf+=_T(", ");
					buf+=buf1;
				}
			}
			buf+=_T(" )");
		}

		else buf.Format( APL_T("%i строк"),aggr0.GetSize());
	}
	else if(m_data->IsKindOf(val,e_table_row_ver))
	{
		buf=_T("( ");
		CaplAggr aggr0;
		m_data->GetAttr(val,a_table_row_ver_items,aggr0);
		CString buf1;
		for(int i11=0;i11<aggr0.GetSize();i11++)
		{
			buf1=_T("?");
			CaplInstance *inst=0;
			aggr0.GetByIndex(i11,inst);
			if(inst!=0)
			{
				CaplInstance *cell;
				m_data->GetAttr(inst,a_table_cell_ver_val,cell);
				if(cell) PrintCharacteristicValue( cell,0,buf1);
				if(i11!=0) buf+=_T(", ");
				buf+=buf1;
			}
		}
		buf+=_T(" )");
	}
	return true;
}

//*************************************************************
bool CaplCharacteristicManager::CreateCharacteristic(CaplInstance *item,
													 CaplInstance *base_val,
													 CaplInstance **val,
													 CaplInstance *new_charact,
													 CaplInstance **val_ver,
													 bool check_out,
													 CaplInstance *group,
													 bool show_dlg,
													 CaplInstance *new_type)
{
	CCharacteristicDlg dlg;

	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	if(item==0) return 0;
	if(item->GetType()==0) return 0;
	if(item->GetAccessmode()>aplRO)
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),item);
		return 0;
	}
	if(base_val!=0) LoadCharacteristic(base_val);
	
	CaplInstance *bp_lock=0,*inst=0;
	if(m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp) && m_bUseVersions)
	{
		if(!m_api->m_bp_mgr.CheckMyLockAndCheckOut(item))
			return false;
		bp_lock=m_api->m_bp_mgr.CheckMyLock(item,false);
		if(!bp_lock) return false;
	}
/*#ifdef _DEBUG	Вроде как не надо
	//Колесников
	CaplInstance *doc_lock=0;
	if(m_data->IsKindOf(item,m_api->m_doc_mgr.e_doc) && m_bUseVersions)
	{
		m_api->m_data.GetAttr(item, m_api->m_doc_mgr.a_apl_doc_lock,doc_lock);
		if(!doc_lock) m_api->m_doc_mgr.CheckOut(item,_T(""));
		m_api->m_data.GetAttr(item, m_api->m_doc_mgr.a_apl_doc_lock,doc_lock);
		if(!doc_lock) return false;
	}

#endif*/

	int num=0;
	CString buf=_T("");
	CaplInstance *nValue=0, *zero_ver=0;
	BOOL m_bAutoCheckIn= TRUE;

	if(!show_dlg && base_val)
	{
		CaplInstance *lock=CheckMyLock(base_val,false);
		if(lock) nValue=CopyValVersionToVal(lock); 
		else nValue=CreateCopyCharacteristicVal(base_val);

		if(nValue)
		{
			m_data->PutAttr(nValue,a_apl_charact_val_item,item);
			if(group) m_data->PutAttr(nValue,a_apl_charact_val_group,group);
			m_data->GetAttrBN(base_val,_T("unit"),inst);
			if(inst)m_data->PutAttrBN(nValue,_T("unit"),inst);
		}
	
	}
	else
	{
		CaplSetResourceHandle setres(module_inst);

		dlg.m_api=m_api;
		dlg.m_mode=_T("Create");
		dlg.m_item=item;
		dlg.m_base_val=base_val;
		dlg.m_charactteristic=new_charact;
		if(new_type!=(CaplInstance*)-1){
			dlg.m_new_type=new_type;
			dlg.m_locked_type=true;
		}
		dlg.m_sel_charact_names.Append(m_sel_charact_names);
		if(dlg.DoModal()==IDOK)
		{
			nValue=dlg.m_value;
			m_bAutoCheckIn= dlg.m_auto_checkin;
		}
	}
	CaplInstance *lock=0;
	if(nValue)
	{
		if(m_bUseVersions) 
		{
			zero_ver = CreateCharValVersion(nValue,_T("0"),false);
			if(zero_ver)
			{
				m_data->PutAttr(zero_ver,a_apl_charact_val_ver_is_changed,true);
				m_data->PutAttr(nValue,a_apl_charact_val_act_ver,zero_ver);
				m_data->PutAttr(nValue,a_apl_charact_val_lock_ver,zero_ver);
			}
		}
	}
	if(bp_lock && zero_ver) 
	{
		CaplAggr aggr;
		m_data->PutAttr(zero_ver,a_apl_charact_val_ver_item,bp_lock);
		m_data->GetAttr(bp_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
		aggr.Add(zero_ver);
		m_data->PutAttr(bp_lock,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr);
	}
//#ifdef _DEBUG
	//Колесников - ACAD

	if(m_data->IsKindOf(item,m_api->m_doc_mgr.e_doc) && m_bUseVersions)
	{
		CaplInstance *doc_lock=0;
		m_api->m_data.GetAttr(item, m_api->m_doc_mgr.a_apl_doc_lock,doc_lock);
		if(doc_lock && zero_ver) 
		{
			aplExtent aggr;
			m_data->GetAttr(doc_lock,m_api->m_doc_mgr.a_apl_doc_rev_char_val_versions,aggr);
			aggr.Add(zero_ver);
			m_data->PutAttr(doc_lock,m_api->m_doc_mgr.a_apl_doc_rev_char_val_versions,aggr);
		}
//		m_api->m_data.PutAttr(nValue, a_apl_charact_val_base_item, item);
	}
//#endif
	if(m_bAutoCheckIn)
	{
		if(bp_lock)
		{
			CaplInstance* process= NULL;
			m_api->m_data.GetAttr(bp_lock, m_api->m_bp_mgr.a_bp_ver_bp, process);
			if(process)
			{
				if(nValue)m_api->m_bp_mgr.CheckInWithRequest(process);
				else m_api->m_bp_mgr.UndoCheckOutWithRequest(process);
			}
		}
/*#ifdef _DEBUG Вроде как не надо
		//Колесников- ACAD
		else if (doc_lock)
		{
			CaplInstance* m_ciDocument= NULL; 
			m_api->m_data.GetAttr(doc_lock, m_api->m_doc_mgr.a_apl_doc_rev_doc, m_ciDocument);
			if(m_ciDocument)
			{
				if(nValue)m_api->m_doc_mgr.CheckIn(m_ciDocument,_T(""));
				else m_api->m_doc_mgr.UndoCheckOut(m_ciDocument);
			}

		}

#endif*/

		else CheckIn(nValue);
	}


	if(m_AutoSave)
		m_api->SaveChanges();

	if(NULL!=nValue && true==m_AutoSave)
	{
		CString csAccPat;
		aplExtent aet;

		aet.Add(nValue);
		if(true==show_dlg && _T("")!=dlg.m_csAccessString)
			apidata.NET_SetAccessFromPattern(&aet,dlg.m_csAccessString);
		else
		if(true==m_AutoUsurpire)
			if(TRUE==m_api->m_options_mgr.GetDefPatern(e_apl_charact_value,csAccPat))
				apidata.NET_SetAccessFromPattern(&aet,csAccPat);
	}

	if(val) *val=nValue;
	if(val_ver) *val_ver = zero_ver;
	if(nValue) return true;
	return false;
}
//*************************************************************
bool CaplCharacteristicManager::CreateCharacteristicGroup(CaplInstance *item, CaplInstance **group, CaplInstance *base_group,bool show_dlg)
{
	*group=0;
	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	if(item==0) return 0;
	if(item->GetType()==0) return 0;
	if(item->GetAccessmode()>aplRO)
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),item);
		return 0;
	}
	//if(base_ass!=0) LoadCharacteristic(base_ass);

	if(base_group!=0)
	{
		CaplInstance *m_union_def;
		m_data->GetAttr(base_group,a_charact_val_group_def,m_union_def);

		CaplAttrValue tst_values[2];
		tst_values[0].value.Set(item);
		tst_values[0].attr=a_charact_val_group_item;
		tst_values[1].value.Set(m_union_def);
		tst_values[1].attr=a_charact_val_group_def;

		aplExtent ext_found;
		m_data->NET_FindInstancesWithAttrValues(e_charact_val_group,2,&tst_values[0], ext_found, false);
		if(ext_found.GetSize())
		{
			if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Такая группа уже задана для данного объекта !!!"));
			return 0;
		}
		else
		{
			*group=m_data->CreateInstance(e_charact_val_group);
			m_data->PutAttr(*group,a_charact_val_group_def,m_union_def);
			m_data->PutAttr(*group,a_charact_val_group_item,item);

			// Копирование всех характеристик
			int i;
			aplExtent ext0;
			CaplInstance *inst=0,*inst0=0;
			m_data->GetEntityExtent(e_apl_charact_value,ext0);
			for(i=0;i<ext0.GetSize();i++)
			{
				m_data->GetAttr(ext0[i],a_apl_charact_val_group,inst);
				if(inst==base_group) CreateCharacteristic(item,ext0[i],&inst0,0,0,false,*group,false);
			}
		}
	}

	bool result=false;
	if(show_dlg)
	{
		CaplSetResourceHandle setres(module_inst);

		CCharactGroupDlg dlg;
		dlg.m_group=*group;
		dlg.m_item=item;
		dlg.m_api= m_api;
		if(dlg.DoModal()==IDOK)
		{
			*group=dlg.m_group;
		}
	}
	if(*group) result=true;

	if(m_AutoSave) m_api->SaveChanges();
	if(*group && m_AutoUsurpire)
	{
		CString csAccPat;
		aplExtent aet;

		aet.Add(*group);
		if(true==m_AutoUsurpire)
			if(TRUE==m_api->m_options_mgr.GetDefPatern(e_apl_charact_value,csAccPat))
				apidata.NET_SetAccessFromPattern(&aet,csAccPat);
	}
	return result;
}
//*************************************************************
bool CaplCharacteristicManager::DeleteCharacteristicGroup(CaplInstance *group)
{
	if(m_api==0) return false;
	if(m_api->m_charact_mgr.m_data==0) return false;
	if(m_api->m_charact_mgr.e_apl_charact==0) return false;
	if(group==0) return false;
	if(group->GetType()==0) return true;
	if(group->GetAccessmode()>aplRO)
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),group);
		return false;
	}
	//if(base_ass!=0) LoadCharacteristic(base_ass);

	// Удаление всех характеристик
	int i;
	aplExtent ext0,ext1;
	CaplInstance *inst=0,*inst0=0;
	m_api->m_charact_mgr.m_data->GetEntityExtent(m_api->m_charact_mgr.e_apl_charact_value,ext0);
	for(i=0;i<ext0.GetSize();i++)
	{
		m_api->m_charact_mgr.m_data->GetAttr(ext0[i],m_api->m_charact_mgr.a_apl_charact_val_group,inst);
		if(inst==group){
			if(ext0[i]->GetAccessmode()>aplRO)
			{
				if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),ext0[i]);
				return false;
			}
			ext1.Add(ext0[i]);
		} 
	}
	for(i=0;i<ext1.GetSize();i++)
	{
		m_api->m_charact_mgr.DeleteCharacteristic(ext1[i],true);
	}

	m_api->m_charact_mgr.m_data->DeleteInstance(group);

	if(m_api->m_charact_mgr.m_AutoSave) m_api->SaveChanges();
	return true;
}
bool CaplCharacteristicManager::ShowItemProperties(CaplInstance *item)
{
	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	if(item==0) return 0;
	if(item->GetType()==0) return 0;
	if(item->GetAccessmode()>aplRO)
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),item);
		return 0;
	}
	//if(base_ass!=0) LoadCharacteristic(base_ass);

	CaplSetResourceHandle setres(module_inst);

	CItemCharactDlg dlg;
	dlg.m_item=item;
	dlg.m_api= m_api;
	dlg.DoModal();
	return true;
}
//*************************************************************
bool CaplCharacteristicManager::ShowGroupProperties(CaplInstance *group)
{
	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	if(group==0) return 0;
	if(group->GetType()==0) return 0;
	if(group->GetAccessmode()>aplRO)
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),group);
		return 0;
	}
	//if(base_ass!=0) LoadCharacteristic(base_ass);

	CaplSetResourceHandle setres(module_inst);

	CCharactGroupDlg dlg;
	dlg.m_group=group;
	dlg.m_api= m_api;
	dlg.DoModal();
	if(m_AutoSave) m_api->SaveChanges();
	return true;
}

//*************************************************************
bool CaplCharacteristicManager::ShowProperties(CaplInstance *val,bool locked_type)
{
	if(m_data==0) return false;
	if(e_apl_charact==0) return false;
	if(val==0) return false;

	if(val!=0)
	{
		if(val->GetType()==0) return false;
		if(val->GetAccessmode()>aplRO) {
			if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),val); 
			return false;
		}
	}

	LoadCharacteristic(val);
	if(val->GetType()==0)
	{
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Значение было удалено другим пользователем !!!"));
		return false;
	}
	CaplInstance *ver=0;
	CaplInstance *lock=CheckMyLock(val,false);
	if(m_data->IsKindOf(val,e_apl_charact_value_ver))
		ver=val;
	else
		ver=lock;

	CaplSetResourceHandle setres(module_inst);

	CCharacteristicDlg dlg;
//	if(m_doc!=0) dlg.m_sel_charact_names.Append(m_doc->m_sel_charact_names);
	dlg.m_api=m_api;
	dlg.m_mode=_T("Edit");
	dlg.m_item=0;
	dlg.m_locked_type=locked_type;
	if(ver)
	{
		LoadCharacteristic(ver);
		dlg.m_value=ver;
		if(ver!=lock)
			dlg.m_ReadOnly=true;
	}
	else
	{
		dlg.m_value=val;
		if(m_bUseVersions)
			dlg.m_ReadOnly=true;
	}

	int iRet=dlg.DoModal();

	if(m_AutoSave) m_data->NET_SaveChanges();

	if(dlg.m_value->GetAccessmode()==aplOWN)
	{
		aplExtent aet;
		aet.Add(dlg.m_value);
		apidata.NET_SetAccessFromPattern(&aet,dlg.m_csAccessString);
	}

	return true;
}
//*************************************************************
bool CaplCharacteristicManager::DeleteCharacteristic(CaplInstance *val,bool delete_all,bool delete_only_version, bool bLoadFromBase)
{
	if(m_data==0) return false;
	if(e_apl_charact==0) return false;
	if(val==0) return false;
	if(val->GetType() ==0)	return false;
	if(val->GetAccessmode()>aplOWN)
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),val);
		return false;
	}

	// Атрибуты могут быть не загружены. 
	// Тогда криво удалятся табличные и агровые характеристики
	if(bLoadFromBase)LoadCharacteristic(val);
	
	CaplInstance *t_inst;
	CaplAggr aggr;
	int i;
	if (m_data->IsKindOf(val, e_apl_charact_value))
	{

		// проверяем на использование данной версии хар-ки в каком-либо изменении
		aplExtent ext_changes;
		CaplAttrValue find_val[1];
		find_val[0].attr = m_api->m_change_mgr.a_char_change_val;
		find_val[0].value.Set(val);

		apidata.NET_FindInstancesWithAttrValues(m_api->m_change_mgr.e_char_change, 1, &find_val[0], ext_changes, false);

		if (ext_changes.GetSize())
		{
			int res = IDYES;
			if(m_api->m_ModeInteractive)
				res = AfxMessageBox( APL_T("Характеристика используется в изменении. Всё равно удалить?"), MB_YESNO | MB_ICONQUESTION);

			if (res == IDYES)
			{
				for (int i = 0; i < ext_changes.GetSize(); i++)
				{
					aplExtent aggr;

					apidata.GetAttr(ext_changes[i], m_api->m_change_mgr.a_chng_item_attachment, aggr);
					for (int l = 0; l < aggr.GetSize(); l++)
					{
						apidata.NET_DeleteBlob(aggr[l], m_api->m_doc_mgr.a_apl_stored_document_source);
						apidata.DeleteInstance(aggr[i]);
					}

					apidata.DeleteInstance(ext_changes[i]);
				}
			}
			else
				return false;
		}


		CaplInstance *item=0;
		m_data->GetAttr(val,a_apl_charact_val_item,item);
		if(!item)
		{
			m_data->GetAttr(val,a_apl_charact_val_base_item,item);
			return false;
		}
		CaplInstance *lock=0,*bp_ver=0;		
		if(m_bUseVersions && m_data->IsKindOf(item,m_api->m_bp_mgr.e_bp) && delete_only_version)
		{
			CaplInstance *bp_lock=m_api->m_bp_mgr.CheckMyLock(item,true);
			if(!bp_lock) return false;
			lock=CheckMyLock(val,false);
			if(!lock) return false;
			m_data->GetAttr(lock,a_apl_charact_val_ver_item,bp_ver);
			if(!bp_ver) return false;
		}
						
		if(bp_ver && delete_only_version)
		{
			if(bp_ver->GetAccessmode()>aplOWN)
			{
				if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),bp_ver);
				return false;
			}
			CaplAggr aggr_char_ver;
			m_data->GetAttr(bp_ver,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr_char_ver);
			LoadCharacteristic(aggr_char_ver);
			bool found=false;
			for(int i=0;i<aggr_char_ver.GetSize();i++)
			{
				CaplInstance *char_val,*char_val_ver=0;
				aggr_char_ver.GetByIndex(i,char_val_ver);
				if(!char_val_ver) return false;if(char_val_ver->GetAccessmode()>aplRO) return false;
				m_data->GetAttr(char_val_ver,a_apl_charact_val_ver_char_value,char_val);
				if(char_val==val)
				{
					found=true;
					aggr_char_ver.Remove(i);
					m_data->PutAttr(bp_ver,m_api->m_bp_mgr.a_bp_ver_char_val_versions,aggr_char_ver);
					//if(!DeleteCharacteristic(lock)) 
					//	return false;
					break;
				}
			}
			return found;
		}
		



		if(m_data->IsKindOf(val,e_time_val))
		{
	//		m_data->GetAttr(val,a_apl_charact_val_time_val,t_inst);// объект apl_date_and_time
	//		m_data->DeleteInstance(t_inst,false);	
		}
		else if(m_data->IsKindOf(val,e_aggr_val))
		{
			m_data->GetAttr(val,a_apl_charact_val_aggr_val,aggr);
			for(i=0;i<aggr.GetSize();i++)
			{
				aggr.GetByIndex(i,t_inst);
				if(!t_inst) continue;
				if(t_inst!=val) DeleteCharacteristic(t_inst,true, false, bLoadFromBase);
			}
		} 
		else if(m_data->IsKindOf(val,e_table_val))
		{
			m_data->GetAttr(val,a_apl_charact_val_table_val,aggr);
			for(i=0;i<aggr.GetSize();i++)
			{
				aggr.GetByIndex(i,t_inst);
				if(!t_inst) continue;
				if(t_inst!=val) DeleteCharacteristic(t_inst,true, false, bLoadFromBase);
			}
		} 
		else if(m_data->IsKindOf(val,e_table_row))
		{
			m_data->GetAttr(val,a_table_row_items,aggr);
			for(i=0;i<aggr.GetSize();i++)
			{
				aggr.GetByIndex(i,t_inst);
				if(!t_inst) continue;
				CaplInstance *cell_val;
				m_data->GetAttr(t_inst,a_table_cell_val,cell_val);
				if(cell_val){if(cell_val->GetType()){if(cell_val!=val) DeleteCharacteristic(cell_val, true, false, bLoadFromBase);}}
				if(t_inst){if(t_inst->GetType()){ if(t_inst!=val) m_data->DeleteInstance(t_inst, false);}}
			}
		}
		aplExtent ext_rev;
		GetAllCharactVersion(val, ext_rev, bLoadFromBase);
		for(int i=0;i<ext_rev.GetSize();i++)
		{
			if(ext_rev[i])
				if(ext_rev[i]->GetAccessmode()<aplRO)
					DeleteCharacteristic(ext_rev[i], true, false, bLoadFromBase);

		}
		m_data->DeleteInstance(val,false);
	} 
	else if(m_data->IsKindOf(val, e_apl_charact_value_ver))
	{

		aplExtent ext_ver;
		CaplInstance *char_val=0;
		m_data->GetAttr(val, a_apl_charact_val_ver_char_value, char_val);	
		bool is_active_version=false;
		CaplInstance *act=0;
		if(char_val)
		{
			if(char_val->GetAccessmode()<aplNO)
			{
				m_data->GetAttr(char_val,a_apl_charact_val_act_ver,act);
				if(!delete_all)
				{
					if(act==val)
					{
						if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Нельзя удалять активную версию!"));
						return false;
					}
				}
			}
		}

		// проверяем на использование данной версии хар-ки в каком-либо изменении
		aplExtent ext_changes;
		CaplAttrValue find_val[1];
		find_val[0].attr = m_api->m_change_mgr.a_char_change_val;
		find_val[0].value.Set(char_val);

		apidata.NET_FindInstancesWithAttrValues(m_api->m_change_mgr.e_char_change, 1, &find_val[0], ext_changes, false);

		if (ext_changes.GetSize())
		{
			int res = IDYES;
			if(m_api->m_ModeInteractive)
				res = AfxMessageBox( APL_T("Характеристика используется в изменении. Всё равно удалить?"), MB_YESNO | MB_ICONQUESTION);
			if (res == IDYES)
			{
				for (int i = 0; i < ext_changes.GetSize(); i++)
				{
					aplExtent aggr;

					apidata.GetAttr(ext_changes[i], m_api->m_change_mgr.a_chng_item_attachment, aggr);
					for (int l = 0; l < aggr.GetSize(); l++)
					{
						apidata.NET_DeleteBlob(aggr[l], m_api->m_doc_mgr.a_apl_stored_document_source);
						apidata.DeleteInstance(aggr[i]);
					}

					apidata.DeleteInstance(ext_changes[i]);
				}
			}
		}

		if(m_data->IsKindOf(val,e_aggr_val_ver))
		{
			m_data->GetAttr(val,a_apl_charact_val_ver_aggr_val,aggr);
			for(i=0;i<aggr.GetSize();i++)
			{
				aggr.GetByIndex(i,t_inst);
				if(!t_inst) continue;
				if(t_inst!=val) DeleteCharacteristic(t_inst,true, false, bLoadFromBase);
			}
		}
		else if(m_data->IsKindOf(val,e_table_val_ver))
		{
			m_data->GetAttr(val,a_apl_charact_val_ver_table_val,aggr);
			for(i=0;i<aggr.GetSize();i++)
			{
				aggr.GetByIndex(i,t_inst);
				if(!t_inst) continue;
				if(t_inst!=val) DeleteCharacteristic(t_inst,true, false, bLoadFromBase);
			}
		} 
		else if(m_data->IsKindOf(val,e_table_row_ver))
		{
			m_data->GetAttr(val,a_table_row_ver_items,aggr);
			for(i=0;i<aggr.GetSize();i++)
			{
				aggr.GetByIndex(i,t_inst);
				if(!t_inst) continue;
				CaplInstance *cell_val;
				m_data->GetAttr(t_inst,a_table_cell_ver_val,cell_val);
				if(cell_val){if(cell_val->GetType()){if(cell_val!=val) DeleteCharacteristic(cell_val,true, false, bLoadFromBase);}}
				if(t_inst){if(t_inst->GetType()){ if(t_inst!=val) m_data->DeleteInstance(t_inst,false);}}
			}
		}
		m_data->DeleteInstance(val);
		if(is_active_version && !delete_all)
		{
			CString num=_T("");
			act=GetLatestCharValVersion(char_val,num);
			if(act) m_data->PutAttr(char_val,a_apl_charact_val_act_ver,act);
		}
	}

	return true;
};
//*************************************************************

CaplInstance* CaplCharacteristicManager::CreateCopyCharacteristicVal(CaplInstance* old_inst, CaplInstance* new_inst, CaplMap *inst_map)
{
	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	if(old_inst==0) return 0;
	if(old_inst->GetType() ==0)	return 0;

	CaplInstance *temp_inst=0;
	CaplAggr aggr,aggr_new;
	double rval;
	CString buf;
	int i;
	if(new_inst==0)	new_inst=m_data->CreateInstance(old_inst->GetType());
// 	else
// 	{
// 		DeleteCharacteristic(new_inst);
// 		new_inst=m_data->CreateInstance(old_inst->GetType());
// 	}
	m_data->GetAttr(old_inst,a_apl_charact_val_num,i);
	m_data->GetAttr(old_inst,a_apl_charact_val_type,temp_inst);
	m_data->GetAttr(old_inst,a_apl_charact_val_scope,buf);

	if(i>0) m_data->PutAttr(new_inst,a_apl_charact_val_num,i);
	if(temp_inst) m_data->PutAttr(new_inst,a_apl_charact_val_type,temp_inst);
	m_data->PutAttr(new_inst,a_apl_charact_val_scope,buf);
	m_data->GetAttr(old_inst,a_apl_charact_val_charact,temp_inst);
	if(temp_inst) m_data->PutAttr(new_inst,a_apl_charact_val_charact,temp_inst);
	m_data->GetAttrBN(old_inst,_T("unit"),temp_inst);
	if(temp_inst)m_data->PutAttrBN(new_inst,_T("unit"),temp_inst);

	if(m_data->IsKindOf(old_inst,e_meas_value))
	{
		m_data->GetAttr(old_inst,a_apl_charact_val_meas_val,rval);
		m_data->PutAttr(new_inst,a_apl_charact_val_meas_val,rval);
		m_data->GetAttr(old_inst,a_apl_charact_val_meas_min,rval);
		m_data->PutAttr(new_inst,a_apl_charact_val_meas_min,rval);
		m_data->GetAttr(old_inst,a_apl_charact_val_meas_max,rval);
		m_data->PutAttr(new_inst,a_apl_charact_val_meas_max,rval);
	}
	else if(m_data->IsKindOf(old_inst,e_descr_value))
	{
		m_data->GetAttr(old_inst,a_apl_charact_val_descr_val,buf);
		m_data->PutAttr(new_inst,a_apl_charact_val_descr_val,buf);
	}
	else if(m_data->IsKindOf(old_inst,e_enum_value))
	{
		m_data->GetAttr(old_inst,a_apl_charact_val_enum_val,buf);
		m_data->PutAttr(new_inst,a_apl_charact_val_enum_val,buf);
	}
	else if(m_data->IsKindOf(old_inst,e_monet_value))
	{
		m_data->GetAttr(old_inst,a_apl_charact_val_monet_val,rval);
		m_data->PutAttr(new_inst,a_apl_charact_val_monet_val,rval);
	}
	else if(m_data->IsKindOf(old_inst,e_apl_reference_value))
	{
		CaplInstance *tmp_inst1;
		m_data->GetAttr(old_inst,a_apl_reference_val,tmp_inst1);
		m_data->PutAttr(new_inst,a_apl_reference_val,tmp_inst1);
	}
	else if(m_data->IsKindOf(old_inst,e_time_val))
	{
		CString s_date;
		m_data->GetAttr(old_inst,a_apl_charact_val_time_val_s,s_date);
		m_data->PutAttr(new_inst,a_apl_charact_val_time_val_s,s_date);	
	}
	else if(m_data->IsKindOf(old_inst,e_aggr_val))
	{
		m_data->GetAttr(old_inst,a_apl_charact_val_aggr_val,aggr);
		aggr_new.Clear();
		for(int i=0;i<aggr.GetSize();i++){
			aggr.GetByIndex(i,temp_inst);
			temp_inst=CreateCopyCharacteristicVal(temp_inst,0,inst_map);
			aggr_new.Add(temp_inst);
		}
		m_data->PutAttr(new_inst,a_apl_charact_val_aggr_val,aggr_new);	
	}
	else if(m_data->IsKindOf(old_inst,e_table_val)){
		m_data->GetAttr(old_inst,a_apl_charact_val_table_val,aggr);
		aggr_new.Clear();
		for(int i=0;i<aggr.GetSize();i++){
			aggr.GetByIndex(i,temp_inst);
			temp_inst=CreateCopyCharacteristicVal(temp_inst,0,inst_map);
			aggr_new.Add(temp_inst);
		}
		m_data->PutAttr(new_inst,a_apl_charact_val_table_val,aggr_new);	
		if(inst_map!=0)
		{
			CaplInstance::CaplValueDefinition *attr_val=m_data->GetAttrValue(new_inst,a_apl_charact_val_table_val,true);
			if(attr_val!=0){
				if(attr_val->ArhiveAggr==0) attr_val->ArhiveAggr=new CaplAggr;
				attr_val->ArhiveAggr->Append(aggr_new);
			}
		}
	} 
	else if(m_data->IsKindOf(old_inst,e_table_row)){
		m_data->GetAttr(old_inst,a_table_row_items,aggr);
		aggr_new.Clear();
		for(int i=0;i<aggr.GetSize();i++){
			aggr.GetByIndex(i,temp_inst);
			if(temp_inst)
			{
				CaplInstance *ceel=m_data->CreateInstance(e_table_cell);
				CaplInstance *column, *cell_val,*ceel_val1;
				m_data->GetAttr(temp_inst,a_table_cell_val,cell_val);
				m_data->GetAttr(temp_inst,a_table_cell_column,column);

				ceel_val1=CreateCopyCharacteristicVal(cell_val,0,inst_map);
				m_data->PutAttr(ceel,a_table_cell_val,ceel_val1);
				m_data->PutAttr(ceel,a_table_cell_column,column);
				aggr_new.Add(ceel);
				if(inst_map!=0)inst_map->Add((long)temp_inst,(long)ceel);
			}
		}
		m_data->PutAttr(new_inst,a_table_row_items,aggr_new);
		if(inst_map!=0)
		{
			CaplInstance::CaplValueDefinition *attr_val=m_data->GetAttrValue(new_inst,a_table_row_items,true);
			if(attr_val!=0){
				if(attr_val->ArhiveAggr==0) attr_val->ArhiveAggr=new CaplAggr;
				attr_val->ArhiveAggr->Append(aggr_new);
			}
		}
	} 
	else
	{
		if(m_api->m_ModeInteractive)AfxMessageBox(APL_T("недопустимая ошибка при копировании\nВ этой версии данный тип не поддерживается"));
		return 0;
	}
	if(inst_map!=0)inst_map->Add((long)old_inst,(long)new_inst);
	return new_inst;
}
//*************************************************************
CaplInstance *CaplCharacteristicManager::GetColumnByName(CaplInstance *unit, const TCHAR * name)
{
	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	if(unit==0) return 0;
	if(unit->GetType()==0) return 0;
	CString buf,s_name=name;
	if(s_name==_T("")) return 0;

	CaplAggr aggr;
	m_data->GetAttrBN(unit,_T("columns"),aggr);
	for(int i=0;i<aggr.GetSize();i++)
	{
		CaplInstance *column;
		aggr.GetByIndex(i,column);
		if(column==0) continue;
		m_data->GetAttrBN(column,S::name,buf);
		if(buf==s_name) return column;
	}
	return 0;
}
//*************************************************************
CaplInstance *CaplCharacteristicManager::GetColumnValue(CaplInstance *row, CaplInstance *column)
{
	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	if(row==0) return 0;
	if(row->GetType()==0) return 0;
	if(column==0) return 0;
	if(column->GetType()==0) return 0;
	if(row->GetType()!=e_table_row) return 0;

	CaplAggr aggr;
	CaplInstance *cell,*val,*column1;
	m_data->GetAttr(row,a_table_row_items,aggr);
	for(int i=0;i<aggr.GetSize();i++)
	{
		aggr.GetByIndex(i,cell);
		if(cell==0) continue;
		m_data->GetAttr(cell,a_table_cell_column,column1);
		if(column1!=column) continue;
		m_data->GetAttr(cell,a_table_cell_val,val);
		return val;
	}
	return 0;
}//*************************************************************
/** Возвращает значение ячейки из табличной характеристики <p>
	@param table_value  значение табличной характеристики
	@param row индекс  строки таблицы
	@param column  столбец 
	@return найденное значение и NULL если такого нет */
CaplInstance *CaplCharacteristicManager::GetColumnValue(CaplInstance *table_value, int row, CaplInstance *column)
{
	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	if(table_value==0) return 0;
	if(table_value->GetType()==0) return 0;
	if(column==0) return 0;
	if(column->GetType()==0) return 0;

	CaplAggr aggr;
	CaplInstance *i_row;
	m_data->GetAttr(table_value,a_apl_charact_val_table_val,aggr);
	
	if(row>=aggr.GetSize()) return 0;

	aggr.GetByIndex(row,i_row);
	if(i_row==0) return 0;
	return GetColumnValue(i_row,column);
}

//*************************************************************
/** Создает (перезаписывает) значение ячейки табличной характеристики <p>
	@param row  строка таблицы
	@param value  новое значение 
	@return созданная ячейка значение и NULL в случае ошибки  */
CaplInstance *CaplCharacteristicManager::PutCellInRow(CaplInstance *row, CaplInstance *column, CaplInstance *value)
{
	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	if(row==0) return 0;
	if(row->GetType()==0) return 0;
	if(value==0) return 0;
	if(value->GetType()==0) return 0;
	if(column==0) return 0;
	if(column->GetType()==0) return 0;


	CaplAggr aggr;
	CaplInstance *cell=0,*cell1,*val=0,*column1;
	m_data->GetAttr(row,a_table_row_items,aggr);
	for(int i=0;i<aggr.GetSize();i++)
	{
		aggr.GetByIndex(i,cell1);
		if(cell1==0) continue;
		m_data->GetAttr(cell1,a_table_cell_column,column1);
		if(column1!=column) continue;
		m_data->GetAttr(cell1,a_table_cell_val,val);
		cell=cell1;
		break;
	}
	if(val!=0) DeleteCharacteristic(val);
	if(cell==0)
	{
		cell=m_data->CreateInstance(e_table_cell);
		m_data->PutAttr(cell1,a_table_cell_column,column);
		aggr.Add(cell);
		m_data->PutAttr(row,a_table_row_items,aggr);
	}
	m_data->PutAttr(cell,a_table_cell_val,value);
	return cell;
}
//*************************************************************

CaplInstance* CaplCharacteristicManager::BrowseReferenceVal(CaplInstance* unit)
{
	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	if(unit==0) return 0;
	if(unit->GetType()==0) return 0;
	if(!m_data->IsKindOf(unit,e_apl_reference_unit)) return 0;
	
	long flag=0;
	int i;
	CString buf=_T(""),format;
	CaplInstance *inst;
	CaplAggr m_ElementsAggr,aggr_base_items;
	aplExtent base_items;
	m_data->GetAttr(unit,a_apl_reference_types,m_ElementsAggr);
	m_data->GetAttr(unit,a_apl_reference_format,format);
	m_data->GetAttr(unit,a_apl_reference_base,aggr_base_items);

	for (i = 0; i < aggr_base_items.GetSize(); i++)
	{
		aggr_base_items.GetByIndex(i,inst);
		if(inst!=0) base_items.Add(inst);
	}

	for (i = 0; i < m_ElementsAggr.GetSize(); i++)
	{
		m_ElementsAggr.GetByIndex(i,buf);

		if(buf==_T("categ")) flag+=APL_MODE_SELECT_CATEGORY;
		else if(buf==_T("doc")) flag+=APL_MODE_SELECT_DOC;
		else if(buf==_T("prd")) flag+=APL_MODE_SELECT_PRD;
		else if(buf==_T("pdf")) flag+=APL_MODE_SELECT_PDF;
		else if(buf==_T("folder")) flag+=APL_MODE_SELECT_FOLDER;
		else if(buf==_T("action")) flag+=APL_MODE_SELECT_BP;
		else if(buf==_T("person")) flag+=APL_MODE_SELECT_PERSON;
		else if(buf==_T("organization")) flag+=APL_MODE_SELECT_ORG;
		else if(buf==_T("instances")) flag+=APL_MODE_SELECT_PRDINST;
		else if(buf==_T("classif_sys")) flag+=APL_MODE_SELECT_CLASSIF_SYSTEM;
		else if(buf==_T("classif_elm")) flag+=APL_MODE_SELECT_CLASSIF_ELEMENT;
		//else if(buf==_T("bp")) flag+=APL_MODE_SELECT_BP;
		else if(buf==_T("bpi")) flag+=APL_MODE_SELECT_BPINST;
		//else if(buf==_T("doc_rev")) flag+=;
		else if(buf==_T("project")) flag+=APL_MODE_SELECT_PROJECT;
		else if(buf==_T("lot")) flag+=APL_MODE_SELECT_LOT;
		else if(buf==_T("official")) flag+=APL_MODE_SELECT_OFFICIAL;
		else if(buf==_T("requirement")) flag+=APL_MODE_SELECT_REQUIREMENT;
		else if(buf==_T("change")) flag+=APL_MODE_SELECT_CHANGE;

	}
	if(flag==0)	{
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Типы данных не заданы. Настройте словари !")); 
		return 0;
	}

	return SelectInstance(flag, APL_T("Выберите объект"),&base_items);
}

CaplInstance* CaplCharacteristicManager::SelectUnit(CaplInstance *selected_unit,CaplInstance *selected_group)
{
	CaplSetResourceHandle setres(module_inst);
	CChoose_inst_dlg dlg;
	dlg.m_api=m_api;
	dlg.header= APL_T("Выбор единицы измерения");
	dlg.e_group=e_apl_unit_group;
	dlg.a_group_id=a_apl_unit_group_id;
	dlg.a_group_name=a_apl_unit_group_name;
	dlg.a_group_description=a_apl_unit_group_description;
	dlg.a_group_content=a_apl_unit_group_content;
	dlg.a_group_parent=a_apl_unit_group_parent;
	dlg.e_elem=e_apl_unit;

	dlg.selected_element=selected_unit;

	dlg.m_sCodeTitle = APL_T("Обозначение:");

	static CaplInstance *global_selected_group=0;
	if(selected_group!=0) dlg.selected_group=selected_group;
	else
	{
		if(global_selected_group!=0) dlg.selected_group=global_selected_group;
	}

	dlg.tmp.header= APL_T("Обозначение");dlg.tmp.function_type=0;dlg.tmp.attr=a_apl_unit_id;dlg.tmp.second_attr=0;dlg.tmp.width=80;dlg.elements.Add(dlg.tmp);
	dlg.tmp.header= APL_T("Код");dlg.tmp.function_type=0;dlg.tmp.attr=a_apl_unit_code;dlg.tmp.second_attr=0;dlg.tmp.width=40;dlg.elements.Add(dlg.tmp);
	dlg.tmp.header= APL_T("Наименование");dlg.tmp.function_type=1;dlg.tmp.attr=a_apl_unit_name;dlg.tmp.second_attr=0;dlg.tmp.width=120;dlg.elements.Add(dlg.tmp);
	dlg.tmp.header= APL_T("Описание");dlg.tmp.function_type=0;dlg.tmp.attr=a_apl_unit_descr;dlg.tmp.second_attr=0;dlg.tmp.width=80;dlg.elements.Add(dlg.tmp);
	dlg.tmp.header= APL_T("Определение");dlg.tmp.function_type=2;dlg.tmp.attr=0;dlg.tmp.second_attr=0;dlg.tmp.width=200;dlg.elements.Add(dlg.tmp);

	int ret=dlg.DoModal();

	global_selected_group=dlg.selected_group;

	if(ret==IDOK)
		return dlg.GetChosenElement();
	return 0;
}

CaplInstance* CaplCharacteristicManager::SelectCharacteristic(CaplInstance *selected_characteristic,CaplInstance *selected_group)
{
	CaplSetResourceHandle setres(module_inst);
	CChoose_inst_dlg dlg;
	dlg.m_api=m_api;
	dlg.header= APL_T("Выбор характеристики");
	dlg.e_group=e_apl_charact_group;
	dlg.a_group_id=a_apl_charact_group_id;
	dlg.a_group_name=a_apl_charact_group_name;
	dlg.a_group_description=a_apl_charact_group_description;
	dlg.a_group_content=a_apl_charact_group_content;
	dlg.a_group_parent=a_apl_charact_group_parent;
	dlg.e_elem=e_apl_charact;

	dlg.selected_element=selected_characteristic;


	static CaplInstance *global_selected_group=0;
	if(selected_group!=0) dlg.selected_group=selected_group;
	else
	{
		if(global_selected_group!=0) dlg.selected_group=global_selected_group;
	}

	dlg.tmp.header= APL_T("Обозначение");dlg.tmp.function_type=0;dlg.tmp.attr=a_apl_charact_id;dlg.tmp.second_attr=0;dlg.tmp.width=80;dlg.elements.Add(dlg.tmp);
	dlg.tmp.header= APL_T("Код");dlg.tmp.function_type=0;dlg.tmp.attr=a_apl_charact_code;dlg.tmp.second_attr=0;dlg.tmp.width=40;dlg.elements.Add(dlg.tmp);
	dlg.tmp.header= APL_T("Наименование");dlg.tmp.function_type=0;dlg.tmp.attr=a_apl_charact_name;dlg.tmp.second_attr=0;dlg.tmp.width=120;dlg.elements.Add(dlg.tmp);
	dlg.tmp.header= APL_T("Описание");dlg.tmp.function_type=0;dlg.tmp.attr=a_apl_charact_descr;dlg.tmp.second_attr=0;dlg.tmp.width=80;dlg.elements.Add(dlg.tmp);
	dlg.tmp.header= APL_T("Единица измерения");dlg.tmp.function_type=1;dlg.tmp.attr=a_apl_charact_unit;dlg.tmp.second_attr=a_apl_charact_unit;dlg.tmp.width=120;dlg.elements.Add(dlg.tmp);

	if(m_sel_charact_names.GetSize()>0)
	{
		dlg.m_attr_for_def=a_apl_charact_name;
		dlg.m_default_names=&m_sel_charact_names;
	}

	int ret=dlg.DoModal();

	global_selected_group=dlg.selected_group;


	if(ret==IDOK)
		return dlg.GetChosenElement();
	return 0;
	
}

CaplInstance* CaplCharacteristicManager::SelectCharactUnionGroup(CaplInstance *selected_charact_union,CaplInstance *selected_group)
{
	CaplSetResourceHandle setres(module_inst);
	CChoose_inst_dlg dlg;
	dlg.m_api= m_api;
	dlg.header= APL_T("Выбор группы характеристик");
	dlg.e_group=e_apl_charact_union_group;
	dlg.a_group_id=a_apl_charact_union_group_id;
	dlg.a_group_name=a_apl_charact_union_group_name;
	dlg.a_group_description=a_apl_charact_union_group_description;
	dlg.a_group_content=a_apl_charact_union_group_content;
	dlg.a_group_parent=a_apl_charact_union_group_parent;
	dlg.e_elem=e_apl_charact_union;

	dlg.selected_element=selected_charact_union;

	static CaplInstance *global_selected_group=0;
	if(selected_group!=0) dlg.selected_group=selected_group;
	else
	{
		if(global_selected_group!=0) dlg.selected_group=global_selected_group;
	}

	dlg.tmp.header= APL_T("Обозначение");dlg.tmp.function_type=0;dlg.tmp.attr=a_apl_charact_union_id;dlg.tmp.second_attr=0;dlg.tmp.width=80;dlg.elements.Add(dlg.tmp);
	dlg.tmp.header= APL_T("Наименование");dlg.tmp.function_type=0;dlg.tmp.attr=a_apl_charact_union_name;dlg.tmp.second_attr=0;dlg.tmp.width=80;dlg.elements.Add(dlg.tmp);
	dlg.tmp.header= APL_T("Описание");dlg.tmp.function_type=0;dlg.tmp.attr=a_apl_charact_union_descr;dlg.tmp.second_attr=0;dlg.tmp.width=80;dlg.elements.Add(dlg.tmp);

	int ret=dlg.DoModal();

	global_selected_group=dlg.selected_group;

	if(ret==IDOK)
		return dlg.GetChosenElement();
	return 0;


}





CaplInstance *CaplCharacteristicManager::GetLock(CaplInstance *val, bool bShowMessages)
{
	if(!m_bUseVersions) return 0;
	if(!val) return 0;
	if(val->GetAccessmode()>aplRO) return 0;
	if(!m_data->IsKindOf(val,e_apl_charact_value)) 
		if(!m_data->IsKindOf(val,e_apl_charact_value_ver))
			return 0;

	CaplInstance *lock=0,*user=0;
	if(m_data->IsKindOf(val,e_apl_charact_value))
	{
		m_data->GetAttr(val,a_apl_charact_val_lock_ver,lock);
	}
	else if(m_data->IsKindOf(val,e_apl_charact_value_ver))
	{
		CaplInstance *val_ver_char_value=0;
		m_data->GetAttr(val,a_apl_charact_val_ver_char_value,val_ver_char_value);
		if(!val_ver_char_value) return 0;
		m_data->GetAttr(val_ver_char_value,a_apl_charact_val_lock_ver,lock);
	}
	if(lock==0){
		if(bShowMessages && m_api->m_ModeInteractive)AfxMessageBox( APL_T("Характеристика не заблокирована !"),MB_OK|MB_ICONSTOP);
	}
		
	return lock;
	
}


CaplInstance *CaplCharacteristicManager::CheckMyLock(CaplInstance *val, bool bShowMessages)
{
	if(!m_bUseVersions) return 0;
	if(!val) return 0;
	if(val->GetAccessmode()>aplRO) return 0;
	if(!m_data->IsKindOf(val,e_apl_charact_value)) 
		if(!m_data->IsKindOf(val,e_apl_charact_value_ver))
			return 0;

	CaplInstance *lock=GetLock(val,bShowMessages);
	if(!lock) return 0;

	CaplInstance *user=0;
	m_data->GetAttr(lock,a_apl_charact_val_ver_author,user);
	if(user!=m_data->GetCurrUser())
	{
		if(bShowMessages && m_api->m_ModeInteractive)AfxMessageBox( APL_T("Характеристика заблокирована другим пользователем !"),MB_OK|MB_ICONSTOP);
		return 0;
	}
	return lock;

}

bool CaplCharacteristicManager::CheckOut(CaplInstance *val)
//bool CaplCharacteristicManager::CheckOut(CaplInstance *val,bool create_new_version)
{
	if(!m_bUseVersions) return false;
	if(!val) return false;
	if(val->GetAccessmode()>aplRO)
	{
		if(m_api->m_ModeInteractive) aplErrorMessage(S::NoAccessRight(),val);
		return false;
	}

	//Блокируем редактирование характеристик - параметров интеграции средствами PSS
	CString sEditSystem;
	m_api->m_data.GetAttr(val, a_apl_charact_val_system, sEditSystem);
	if(!sEditSystem.IsEmpty())
	{
		if(m_api->m_ModeInteractive)
		{
			CString sBuf;
			sBuf.Format( APL_T("Характеристика может редактироваться только в модуле %s!"), sEditSystem);
			AfxMessageBox(sBuf, MB_OK|MB_ICONSTOP);
		}
		return false;
	}

	//LoadCharacteristic(val);
	if(GetLock(val,false))
	{
		if(m_api->m_ModeInteractive) AfxMessageBox( APL_T("Характеристика уже заблокирована !"),MB_OK|MB_ICONSTOP);
		return false;
	}

	if(m_data->IsKindOf(val,e_apl_charact_value))
		if(val->GetAccessmode()>aplRW){if(m_api->m_ModeInteractive) aplErrorMessage(S::NoAccessRight(),val);return false;}	

	CaplInstance *rev=0,*act=0,*char_val_to_check_out=0,*lock=0;

	char_val_to_check_out=val;
	if(m_data->IsKindOf(val,e_apl_charact_value_ver)) 
	{
		m_data->GetAttr(val,a_apl_charact_val_ver_char_value,char_val_to_check_out);
		if(!char_val_to_check_out) return false;
		if(char_val_to_check_out->GetAccessmode()>aplRW)
		{
			if(m_api->m_ModeInteractive) aplErrorMessage(S::NoAccessRight(),char_val_to_check_out);
			return false;
		}
		rev=val;
	}
	m_data->GetAttr(char_val_to_check_out,a_apl_charact_val_act_ver,act);

	if(!act)
	{
		CString num=_T("");
		act=GetLatestCharValVersion(char_val_to_check_out,num);
		if(act)
			m_data->PutAttr(char_val_to_check_out,a_apl_charact_val_act_ver,act);
		else
			act=CreateCharValVersion(char_val_to_check_out,_T("0"));
		if(!act) return false;
	}

//	if(create_new_version)
//	{
		if(rev)	lock=CreateCharValVersion(rev,_T("-1"),false);
		else lock=CreateCharValVersion(act,_T("-1"),false);	
//	}
//	else
//		lock=val;
	if(!lock) return false;
	m_data->PutAttr(char_val_to_check_out,a_apl_charact_val_lock_ver,lock);
	if(m_AutoSave) 
		m_api->SaveChanges();
	return true;
}

bool CaplCharacteristicManager::CheckIn(CaplInstance *val,bool make_new_version_active)
//bool CaplCharacteristicManager::CheckIn(CaplInstance *val,bool create_new_version,bool make_new_version_active)
{
	if(!m_bUseVersions) return false;
	if(!val) return false;
	if(val->GetAccessmode()>aplRW)
	{
		if(m_api->m_ModeInteractive) aplErrorMessage(S::NoAccessRight(),val);
		return false;
	}
	if(!m_data->IsKindOf(val,e_apl_charact_value)) return false;

	CString sEditSystem;
	m_api->m_data.GetAttr(val, a_apl_charact_val_system, sEditSystem);
	if(!sEditSystem.IsEmpty())
	{
		if(m_api->m_ModeInteractive)
		{
			CString sBuf;
			sBuf.Format( APL_T("Редактирование характеристики может быть завершено только в модуле %s!"), sEditSystem);
			AfxMessageBox(sBuf, MB_OK|MB_ICONSTOP);
		}
		return false;
	}
	
	CaplInstance *lock=CheckMyLock(val,true);
	if(!lock) return false;
	if(lock->GetAccessmode()>aplRW) 
	{
		if(m_api->m_ModeInteractive) aplErrorMessage(S::NoAccessRight(),lock);
		return false;
	}
	CaplInstance *inst=0,*new_ver=0,*type=0,*charact=0;
	bool is_value_changed;
	CString buf=_T(""),dt_s=_T(""),scope=_T(""),version_num=_T("");
	int num=0,ver_num=0;
	double rval=0;

	m_data->GetAttr(lock,a_apl_charact_val_ver_is_changed,is_value_changed);
	CaplInstance *act=0,*base=0;
	m_data->GetAttr(lock,a_apl_charact_val_ver_base,base);
	m_data->GetAttr(val,a_apl_charact_val_act_ver,act);

	

	if(!is_value_changed)
	{
		if(act==base)
		{
			if(m_api->m_ModeInteractive)
			{
				if(IDNO==AfxMessageBox( APL_T("Данные не изменились !\n\nОтменить редактирование ?"),
					MB_YESNO|MB_ICONQUESTION)) return false;
			}
			
			if(!UndoCheckOut(val, false)) return false;
			return true;
		}
	}

	COleDateTime dt=COleDateTime::GetCurrentTime();
	aplDate2String(dt,dt_s);
	m_data->PutAttr(lock,a_apl_charact_val_ver_end_date,dt_s);
/*	if(act==lock)
	{
		version_num=_T("0");
	}
	else
	{
		GetLatestCharValVersion(val,version_num);
		ver_num=atoi(version_num);
		ver_num++;
		version_num.Format(_T("%i"),ver_num);
	}
	m_data->PutAttr(lock,a_apl_charact_val_ver_version_num,version_num);*/
	
	if(make_new_version_active)
	{
		MakeCharValVersionActive(lock);
	}
	m_data->PutAttr(val,a_apl_charact_val_lock_ver,(CaplInstance*)0);

	if(m_AutoSave) 
		m_api->SaveChanges();
	return true;
}


bool CaplCharacteristicManager::IsValueChanged(CaplInstance *val,CaplInstance *val_ver)
{
	if(!val) return true;
	if(!val_ver) return true;
	if(val->GetAccessmode()>aplRO) return true;
	if(val_ver->GetAccessmode()>aplRO) return true;
	if(!m_data->IsKindOf(val,e_apl_charact_value)) 
		if(!m_data->IsKindOf(val,e_apl_charact_value_ver)) 
			if(!m_data->IsKindOf(val,e_table_row))
				if(!m_data->IsKindOf(val,e_table_row_ver))
					return true;
	if(!m_data->IsKindOf(val_ver,e_apl_charact_value_ver)) 
		if(!m_data->IsKindOf(val_ver,e_table_row_ver)) 
			return true;
	if(m_data->IsKindOf(val,e_apl_charact_value_ver)) 
		if(val->GetType()!=val_ver->GetType()) return true;

	CaplInstance *inst=0,*inst1=0,*item=0,*item1=0,*type=0,*type1=0,*charact=0,*charact1=0,*char_ver_char_value=0;
	CString buf=_T(""),buf1=_T("");
	double rval=0,rval1=0,rvalmax=0,rvalmin=0,rvalmax1=0,rvalmin1=0;
	int num=0,num1=0;

	if(m_data->IsKindOf(val,e_meas_value) || m_data->IsKindOf(val,e_meas_value_ver))
	{
		if(!m_data->IsKindOf(val_ver,e_meas_value_ver)) return true;
		
		if(m_data->IsKindOf(val,e_apl_charact_value)) 
		{
			m_data->GetAttr(val,a_apl_charact_val_meas_val,rval);
			m_data->GetAttr(val,a_apl_charact_val_meas_min,rvalmin);
			m_data->GetAttr(val,a_apl_charact_val_meas_max,rvalmax);
		}
		else
		{
			m_data->GetAttr(val,a_apl_charact_val_ver_meas_val,rval);
			m_data->GetAttr(val,a_apl_charact_val_ver_meas_min,rvalmin);
			m_data->GetAttr(val,a_apl_charact_val_ver_meas_max,rvalmax);
		}
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_meas_val,rval1);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_meas_min,rvalmin1);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_meas_max,rvalmax1);
		
	}
	else if(m_data->IsKindOf(val,e_descr_value) || m_data->IsKindOf(val,e_descr_value_ver))
	{
		if(!m_data->IsKindOf(val_ver,e_descr_value_ver)) return true;

		if(m_data->IsKindOf(val,e_apl_charact_value)) 
			m_data->GetAttr(val,a_apl_charact_val_descr_val,buf);
		else
			m_data->GetAttr(val,a_apl_charact_val_ver_descr_val,buf);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_descr_val,buf1);

	}
	else if(m_data->IsKindOf(val,e_monet_value) || m_data->IsKindOf(val,e_monet_value_ver))
	{
		if(!m_data->IsKindOf(val_ver,e_monet_value_ver)) return true;

		if(m_data->IsKindOf(val,e_apl_charact_value)) 
			m_data->GetAttr(val,a_apl_charact_val_monet_val,rval);
		else
			m_data->GetAttr(val,a_apl_charact_val_ver_monet_val,rval);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_monet_val,rval1);
		

	}
	else if(m_data->IsKindOf(val,e_time_val) || m_data->IsKindOf(val,e_time_val_ver))
	{
		if(!m_data->IsKindOf(val_ver,e_time_val_ver)) return true;
		
		if(m_data->IsKindOf(val,e_apl_charact_value)) 
			m_data->GetAttr(val,a_apl_charact_val_time_val_s,buf);
		else
			m_data->GetAttr(val,a_apl_charact_val_ver_time_val_s,buf);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_time_val_s,buf1);

	}
	else if(m_data->IsKindOf(val,e_enum_value) || m_data->IsKindOf(val,e_enum_value_ver))
	{
		if(!m_data->IsKindOf(val_ver,e_enum_value_ver)) return true;

		if(m_data->IsKindOf(val,e_apl_charact_value)) 
			m_data->GetAttr(val,a_apl_charact_val_enum_val,buf);
		else
			m_data->GetAttr(val,a_apl_charact_val_ver_enum_val,buf);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_enum_val,buf1);
		
	}
	else if(m_data->IsKindOf(val,e_apl_reference_value) || m_data->IsKindOf(val,e_apl_reference_value_ver))
	{
		if(!m_data->IsKindOf(val_ver,e_apl_reference_value_ver)) return true;

		if(m_data->IsKindOf(val,e_apl_charact_value)) 
			m_data->GetAttr(val,a_apl_reference_val,inst);
		else
			m_data->GetAttr(val,a_apl_reference_val_ver_val,inst);
		m_data->GetAttr(val_ver,a_apl_reference_val_ver_val,inst1);
	}
	else if(m_data->IsKindOf(val,e_aggr_val) || m_data->IsKindOf(val,e_aggr_val_ver))
	{
		if(!m_data->IsKindOf(val_ver,e_aggr_val_ver)) return true;

		CaplAggr aggr0,aggr1;
		if(m_data->IsKindOf(val,e_apl_charact_value)) 
			m_data->GetAttr(val,a_apl_charact_val_aggr_val, aggr0);
		else
			m_data->GetAttr(val,a_apl_charact_val_ver_aggr_val, aggr0);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_aggr_val, aggr1);
		if(aggr0.GetSize()!=aggr1.GetSize()) return true;
		for(int i=0;i<aggr0.GetSize();i++)
		{
			CaplInstance *t_old_inst,*t_new_inst;
			aggr0.GetByIndex(i,t_old_inst);
			if(!t_old_inst) continue;
			aggr1.GetByIndex(i,t_new_inst);
			if(!t_new_inst) continue;
			if(IsValueChanged(t_old_inst,t_new_inst)) return true;
		}
	}
	else if(m_data->IsKindOf(val,e_table_val) || m_data->IsKindOf(val,e_table_val_ver))
	{
		if(!m_data->IsKindOf(val_ver,e_table_val_ver)) return true;

		CaplAggr aggr0,aggr1;
		if(m_data->IsKindOf(val,e_apl_charact_value)) 
			m_data->GetAttr(val,a_apl_charact_val_table_val, aggr0);
		else
			m_data->GetAttr(val,a_apl_charact_val_ver_table_val, aggr0);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_table_val, aggr1);
		if(aggr0.GetSize()!=aggr1.GetSize()) return true;
		for(int i=0;i<aggr0.GetSize();i++)
		{
			CaplInstance *t_old_inst,*t_new_inst;
			aggr0.GetByIndex(i,t_old_inst);
			if(!t_old_inst) continue;
			aggr1.GetByIndex(i,t_new_inst);
			if(!t_new_inst) continue;
			if(IsValueChanged(t_old_inst,t_new_inst)) return true;
		}
	}
	else if(m_data->IsKindOf(val,e_table_row) || m_data->IsKindOf(val,e_table_row_ver))
	{
		if(!m_data->IsKindOf(val_ver,e_table_row_ver)) return true;

		CaplAggr aggr0,aggr1;
		if(m_data->IsKindOf(val,e_apl_charact_value)) 
			m_data->GetAttr(val,a_table_row_items, aggr0);
		else
			m_data->GetAttr(val,a_table_row_ver_items, aggr0);
		m_data->GetAttr(val_ver,a_table_row_ver_items, aggr1);
		if(aggr0.GetSize()!=aggr1.GetSize()) return true;
		for(int i=0;i<aggr0.GetSize();i++)
		{
			CaplInstance *cell_old,*cell_new,*t_old_inst,*t_new_inst;
			aggr0.GetByIndex(i,cell_old);
			if(!cell_old) continue;
			aggr1.GetByIndex(i,cell_new);
			if(!cell_new) continue;
			if(m_data->IsKindOf(val,e_table_cell)) 
				m_data->GetAttr(cell_old,a_table_cell_val, t_old_inst);
			else
				m_data->GetAttr(cell_old,a_table_cell_ver_val, t_old_inst);
			m_data->GetAttr(cell_new,a_table_cell_ver_val, t_new_inst);
			if(IsValueChanged(t_old_inst,t_new_inst)) return true;
		}
	}
	if(buf!=buf1) return true;
	if(rval!=rval1) return true;
	if(rvalmax!=rvalmax1) return true;
	if(rvalmin!=rvalmin1) return true;
	if(inst!=inst1)  return true;

	if(m_data->IsKindOf(val,e_apl_charact_value)) 
	{
		m_data->GetAttr(val,a_apl_charact_val_item,item);
		m_data->GetAttr(val,a_apl_charact_val_type,type);
		m_data->GetAttr(val,a_apl_charact_val_charact,charact);
		m_data->GetAttr(val,a_apl_charact_val_scope,buf);
		m_data->GetAttr(val,a_apl_charact_val_num,num);

		m_data->GetAttr(val_ver,a_apl_charact_val_ver_char_value,char_ver_char_value);
		if(char_ver_char_value) m_data->GetAttr(char_ver_char_value,a_apl_charact_val_item,item1);
	}
	else
	{
		m_data->GetAttr(val,a_apl_charact_val_ver_item,item);
		m_data->GetAttr(val,a_apl_charact_val_ver_type,type);
		m_data->GetAttr(val,a_apl_charact_val_ver_charact,charact);
		m_data->GetAttr(val,a_apl_charact_val_ver_scope,buf);
		m_data->GetAttr(val,a_apl_charact_val_ver_num,num);

		m_data->GetAttr(val_ver,a_apl_charact_val_ver_item,item1);
	}
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_scope,buf1);
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_type,type1);
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_charact,charact1);
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_num,num1);
	if(item!=item1)  return true;
	if(buf!=buf1) return true;
	if(type!=type1)  return true;
	if(charact!=charact1) return true;
	if(num!=num1) return true;
			
	return false;
}

bool CaplCharacteristicManager::UndoCheckOut(CaplInstance *val,bool ask_before_undo)
{
	if(!val) return false;
	if(val->GetAccessmode()>aplRW) 
	{
		if(m_api->m_ModeInteractive) aplErrorMessage(S::NoAccessRight(),val);
		return false;
	}
	if(!m_data->IsKindOf(val,e_apl_charact_value)) return false;

	CString sEditSystem;
	m_api->m_data.GetAttr(val, a_apl_charact_val_system, sEditSystem);
	if(!sEditSystem.IsEmpty())
	{
		if(m_api->m_ModeInteractive)
		{
			CString sBuf;
			sBuf.Format( APL_T("Редактирование характеристики может быть завершено только в модуле %s!"), sEditSystem);
			AfxMessageBox(sBuf, MB_OK|MB_ICONSTOP);
		}
		return false;
	}
	//LoadCharacteristic(val);

	CaplInstance *lock=0,*user=0;
	lock=GetLock(val,ask_before_undo);
	if(!lock) return false;
	if(lock->GetAccessmode()>aplRW) 
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),lock);
		return false;
	}

	if(ask_before_undo && m_api->m_ModeInteractive)
	{
		m_data->GetAttr(lock,a_apl_charact_val_ver_author,user);
		if(user!=m_data->GetCurrUser())
		{
			if(val->GetAccessmode()>aplOWN)
			{
				if(m_api->m_ModeInteractive)
					AfxMessageBox( APL_T("Характеристика заблокирована другим пользователем !"),MB_OK|MB_ICONSTOP);
				return false;
			}
			if(m_api->m_ModeInteractive)
			{
				if(IDYES!=AfxMessageBox( APL_T("Характеристика заблокирована другим пользователем !\n\nВсе равно отменить редактирование ?"),
					MB_YESNO|MB_ICONQUESTION)) return true;
			}
		}
		else
		{
			if(m_api->m_ModeInteractive)
				if(IDNO==AfxMessageBox( APL_T("Вы действительно хотите отменить редактирование ?"), MB_YESNO|MB_ICONQUESTION)) return false;
		}
	}

	m_data->PutAttr(val,a_apl_charact_val_lock_ver,(CaplInstance*)0);
	bool old_ModeInteractive=m_api->m_ModeInteractive;
	m_api->m_ModeInteractive=false;
	DeleteCharacteristic(lock);
	m_api->m_ModeInteractive=old_ModeInteractive;
	if(m_AutoSave) 
		m_api->SaveChanges();
	return true;
}

bool CaplCharacteristicManager::GetAllCharactVersion(CaplInstance *val,aplExtent &outExt, bool bLoadFromBase)
{
	outExt.Clear();
	if(m_data==0) return false;
	if(val==0) return false;
	if(val->GetType()==0) return false;
	if(!m_bUseVersions) return false;
	if(!val->GetId()) return false;
	int i,j;
	aplExtent ext_1;

	if(m_data->IsConnected() && bLoadFromBase) 
	{
		// Чтение из базы
		CaplLoadData ld(m_data,DEF_SOURCE);

		if(m_data->IsKindOf(val,e_apl_charact_value))
			j=ld.AddQuery(_T('b'), val->GetId(), e_apl_charact_value_ver,a_apl_charact_val_ver_char_value, true,true);
		else if(m_data->IsKindOf(val,e_apl_charact_value_ver))
			j=ld.AddQuery(_T('b'), val->GetId(), e_apl_charact_value_ver,a_apl_charact_val_ver_base, true,true);
		ld.LoadEx(true,&ext_1);
	}

	
	CaplInstance *inst=0;
	//aplExtent ext_hist;
	// Чтение версий
	//m_data->GetEntityExtent(e_apl_charact_value_ver,ext_hist);

	BOOL bUseBase=false;
	if(m_data->IsKindOf(val,e_apl_charact_value_ver)) bUseBase=true;

	for(i=0;i<ext_1.Size;i++)
	{
		CaplInstance *inst_v=ext_1[i];
		if(inst_v==0) continue;
		if(inst_v->GetType()==0) continue;
		if(inst_v->GetAccessmode()>aplRO) continue;
		if(!m_data->IsKindOf(inst_v,e_apl_charact_value_ver ))continue;

		if(bUseBase)
			m_data->GetAttr(inst_v,a_apl_charact_val_ver_base,inst);
		else 
			m_data->GetAttr(inst_v,a_apl_charact_val_ver_char_value,inst);

		if(inst==val) 
			outExt.Add(inst_v);
	}
	if(m_data->IsConnected() && bLoadFromBase)
		LoadCharacteristic(outExt);
	return true;
}

bool CaplCharacteristicManager::GetAllCharactVersion(aplExtent& vals, aplExtent &outExt, bool bLoadFromBase)
{
	outExt.Clear();
	if(m_data==0) return false;
	if(vals.GetSize()==0) return false;
	if(!m_bUseVersions) return false;
	int i,j;
	CaplInstance* val=0;
	if(m_data->IsConnected() && bLoadFromBase) 
	{
		// Чтение из базы
		CaplLoadData ld_char(m_data,DEF_SOURCE);
		CaplLoadData ld_charver(m_data,DEF_SOURCE);
		for(i=0;i<vals.GetSize();i++){
			val=vals[i];
			if(m_data->IsKindOf(val,e_apl_charact_value))
				j=ld_char.AddQuery(0, val);
			else if(m_data->IsKindOf(val,e_apl_charact_value_ver))
				j=ld_charver.AddQuery(0,val);
		}

		if(ld_char.m_queries.Size>0){
			j=ld_char.AddQuery(_T('r'), 0, e_apl_charact_value_ver,a_apl_charact_val_ver_char_value, true);
			ld_char.AddQuery(_T('d'), j, 0, a_apl_charact_val_ver_char_value, true);
			ld_char.LoadEx();
		}

		if(ld_charver.m_queries.Size>0){
			j=ld_charver.AddQuery(_T('r'), val->GetId(), e_apl_charact_value_ver,a_apl_charact_val_ver_char_value, true);
			ld_charver.AddQuery(_T('d'), j, 0, a_apl_charact_val_ver_char_value, true);
			ld_charver.AddQuery(_T('d'), j, 0, a_apl_charact_val_ver_base, true);
			ld_charver.LoadEx();
		}
	}

	
	CaplInstance *inst;
	aplExtent ext_hist;
	// Чтение версий
	m_data->GetEntityExtent(e_apl_charact_value_ver,ext_hist);
	for(i=0;i<ext_hist.Size;i++)
	{
		if(ext_hist[i]==0) continue;
		if(ext_hist[i]->GetType()==0) continue;
		if(ext_hist[i]->GetAccessmode()>aplRO) continue;
		if(m_data->IsKindOf(ext_hist[i],e_apl_charact_value))
			m_data->GetAttr(ext_hist[i],a_apl_charact_val_ver_char_value,inst);
		if(m_data->IsKindOf(ext_hist[i],e_apl_charact_value_ver))
			m_data->GetAttr(ext_hist[i],a_apl_charact_val_ver_base,inst);
		if(-1!=vals.Find(inst)) 
			outExt.Add(ext_hist[i]);
	}
	if(m_data->IsConnected() && bLoadFromBase)
		LoadCharacteristic(outExt);
	return true;
}

CaplInstance *CaplCharacteristicManager::CreateCharValVersion(CaplInstance *val,CString num,bool make_active,bool only_values)
{
	if(!val) return 0;
	if(val->GetAccessmode()>aplRO) return 0;
	//LoadCharacteristic(val);
	CaplInstance *inst=0,*inst0=0,*new_ver=0,*item=0,*type=0,*charact=0,*char_val=0,*base_ver=0;
	CString buf=_T(""),dt_s=_T(""),scope=_T("");
	int num_of_measurement=0;
	CaplAggr aggr_char_val,aggr_char_val_ver;
	double rval=0;

	char_val=val;
	if(m_data->IsKindOf(val,e_apl_charact_value)) {}
	else if(m_data->IsKindOf(val,e_apl_charact_value_ver)) 
	{
		m_data->GetAttr(val,a_apl_charact_val_ver_char_value,char_val);
	}
	else if(m_data->IsKindOf(val,e_table_row_ver)) {}
	else return 0;
	if(!only_values)
	{
		if(!char_val) return 0;
		if(char_val->GetAccessmode()>aplRO) return 0;
	}

	if(m_data->IsKindOf(val,e_meas_value))
	{
		new_ver=m_data->CreateInstance(e_meas_value_ver);
		m_data->GetAttr(val,a_apl_charact_val_meas_val,rval);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_meas_val,rval);
		m_data->GetAttr(val,a_apl_charact_val_meas_min,rval);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_meas_min,rval);
		m_data->GetAttr(val,a_apl_charact_val_meas_max,rval);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_meas_max,rval);
	}
	else if(m_data->IsKindOf(val,e_descr_value))
	{
		new_ver=m_data->CreateInstance(e_descr_value_ver);
		m_data->GetAttr(val,a_apl_charact_val_descr_val,buf);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_descr_val,buf);
	
	}
	else if(m_data->IsKindOf(val,e_monet_value))
	{
		new_ver=m_data->CreateInstance(e_monet_value_ver);
		m_data->GetAttr(val,a_apl_charact_val_monet_val,rval);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_monet_val,rval);
	}
	else if(m_data->IsKindOf(val,e_time_val))
	{
		new_ver=m_data->CreateInstance(e_time_val_ver);
		m_data->GetAttr(val,a_apl_charact_val_time_val_s,buf);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_time_val_s,buf);
	}
	else if(m_data->IsKindOf(val,e_enum_value))
	{
		new_ver=m_data->CreateInstance(e_enum_value_ver);
		m_data->GetAttr(val,a_apl_charact_val_enum_val,buf);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_enum_val,buf);
	}
	else if(m_data->IsKindOf(val,e_apl_reference_value))
	{
		new_ver=m_data->CreateInstance(e_apl_reference_value_ver);
		m_data->GetAttr(val,a_apl_reference_val,inst);
		m_data->PutAttr(new_ver,a_apl_reference_val_ver_val,inst);
	}
	else if(m_data->IsKindOf(val,e_aggr_val))
	{
		new_ver=m_data->CreateInstance(e_aggr_val_ver);
		m_data->GetAttr(val,a_apl_charact_val_aggr_val,aggr_char_val);
		for(int i=0;i<aggr_char_val.GetSize();i++)
		{
			aggr_char_val.GetByIndex(i,inst);
			if(inst)
			{
				CaplInstance *val_ver=CreateCharValVersion(inst,_T("-1"),false,true);
				if(val_ver) aggr_char_val_ver.Add(val_ver);
			}
		}
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_aggr_val,aggr_char_val_ver);
	}
	else if(m_data->IsKindOf(val,e_table_val))
	{
		new_ver=m_data->CreateInstance(e_table_val_ver);
		CaplAggr aggr_row,aggr_row_ver;
		m_data->GetAttr(val,a_apl_charact_val_table_val,aggr_row);
		for(int i=0;i<aggr_row.GetSize();i++)
		{
			aggr_row.GetByIndex(i,inst);
			if(inst)
			{
				CaplInstance *new_row_ver=CreateCharValVersion(inst,_T("-1"),false,true);
				if(new_row_ver) aggr_row_ver.Add(new_row_ver);
			}
		}
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_table_val,aggr_row_ver);
	}
	else if(m_data->IsKindOf(val,e_table_row))
	{
		new_ver=m_data->CreateInstance(e_table_row_ver);
		CaplAggr aggr_cell,aggr_cell_ver;
		m_data->GetAttr(val,a_table_row_items,aggr_cell);
		for(int i=0;i<aggr_cell.GetSize();i++)
		{
			aggr_cell.GetByIndex(i,inst);
			if(inst)
			{
				CaplInstance *new_cell_ver=m_data->CreateInstance(e_table_cell_ver);
				if(new_cell_ver) 
				{
					CaplInstance *cell_val=0,*cell_val_ver=0,*cell_column=0,*cell_column_ver=0;
					m_data->GetAttr(inst,a_table_cell_val,cell_val);
					if(cell_val) cell_val_ver=CreateCharValVersion(cell_val,_T("-1"),false,true);
					if(cell_val_ver) m_data->PutAttr(new_cell_ver,a_table_cell_ver_val,cell_val_ver); 
					m_data->GetAttr(inst,a_table_cell_column,cell_column);
					if(cell_column) m_data->PutAttr(new_cell_ver,a_table_cell_ver_column,cell_column);
					aggr_cell_ver.Add(new_cell_ver);
				}
			}
		}
		m_data->PutAttr(new_ver,a_table_row_ver_items,aggr_cell_ver);
	}
	else if(m_data->IsKindOf(val,e_meas_value_ver))
	{
		new_ver=m_data->CreateInstance(e_meas_value_ver);
		m_data->GetAttr(val,a_apl_charact_val_ver_meas_val,rval);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_meas_val,rval);
		m_data->GetAttr(val,a_apl_charact_val_ver_meas_min,rval);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_meas_min,rval);
		m_data->GetAttr(val,a_apl_charact_val_ver_meas_max,rval);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_meas_max,rval);
	}
	else if(m_data->IsKindOf(val,e_descr_value_ver))
	{
		new_ver=m_data->CreateInstance(e_descr_value_ver);
		m_data->GetAttr(val,a_apl_charact_val_ver_descr_val,buf);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_descr_val,buf);
	}
	else if(m_data->IsKindOf(val,e_monet_value_ver))
	{
		new_ver=m_data->CreateInstance(e_monet_value_ver);
		m_data->GetAttr(val,a_apl_charact_val_ver_monet_val,rval);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_monet_val,rval);
	}
	else if(m_data->IsKindOf(val,e_time_val_ver))
	{
		new_ver=m_data->CreateInstance(e_time_val_ver);
		m_data->GetAttr(val,a_apl_charact_val_ver_time_val_s,buf);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_time_val_s,buf);
	}
	else if(m_data->IsKindOf(val,e_enum_value_ver))
	{
		new_ver=m_data->CreateInstance(e_enum_value_ver);
		m_data->GetAttr(val,a_apl_charact_val_ver_enum_val,buf);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_enum_val,buf);
	}
	else if(m_data->IsKindOf(val,e_apl_reference_value_ver))
	{
		new_ver=m_data->CreateInstance(e_apl_reference_value_ver);
		m_data->GetAttr(val,a_apl_reference_val_ver_val,inst);
		m_data->PutAttr(new_ver,a_apl_reference_val_ver_val,inst);
	}
	else if(m_data->IsKindOf(val,e_aggr_val_ver))
	{
		new_ver=m_data->CreateInstance(e_aggr_val_ver);
		m_data->GetAttr(val,a_apl_charact_val_ver_aggr_val,aggr_char_val);
		for(int i=0;i<aggr_char_val.GetSize();i++)
		{
			aggr_char_val.GetByIndex(i,inst);
			if(inst)
			{
				CaplInstance *val_ver=CreateCharValVersion(inst,_T("-1"),false,true);
				if(val_ver) aggr_char_val_ver.Add(val_ver);
			}
		}
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_aggr_val,aggr_char_val_ver);
	}
	else if(m_data->IsKindOf(val,e_table_val_ver))
	{
		new_ver=m_data->CreateInstance(e_table_val_ver);
		CaplAggr aggr_row,aggr_row_ver;
		m_data->GetAttr(val,a_apl_charact_val_ver_table_val,aggr_row);
		for(int i=0;i<aggr_row.GetSize();i++)
		{
			aggr_row.GetByIndex(i,inst);
			if(inst)
			{
				CaplInstance *new_row_ver=CreateCharValVersion(inst,_T("-1"),false,true);
				if(new_row_ver) aggr_row_ver.Add(new_row_ver);
			}
		}
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_table_val,aggr_row_ver);
	}
	else if(m_data->IsKindOf(val,e_table_row_ver))
	{
		new_ver=m_data->CreateInstance(e_table_row_ver);
		CaplAggr aggr_cell,aggr_cell_ver;
		m_data->GetAttr(val,a_table_row_ver_items,aggr_cell);
		for(int i=0;i<aggr_cell.GetSize();i++)
		{
			aggr_cell.GetByIndex(i,inst);
			if(inst)
			{
				CaplInstance *new_cell_ver=m_data->CreateInstance(e_table_cell_ver);
				if(new_cell_ver) 
				{
					CaplInstance *cell_val=0,*cell_val_ver=0,*cell_column=0,*cell_column_ver=0;
					m_data->GetAttr(inst,a_table_cell_ver_val,cell_val);
					if(cell_val) cell_val_ver=CreateCharValVersion(cell_val,_T("-1"),false,true);
					if(cell_val_ver) m_data->PutAttr(new_cell_ver,a_table_cell_ver_val,cell_val_ver); 
					m_data->GetAttr(inst,a_table_cell_ver_column,cell_column);
					if(cell_column) m_data->PutAttr(new_cell_ver,a_table_cell_ver_column,cell_column);
					aggr_cell_ver.Add(new_cell_ver);
				}
			}
		}
		m_data->PutAttr(new_ver,a_table_row_ver_items,aggr_cell_ver);
	}
	else
	{
		if(m_api->m_ModeInteractive)
			AfxMessageBox( APL_T("Данный тип характеристики в текущей версии не поддерживается!"));
		return 0;
	}
	if(only_values)
		return new_ver;
	
	if(m_data->IsKindOf(val,e_apl_charact_value)) 
	{
		char_val=val;
		m_data->GetAttr(val,a_apl_charact_val_act_ver,base_ver);
		m_data->GetAttr(val,a_apl_charact_val_scope,scope);
		m_data->GetAttr(val,a_apl_charact_val_type,type);
		m_data->GetAttr(val,a_apl_charact_val_charact,charact);
		m_data->GetAttr(val,a_apl_charact_val_num,num_of_measurement);
	}
	else if(m_data->IsKindOf(val,e_apl_charact_value_ver)) 
	{
		base_ver=val;
		m_data->GetAttr(val,a_apl_charact_val_ver_scope,scope);
		m_data->GetAttr(val,a_apl_charact_val_ver_type,type);
		m_data->GetAttr(val,a_apl_charact_val_ver_charact,charact);
		m_data->GetAttr(val,a_apl_charact_val_ver_num,num_of_measurement);
	}
	CaplInstance *base_item=0;
	m_data->GetAttr(char_val,a_apl_charact_val_base_item,base_item);
	if(!base_item) 
	{
		m_data->GetAttr(char_val,a_apl_charact_val_item,base_item);
		if(base_item) m_data->PutAttr(char_val,a_apl_charact_val_base_item,base_item);
	}

	m_data->PutAttr(new_ver,a_apl_charact_val_ver_char_value,char_val);
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_base,base_ver);
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_scope,scope);
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_type,type);
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_charact,charact);
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_num,num_of_measurement);
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_is_changed,false);

	COleDateTime dt=COleDateTime::GetCurrentTime();
	aplDate2String(dt,dt_s);
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_start_date,dt_s);
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_author,m_data->GetCurrUser());
	
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_end_date,dt_s);
	if(num==_T("-1")) 
	{
		GetLatestCharValVersion(char_val,num);
		int ver_num=_atoi(num);
		ver_num++;
		num.Format(_T("%i"),ver_num);
	}
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_version_num,num);
	if(make_active)
	{
		MakeCharValVersionActive(new_ver);
	}

	
	if(m_AutoSave) 
		m_api->SaveChanges();

	return new_ver;

}

CaplInstance *CaplCharacteristicManager::GetLatestCharValVersion(CaplInstance *val,CString &num,bool load_from_db)
{
	int j;
	if(val==0)return 0;
	if(m_data->IsConnected() && val->GetId()!=0&&load_from_db)
	{
		CaplLoadData ld(m_data,DEF_SOURCE);
		j=ld.AddQuery(_T('b'), val->GetId(), e_apl_charact_value_ver,a_apl_charact_val_ver_char_value, true,true);
		ld.LoadEx();
	}

    CaplInstance *latest_ver=0,*inst=0;
	int max_id=-1;
	aplExtent ext_rev;
	CString buf;
	num=_T("0");
	m_data->GetEntityExtent(e_apl_charact_value_ver,ext_rev);
	CaplInstance *lock=GetLock(val,false);
	for(int i=0;i<ext_rev.Size;i++)
	{
		if(!ext_rev[i]) continue;
		if(ext_rev[i]->GetAccessmode()>aplRO) continue;
		m_data->GetAttr(ext_rev[i],a_apl_charact_val_ver_char_value,inst);
		if(inst==val && lock!=ext_rev[i])
		{
			m_data->GetAttr(ext_rev[i],a_apl_charact_val_ver_version_num,buf);
			j=_atoi(buf);
			if(j>max_id)
			{
				latest_ver=ext_rev[i];
				max_id=j;
				num.Format(_T("%i"),max_id);
			}
		}
	}
	return latest_ver;
}

CaplInstance *CaplCharacteristicManager::CopyValVersionToVal(CaplInstance *val_ver,CaplInstance *val)
{
	if(!val_ver) return 0;
	if(val_ver->GetAccessmode()>aplRO) return 0;
	if(val)
		if(val->GetAccessmode()>aplRW) return 0;
	CaplInstance *inst=0,*inst1=0;
	CString buf=_T("");
	double rval=0;
	if(m_data->IsKindOf(val_ver,e_meas_value_ver))
	{
		if(!val) val=m_data->CreateInstance(e_meas_value);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_meas_val,rval);
		m_data->PutAttr(val,a_apl_charact_val_meas_val,rval);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_meas_min,rval);
		m_data->PutAttr(val,a_apl_charact_val_meas_min,rval);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_meas_max,rval);
		m_data->PutAttr(val,a_apl_charact_val_meas_max,rval);
	}
	else if(m_data->IsKindOf(val_ver,e_descr_value_ver))
	{
		if(!val) val=m_data->CreateInstance(e_descr_value);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_descr_val,buf);
		m_data->PutAttr(val,a_apl_charact_val_descr_val,buf);
	}
	else if(m_data->IsKindOf(val_ver,e_monet_value_ver))
	{
		if(!val) val=m_data->CreateInstance(e_monet_value);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_monet_val,rval);
		m_data->PutAttr(val,a_apl_charact_val_monet_val,rval);
	}
	else if(m_data->IsKindOf(val_ver,e_time_val_ver))
	{
		if(!val) val=m_data->CreateInstance(e_time_val);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_time_val_s,buf);
		m_data->PutAttr(val,a_apl_charact_val_time_val_s,buf);
	}
	else if(m_data->IsKindOf(val_ver,e_enum_value_ver))
	{
		if(!val) val=m_data->CreateInstance(e_enum_value);
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_enum_val,buf);
		m_data->PutAttr(val,a_apl_charact_val_enum_val,buf);
	}
	else if(m_data->IsKindOf(val_ver,e_apl_reference_value_ver))
	{
		if(!val) val=m_data->CreateInstance(e_apl_reference_value);
		m_data->GetAttr(val_ver,a_apl_reference_val_ver_val,inst);
		m_data->PutAttr(val,a_apl_reference_val,inst);
	}
	else if(m_data->IsKindOf(val_ver,e_aggr_val_ver))
	{
		if(!val) val=m_data->CreateInstance(e_aggr_val);
		CaplAggr aggr_char_val,aggr_char_val_ver;
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_aggr_val,aggr_char_val_ver);
		for(int i=0;i<aggr_char_val_ver.GetSize();i++)
		{
			aggr_char_val_ver.GetByIndex(i,inst);
			if(inst)
			{
				inst1=CopyValVersionToVal(inst);
				if(inst1) aggr_char_val.Add(inst1);
				
			}
		}
		m_data->PutAttr(val,a_apl_charact_val_aggr_val,aggr_char_val);
	}
	else if(m_data->IsKindOf(val_ver,e_table_val_ver))
	{
		if(!val) val=m_data->CreateInstance(e_table_val);
		CaplAggr table_char_val,table_char_val_ver;
		m_data->GetAttr(val_ver,a_apl_charact_val_ver_table_val,table_char_val_ver);
		for(int i=0;i<table_char_val_ver.GetSize();i++)
		{
			table_char_val_ver.GetByIndex(i,inst);
			if(inst)
			{
				inst1=CopyValVersionToVal(inst);
				if(inst1) table_char_val.Add(inst1);
				
			}
		}
		m_data->PutAttr(val,a_apl_charact_val_table_val,table_char_val);
	}
	else if(m_data->IsKindOf(val_ver,e_table_row_ver))
	{
		if(!val) val=m_data->CreateInstance(e_table_row);
		CaplAggr table_row_ver_items,table_row_items;
		m_data->GetAttr(val_ver,a_table_row_ver_items,table_row_ver_items);
		for(int i=0;i<table_row_ver_items.GetSize();i++)
		{
			table_row_ver_items.GetByIndex(i,inst);
			if(inst)
			{
				CaplInstance *cell=m_data->CreateInstance(e_table_cell);
				if(!cell) continue;
				m_data->GetAttr(inst,a_table_cell_ver_column,inst1);
				m_data->PutAttr(cell,a_table_cell_column,inst1);
				m_data->GetAttr(inst,a_table_cell_ver_val,inst);
				inst1=CopyValVersionToVal(inst);
				if(inst1) m_data->PutAttr(cell,a_table_cell_val,inst1);
				table_row_items.Add(cell);
				
			}
		}
		m_data->PutAttr(val,a_table_row_items,table_row_items);
	}
	else
		return 0;
	int i;
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_num,i);
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_type,inst);
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_scope,buf);

	if(i>0) m_data->PutAttr(val,a_apl_charact_val_num,i);
	if(inst) m_data->PutAttr(val,a_apl_charact_val_type,inst);
	m_data->PutAttr(val,a_apl_charact_val_scope,buf);
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_charact,inst);
	if(inst) m_data->PutAttr(val,a_apl_charact_val_charact,inst);

	return val;
}

bool CaplCharacteristicManager::MakeCharValVersionActive(CaplInstance *val_ver)
{
	if(!m_bUseVersions) return false;
	if(!val_ver) return false;
	if(val_ver->GetAccessmode()>aplRO) {
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),val_ver); 
		return false;
	}
	if(!m_data->IsKindOf(val_ver,e_apl_charact_value_ver))
		return false;

	CaplInstance *val=0;
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_char_value,val);	
	if(!val) return false;
	if(val->GetAccessmode()>aplRW) {
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight(),val); 
		return false;
	}

	CaplInstance *lock=CheckMyLock(val,false);
	if(!lock && GetLock(val,false)) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Характеристика заблокирована другим пользователем !"),MB_OK|MB_ICONSTOP);
		return false;
	}

	CaplInstance *act=0;
	m_data->GetAttr(val,a_apl_charact_val_act_ver,act);	
	if(act==val_ver && act!=lock)
	{
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Версия уже активна!"));
		return false;
	}

	CopyValVersionToVal(val_ver,val);	

	CaplInstance *type=0,*charact=0,*base_item=0;
	CString scope=_T("");
	int num=0;

	m_data->GetAttr(val_ver,a_apl_charact_val_ver_scope,scope);
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_type,type);
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_charact,charact);
	m_data->GetAttr(val_ver,a_apl_charact_val_ver_num,num);

	m_data->GetAttr(val,a_apl_charact_val_base_item,base_item);
	if(base_item) m_data->PutAttr(val,a_apl_charact_val_item,base_item);
	m_data->PutAttr(val,a_apl_charact_val_scope,scope);
	m_data->PutAttr(val,a_apl_charact_val_type,type);
	m_data->PutAttr(val,a_apl_charact_val_charact,charact);
	m_data->PutAttr(val,a_apl_charact_val_num,num);
	
	m_data->PutAttr(val, a_apl_charact_val_act_ver, val_ver);
	
	return true;
}
//*************************************************************
bool CaplCharacteristicManager::LoadCharacteristicChange(CaplInstance *val)
{
	if(val==0) return false;
	if(val->GetAccessmode()>aplRO) return false;

	aplExtent ext;
	ext.Add(val);
	return LoadCharacteristicChange(ext);
}
//*************************************************************
bool CaplCharacteristicManager::LoadCharacteristicChange(aplExtent& ext)
{
	if(ext.Size==0) return false;
	if(!m_api->m_data.IsConnected()) return false;
	bool ok = false;
	CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
	int cnt = ext.Size/m_MaxItemsLoad+1;
	int z=-1;
	for(int j=0; j<cnt; j++)
	{
		for(int i=0; i<m_MaxItemsLoad;i++)
		{
			z++;
			if(z>=ext.Size)
				break;
			if(!m_api->m_data.IsKindOf(ext[z], e_apl_change_charact)) continue;
			if(ext[z]==0) continue;
			if(ext[z]->GetId()==0) continue;
			if(ext[z]->GetType()==0) continue;
			ld.AddQuery(0, ext[z],true);
			ok = true;
		}
		ld.LoadEx();
		ld.ClearQuery();
	}
	if(!ok) return false;
	return true;
}
//*************************************************************
bool CaplCharacteristicManager::FindAssociatedCharacteristicChange(CaplInstance *item, aplExtent &ext, CaplInstance *characreristic /* = 0 */)
{
	if(item==0) return false;
	if(item->GetType()==0) return false;
	if(item->GetAccessmode()>aplRO) return false;
	ext.Clear();
	if(m_api->m_data.IsConnected()) 
	{
		CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
		ld.AddQuery(_T('b'), item->GetId(), e_apl_change_charact, a_apl_change_charact_basis, true,true);
		ld.LoadEx();
	}

	aplExtent tmp_ext;
	m_api->m_data.GetEntityExtent(e_apl_change_charact, tmp_ext);
	CaplInstance *charact, *inst;		
	for(int i=0; i<tmp_ext.Size;i++)
	{
		if(tmp_ext[i]->GetAccessmode()>aplRO) continue;
		m_api->m_data.GetAttr(tmp_ext[i], a_apl_change_charact_basis, inst);
		if(inst!=item) continue;
		m_api->m_data.GetAttr(tmp_ext[i], a_apl_change_charact_charact, charact);
		if(characreristic!=0 && characreristic!=charact) continue;
		ext.Add(tmp_ext[i]);
	}
	return ext.Size>0; //Возвращаем true если таковые объекты найдены
}
//*************************************************************
CaplInstance* CaplCharacteristicManager::ChangeCharactValue(CaplInstance* value, double delta, CaplInstance* bp_inst, CString type/*=_T("delta")*/, CaplInstance **new_val_ver/* =0 */)
{ 
	if(value==0) return 0;
	if(value->GetAccessmode()>aplRW) return 0;
	if(bp_inst==0) return 0;
	if(bp_inst->GetAccessmode()>aplRW) return 0;
	if(!m_api->m_data.IsDictLoad()) return 0;
	if(!m_api->m_data.IsKindOf(value, e_meas_value)) return 0 ;
	if(type!=_T("new_value") && type!=_T("delta")) return 0;
	CaplInstance *new_ver;
	CaplInstance *active;
	m_api->m_data.GetAttr(value, a_apl_charact_val_act_ver, active);
	if(active==0) return 0;
	double dValue;
	m_api->m_data.GetAttr(active, a_apl_charact_val_ver_meas_val, dValue);
	//Создаем новую версию;

		double dTmp;
		CaplInstance *item=0,*itype=0,*charact=0,*char_val=0,*base_ver=0;
		CString scope=_T(""), dt_s;
		int num_of_measurement=0;
		new_ver=m_data->CreateInstance(e_meas_value_ver);
		m_data->GetAttr(value,a_apl_charact_val_meas_min,dTmp);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_meas_min,dTmp);
		m_data->GetAttr(value,a_apl_charact_val_meas_max,dTmp);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_meas_max,dTmp);

		m_data->GetAttr(value,a_apl_charact_val_act_ver,base_ver);
		m_data->GetAttr(value,a_apl_charact_val_scope,scope);
		m_data->GetAttr(value,a_apl_charact_val_type,itype);
		m_data->GetAttr(value,a_apl_charact_val_charact,charact);
		m_data->GetAttr(value,a_apl_charact_val_num,num_of_measurement);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_char_value,value);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_base,base_ver);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_scope,scope);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_type,itype);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_charact,charact);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_num,num_of_measurement);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_is_changed,false);
		COleDateTime dt=COleDateTime::GetCurrentTime();
		aplDate2String(dt,dt_s);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_start_date,dt_s);
		m_data->PutAttr(new_ver,a_apl_charact_val_ver_author,m_data->GetCurrUser());

	if(type==_T("new_value"))
		dValue=delta;
	else if(type==_T("delta"))
		dValue+=delta;
	m_api->m_data.PutAttr(new_ver, a_apl_charact_val_ver_meas_val, dValue);
	m_data->PutAttr(new_ver,a_apl_charact_val_ver_meas_val,dValue);
	m_api->m_data.PutAttr(value, a_apl_charact_val_meas_val, dValue);
	m_api->m_data.PutAttr(value, a_apl_charact_val_act_ver, new_ver);

	//Создаем объект изменение
	CaplInstance* change = m_api->m_data.CreateInstance(e_apl_change_charact);
	ASSERT(change);
	m_api->m_data.PutAttr(change, a_apl_change_charact_charact, value);
	m_api->m_data.PutAttr(change, a_apl_change_charact_type, type);
	m_api->m_data.PutAttr(change, a_apl_change_charact_basis, bp_inst);
	m_api->m_data.PutAttr(change, a_apl_change_charact_delta, delta);
	m_api->m_data.PutAttr(change, a_apl_change_charact_old_val, active);
	m_api->m_data.PutAttr(change, a_apl_change_charact_new_val, new_ver);

	if(new_val_ver)
		*new_val_ver = new_ver;

	if(m_AutoSave)
		m_api->SaveChanges();

	return change;
}
//**************************************************************
bool CaplCharacteristicManager::GetInstancesCharact(CaplMap &map, CaplInstance *charact, CaplInstance *type,bool load_from_bd, int num_izm)
{
	if(charact==0) return false;
	if(map.Size<1) return false;

	int i,j,count=0;
	aplExtent ext;
	CaplInstance *inst;

	map.SortIn();
	for(i=0;i<map.Size;i++)
		(map.Data[i]).out=0;


	if(m_data->IsConnected() && load_from_bd)
	{
		// Ищем в базе. Надо переделать чтобы не читалось лишнее

//		CaplLoadData ld(m_data,DEF_SOURCE);
//		for(i=0;i<map.Size;i++)
//		{
//			if(map.Data[i].in!=0)
//				ld.AddQuery(_T('a'), (CaplInstance*)(map.Data[i].in));
//		}
//  		ld.AddQuery(_T('r'), 0, e_apl_charact_value,a_apl_charact_val_item, true,true);
//		ld.LoadEx(false,&ext);
		
		int count = 0;
		aplExtent tmpExt;

		CString stql,temp1;
		stql.GetBuffer(1024*1024);
		stql.ReleaseBuffer(1024*1024);	
		
		stql=_T("SELECT Ext1 FROM Ext {");

		for(i=0;i<map.Size;i++, ++count)
		{
			if(map.Data[i].in==0)continue;
			inst=(CaplInstance*)map.Data[i].in;
			temp1.Format(_T("#%i"),inst->GetId());
			stql+=temp1;
			if(i<map.Size-1){
				if(map.Data[i+1].in!=0)stql+=_T(",");
			}
			
			if(count == 500 || i == map.Size - 1)
			{
				stql.TrimRight(_T(','));
				stql+=_T("}\n");
				temp1.Format(_T("#%i"),charact->GetId());
				stql+=_T("Ext1 {apl_characteristic_value(.characteristic=")+temp1;
				if(type!=0){
					temp1.Format(_T(" AND .assignment_type=#%i "),type->GetId());
					stql+=temp1;
				}

				if(num_izm>=0){
					temp1.Format(_T(" AND .number_of_measurement=%i "),num_izm);
					stql+=temp1;
				}

				stql+=_T(" AND .item IN #Ext)} END_SELECT");
				if(m_api->m_data.NET_QueryEditParse(stql, false, 0)){
					if(m_api->m_data.NET_QueryExecute(tmpExt, APL_T("Пожалуйста, подождите..."))){
						m_api->m_charact_mgr.LoadCharacteristic(tmpExt, true);
					}else continue;;
				}else continue;

				ext.Append(tmpExt);
				tmpExt.Clear();

				count = 0;
				stql=_T("SELECT Ext1 FROM Ext {");
			}
		}
		

		for(i=0;i<ext.Size;i++)
		{
			inst=ext[i];
			if(!inst) continue;
			if(!inst->GetType()) continue;
			if(inst->GetAccessmode()>aplRO) continue;
			
			CaplInstance *item, *cur_charact, *cur_type;

			m_data->GetAttr(inst,a_apl_charact_val_charact,cur_charact);
			if(charact!=cur_charact) continue;
	
			m_data->GetAttr(inst,a_apl_charact_val_type,cur_type);
			if(type!=cur_type) continue;
			
			m_data->GetAttr(inst,a_apl_charact_val_item,item);
			j=map.QFindByIn((long)item);
			if(j>=0) (map.Data[j]).out=(long)inst;
		}
	} 
	else
	{
		// Соединение с БД нет. Работаем с кэшом.
		m_data->GetEntityExtent(e_apl_charact_value,ext);

		for(i=0;i<ext.Size;i++)
		{
			inst=ext[i];
			if(!inst) continue;
			if(!inst->GetType()) continue;
			if(inst->GetAccessmode()>aplRO) continue;

			CaplInstance *item, *cur_charact, *cur_type;

			m_data->GetAttr(inst,a_apl_charact_val_charact,cur_charact);
			if(charact!=cur_charact) continue;
	
			m_data->GetAttr(inst,a_apl_charact_val_type,cur_type);
			if(type!=cur_type) continue;
			
			m_data->GetAttr(inst,a_apl_charact_val_item,item);
			j=map.QFindByIn((long)item);
			if(j>=0) (map.Data[j]).out=(long)inst;
		}
	}
	return true;
}

int CaplCharacteristicManager::ShowCharacteristicAndTypeDialog(CaplInstance** characteristic, CaplInstance** type, bool &required,bool ext_mode)
{
	if(m_data==0) return IDCANCEL;
	if(characteristic==0 || type==0){return IDCANCEL;}

	CaplSetResourceHandle setres(module_inst);
	CCharacterysticTypeForced dlg;
	dlg.m_api=m_api;
	dlg.m_ext_mode=ext_mode;
	dlg.m_charactteristic=*characteristic;
	dlg.m_type=*type;
	dlg.m_IsRequired=required?TRUE:FALSE;
	if(dlg.DoModal()==IDOK)
	{
		*characteristic=dlg.m_charactteristic;
		*type=dlg.m_type;
		required=dlg.m_IsRequired==TRUE;
		return IDOK;
	}
	return IDCANCEL;

}

bool CaplCharacteristicManager::IsCharacteristicNumber(CaplInstance* item)
{
	if(m_data==0) return false;
	CaplInstance *unit=0;
	if(m_data->IsKindOf(item,e_apl_unit)){
		unit=item;
	}else if(m_data->IsKindOf(item,e_apl_charact)){
		m_data->GetAttr(item,a_apl_charact_unit,unit);
	}else if(m_data->IsKindOf(item,e_apl_charact_value)){
		CaplInstance *apl_char=0;
		m_data->GetAttr(item,a_apl_charact_val_charact,apl_char);
		if(apl_char!=0){
			m_data->GetAttr(apl_char,a_apl_charact_unit,unit);
		}
	}
	if(unit==0)return false;
	if(m_data->IsKindOf(unit,e_apl_step_unit)){
		return true;
	}else if(m_data->IsKindOf(unit,e_apl_monetary_unit)){
		return true;
	}

//	CaplEntity *e_apl_time_unit,*e_apl_enum_unit,*e_apl_monetary_unit;
//	CaplEntity *e_apl_step_unit,*e_apl_named_unit,*e_apl_derived_unit;
//	CaplEntity *e_apl_conv_base_unit,*e_apl_si_unit,*e_apl_cont_dep_unit;
//	CaplEntity *e_table_unit,*e_table_column,*e_apl_reference_unit

	return false;
}

bool CaplCharacteristicManager::IsCharacteristicDate(CaplInstance* item)
{
	if(m_data==0) return false;
	CaplInstance *unit=0;
	if(m_data->IsKindOf(item,e_apl_unit)){
		unit=item;
	}else if(m_data->IsKindOf(item,e_apl_charact)){
		m_data->GetAttr(item,a_apl_charact_unit,unit);
	}else if(m_data->IsKindOf(item,e_apl_charact_value)){
		CaplInstance *apl_char=0;
		m_data->GetAttr(item,a_apl_charact_val_charact,apl_char);
		if(apl_char!=0){
			m_data->GetAttr(apl_char,a_apl_charact_unit,unit);
		}
	}
	if(unit==0)return false;
	if(m_data->IsKindOf(unit,e_apl_time_unit)){
		return true;
	}

//	CaplEntity *e_apl_time_unit,*e_apl_enum_unit,*e_apl_monetary_unit;
//	CaplEntity *e_apl_step_unit,*e_apl_named_unit,*e_apl_derived_unit;
//	CaplEntity *e_apl_conv_base_unit,*e_apl_si_unit,*e_apl_cont_dep_unit;
//	CaplEntity *e_table_unit,*e_table_column,*e_apl_reference_unit

	return false;
}

CaplInstance* CaplCharacteristicManager::CreateCharacteristicAndType(CaplInstance* characteristic, CaplInstance* type, CaplInstance *item,bool required,bool ext_mode,aplExtent *ext_tested)
{
	if(m_data==0) return 0;
	if(e_apl_charact==0) return 0;
	CaplInstance* new_char_type=0;

	if(characteristic==0){
		if(ShowCharacteristicAndTypeDialog(&characteristic,&type,required,ext_mode)==IDCANCEL)
		{
			return 0;
		}
	}
	int i;
	CaplInstance *charact_1,*type_1;

	if(ext_tested!=0){
		for(i=0;i<ext_tested->GetSize();i++){
			m_api->m_data.GetAttr(ext_tested->GetAt(i),m_api->m_charact_mgr.a_apl_characteristic_and_type_characteristic,charact_1);
			m_api->m_data.GetAttr(ext_tested->GetAt(i),m_api->m_charact_mgr.a_apl_characteristic_and_type_type,type_1);
			if(type_1==type && charact_1==characteristic){
				new_char_type=ext_tested->GetAt(i);
				if(m_api->m_ModeInteractive) AfxMessageBox( APL_T("Такая характеристика уже есть!"));
				break;
			}
		}
	}
	if(new_char_type==0){
		new_char_type=m_api->m_data.CreateInstance(e_apl_characteristic_and_type);
	}
	m_api->m_data.PutAttr(new_char_type,a_apl_characteristic_and_type_base_item,item);
	m_api->m_data.PutAttr(new_char_type,a_apl_characteristic_and_type_characteristic,characteristic);
	m_api->m_data.PutAttr(new_char_type,a_apl_characteristic_and_type_type,type);
	m_api->m_data.PutAttr(new_char_type,a_apl_characteristic_and_type_required,required);

	return new_char_type;

}

bool CaplCharacteristicManager::CharacteristicAndTypeProperties(CaplInstance* characteristic_and_type,bool forced_ro,bool ext_mode)
{
	if(m_data==0) return false;
	if(characteristic_and_type==0)return false;
	if(characteristic_and_type->GetType()==0)return false;

	CaplSetResourceHandle setres(module_inst);
	CCharacterysticTypeForced dlg;
	dlg.m_api=m_api;
	dlg.m_ext_mode=ext_mode;

	bool required;
	m_api->m_data.GetAttr(characteristic_and_type,a_apl_characteristic_and_type_characteristic,dlg.m_charactteristic);
	m_api->m_data.GetAttr(characteristic_and_type,a_apl_characteristic_and_type_type,dlg.m_type);
	m_api->m_data.GetAttr(characteristic_and_type,a_apl_characteristic_and_type_required,required);
	if(required){dlg.m_IsRequired=TRUE;}else{dlg.m_IsRequired=FALSE;}
	dlg.m_readonly=(characteristic_and_type->GetAccessmode()>aplRW || forced_ro);
	if(dlg.DoModal()==IDOK){
		m_api->m_data.PutAttr(characteristic_and_type,a_apl_characteristic_and_type_characteristic,dlg.m_charactteristic);
		m_api->m_data.PutAttr(characteristic_and_type,a_apl_characteristic_and_type_type,dlg.m_type);
		m_api->m_data.PutAttr(characteristic_and_type,a_apl_characteristic_and_type_required,dlg.m_IsRequired==TRUE);
	}	
	return true;
}

bool CaplCharacteristicManager::ShowCharactChanges(CaplInstance *characteristic)
{
	if (m_data == 0)
		return false;

	if (characteristic == 0)
		return false;

	if (characteristic->GetType() == 0)
		return false;

	if (characteristic->GetAccessmode() > aplRO)
		return false;

	if (e_apl_charact_value == 0)
		return false;

	if (m_data->IsConnected())
	{
		int i, j;
		CaplLoadData ld(m_data, DEF_SOURCE);
		CaplAttr *a_user = m_data->GetAttrDefinitionBN(_T("apl_user"), _T("name"));
		// ссылка
		i = ld.AddQuery(_T('b'), characteristic->GetId(), m_api->m_change_mgr.e_char_change, m_api->m_change_mgr.a_char_change_val, true);
		
		j = ld.AddQuery(_T('d'), i, 0,m_api->m_change_mgr.a_char_change_val, true);
			ld.AddQuery(_T('d'), j, 0, a_apl_charact_val_act_ver, true);
			
		ld.AddQuery(_T('d'), i, 0, m_api->m_change_mgr.a_chng_item_id, true);
		ld.AddQuery(_T('d'), i, 0, m_api->m_change_mgr.a_chng_item_basis, true);
		  ld.AddQuery(_T('d'), i, 0, m_api->m_change_mgr.a_chng_item_dscr, true);
		  ld.AddQuery(_T('d'), i, 0, m_api->m_change_mgr.a_chng_item_autor, true);
		j=ld.AddQuery(_T('d'), i, 0, m_api->m_change_mgr.a_chng_item_attachment, true);
		  ld.AddQuery(_T('d'), j, 0, m_api->m_doc_mgr.a_apl_stored_document_file_name, true);
		  ld.AddQuery(_T('d'), j, 0, m_api->m_doc_mgr.a_apl_stored_document_source, true);
		  ld.AddQuery(_T('d'), j, 0, m_api->m_doc_mgr.a_apl_assigned_document_location_path, true);
		j=ld.AddQuery(_T('d'), i, 0, m_api->m_change_mgr.a_chng_item_user, true);
		  ld.AddQuery(_T('d'), j, 0, a_user, true);
		j=ld.AddQuery(_T('d'), i, 0, m_api->m_change_mgr.a_char_change_old_rev, true);
		  ld.AddQuery(j,_T('d'), i, 0,m_api->m_change_mgr.a_char_change_new_rev, true);
		  ld.AddQuery(_T('d'), j, 0,a_apl_charact_val_ver_version_num, true);
		  ld.AddQuery(_T('d'), i, 0,m_api->m_change_mgr.a_chng_apply_date, true);
		ld.LoadEx();
	}

	CaplSetResourceHandle setres(module_inst);
	
	CDocChanges dlg;
	dlg.m_api = m_api;
	dlg.m_charact = characteristic;

	dlg.DoModal();
	return true;
}

bool CaplCharacteristicManager::SetupUnitConvertion(CaplInstance *ciPdf, CaplInstance *ciUnit, double dBaseCount)
{
	if(0 == m_api) return false;
	if(false == m_api->m_data.IsConnected()) return false;
	if(0 == ciPdf) return false;
	if(ciPdf->GetAccessmode() > aplRO) return false;
	
	/*if(ciPdf->GetAccessmode() >= aplRO)
	{
		if(m_api->m_ModeInteractive)
			AfxMessageBox( APL_T("Недостаточно прав."), MB_ICONSTOP);

		return false;
	}*/


	bool bReadOnly=false;

	//if(m_api->m_prd_mgr.bNoCreateAndChangePDF) bReadOnly=true;  // ЯАИ: Эта проверка здесь на будущее, если надо будет переделывать
	//else
	{
		if(ciPdf->GetAccessmode()>=aplRO) bReadOnly=true;
		else 
		{
			CString state;
			m_api->m_data.GetAttr(ciPdf, m_api->m_prd_mgr.a_apl_pdf_state, state);

			if( ! ( state==_T("")  || state==_T("working")  || state==_T("changing")))
			{
				bReadOnly=true;
			}
		}
	}


	CaplSetResourceHandle setres(module_inst);

	CUnitConvertionDlg dlg(m_api, ciPdf, ciUnit, dBaseCount);
	dlg.m_bReadOnly=bReadOnly;
	int result = dlg.DoModal();

	return (IDOK == result);
}


void CaplCharacteristicManager::GetPossiblePdfUnits( CaplInstance *ciPdf, aplExtent &unitsExt )
{
	unitsExt.Clear();
	if(0==ciPdf) return;
	if(0==ciPdf->GetType()) return;
	if(ciPdf->GetAccessmode()>aplRO) return;


	aplExtent tmpExt;
	CaplAttrValue val;
	val.attr = m_api->m_charact_mgr.a_apl_unit_convertion_item;
	val.value.Set(ciPdf);

	m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_apl_unit_convertion, 1, &val, tmpExt, false);
	m_api->LoadExtentInfo(tmpExt);	

	CaplInstance *ciAddUnit, *ciBaseUnit;

	m_api->m_data.GetAttr(ciPdf, m_api->m_prd_mgr.a_apl_pdf_unit, ciAddUnit);
	if(0!=ciAddUnit) unitsExt.Add(ciAddUnit);

	int i;
	for(i=0; i<tmpExt.Size; ++i)
	{
		m_api->m_data.GetAttr(tmpExt[i], m_api->m_charact_mgr.a_apl_unit_convertion_add_unit, ciAddUnit);
		m_api->m_data.GetAttr(tmpExt[i], m_api->m_charact_mgr.a_apl_unit_convertion_base_unit, ciBaseUnit);

		if(0!=ciAddUnit) unitsExt.Add(ciAddUnit);
		if(0!=ciBaseUnit) unitsExt.Add(ciBaseUnit);
	}
	
	int option=0;
	m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Изделия\\Дополнить единицы измерения единицами с аналогичным базисом"),option,0);
	if(0!=option)
	{
		aplExtent  ext_pdf_unit;
		m_api->m_unit_exch_mgr.GetPrdUnits(ext_pdf_unit);
		CSortClass::SortExtentByInst(ext_pdf_unit);

		aplExtent extAddUnits, extAppendUnits;
		for(i=0; i<unitsExt.Size;  i++)
		{
			m_api->m_unit_exch_mgr.FindUnitsWithSameBase(unitsExt[i],&extAddUnits);
			if(extAddUnits.GetSize()>0)
			{
				if(0==ext_pdf_unit.GetSize()) extAppendUnits.Append(extAddUnits);
				else
				{
					for(int j=0; j<extAddUnits.GetSize(); j++)
					{
						CaplInstance *unit=extAddUnits[j];
						if(0<=aplQFindInstInExtent(ext_pdf_unit,unit,false)) extAppendUnits.Add(unit);
					}
				}
			}
		}

		if(extAppendUnits.GetSize()>0) unitsExt.Append(extAppendUnits);
	}
}