// ProductManager.cpp

#include "stdafx.h"
#include <aplNetStepData.h>
#include <finder.h>
#include "apl_api.h"
#include "Dlg_pdf_dot.h"
#include "ChangeMkStateDlg.h"
#include "dictionary.h"
#include "DisAsmStatusDlg.h"
#include "ManagerEffectivityDlg.h"
#include "ManagerEffGanttDlg.h"
#include "CaplNrmmManager.h"
#include "ProductCompare.h"
#include "AddDateSn.h"
#include "ProductDlg.h"
#include "ExportProductAttrsDlg.h"
#include "ChangeProductAttrsDlg.h"
#include "SelectLanguageDlg.h"
#include "Helper.h"
#include "FindPKIDlgEx.h"
#include "ChooseConfigDlg.h"
#include "CaplComplectManager.h"

extern bool (*funcLoadAppsInfo)(CaplAPI*, aplExtent&);
extern bool (*funcLoadComplectationsInfo)(CaplAPI*, aplExtent&);
extern bool (*funcFilterByAppOrComplectation)(CaplAPI*, aplExtent&, CaplInstance*, aplExtent&, bool, LPCTSTR);
//extern bool (*funcFilterByApp)(CaplAPI*, aplExtent&, CaplInstance*, aplExtent&, bool);
//extern bool (*funcFilterByComplectation)(CaplAPI*, aplExtent&, CaplInstance*, aplExtent&, bool);

//*************************************************************
bool CaplProductManager::Attach(CaplAPI *api)
{
	if(api==0) {Detach();return false;}

	CaplStepManager::Attach(api);
	m_AllAttrDefined=true;

	bNoCreateAndChangePDF=false;
	funcCompareSN = NULL;
	funcGetPrevSN = NULL;
	funcIntervalIsVerified = NULL;
	funcIsKVZSN = NULL;
	funcGetNextSN = NULL;

	
	CHECK_ZERO_ATTR(e_prd, m_data->GetEntityBN(S::product));
	CHECK_ZERO_ATTR(a_prd_id, m_data->GetAttrDefinition(e_prd,S::id));
	CHECK_ZERO_ATTR(a_prd_name, m_data->GetAttrDefinition(e_prd,S::name));
	CHECK_ZERO_ATTR(a_prd_descr, m_data->GetAttrDefinition(e_prd,S::description));
	CHECK_ZERO_ATTR(a_prd_code, m_data->GetAttrDefinition(e_prd,S::code));
	CHECK_ZERO_ATTR(a_prd_guid, m_data->GetAttrDefinition(e_prd, _T("guid")));

	CHECK_ZERO_ATTR(e_alt, m_data->GetEntityBN(_T("alternate_product_relationship")));
	CHECK_ZERO_ATTR(a_alt_base, m_data->GetAttrDefinition(e_alt,S::base));
	CHECK_ZERO_ATTR(a_alt_alt, m_data->GetAttrDefinition(e_alt,S::alternate));
	CHECK_ZERO_ATTR(a_alt_basis, m_data->GetAttrDefinition(e_alt,S::basis));
	CHECK_ZERO_ATTR(a_alt_name, m_data->GetAttrDefinition(e_alt,S::name));
	CHECK_ZERO_ATTR(a_alt_descr, m_data->GetAttrDefinition(e_alt,S::description));
	CHECK_ZERO_ATTR(a_alt_koeff, m_data->GetAttrDefinition(e_alt,_T("koeff")));

	CHECK_ZERO_ATTR(e_alt_pdf, m_data->GetEntityBN(_T("apl_alternate_pdf_relationship")));
	CHECK_ZERO_ATTR(a_alt_pdf_base, m_data->GetAttrDefinition(e_alt_pdf,S::base));
	CHECK_ZERO_ATTR(a_alt_pdf_alt, m_data->GetAttrDefinition(e_alt_pdf,S::alternate));
	CHECK_ZERO_ATTR(a_alt_pdf_id, m_data->GetAttrDefinition(e_alt_pdf,S::id));
	CHECK_ZERO_ATTR(a_alt_pdf_basis, m_data->GetAttrDefinition(e_alt_pdf,_T("basis")));
	CHECK_ZERO_ATTR(a_alt_pdf_descr, m_data->GetAttrDefinition(e_alt_pdf,S::description));
	CHECK_ZERO_ATTR(a_alt_pdf_koeff, m_data->GetAttrDefinition(e_alt_pdf,_T("koeff")));



	CHECK_ZERO_ATTR(e_pdf, m_data->GetEntityBN(S::pdf));
	CHECK_ZERO_ATTR(a_pdf_id, m_data->GetAttrDefinition(e_pdf,S::id));
	CHECK_ZERO_ATTR(a_pdf_prd, m_data->GetAttrDefinition(e_pdf,S::of_product));
	CHECK_ZERO_ATTR(a_pdf_descr, m_data->GetAttrDefinition(e_pdf,S::description));

	CHECK_ZERO_ATTR(e_apl_pdf, m_data->GetEntityBN(S::apl_pdf));
	CHECK_ZERO_ATTR(a_apl_pdf_state ,  m_data->GetAttrDefinition(e_apl_pdf,_T("state")));
	CHECK_ZERO_ATTR(a_apl_pdf_cp_state ,  m_data->GetAttrDefinition(e_apl_pdf,_T("cp_state")));
	CHECK_ZERO_ATTR(a_pdfwss_source, m_data->GetAttrDefinition(e_apl_pdf,_T("make_or_buy")));
	CHECK_ZERO_ATTR(a_apl_pdf_type, m_data->GetAttrDefinition(e_apl_pdf,S::formation_type));
	CHECK_ZERO_ATTR(a_apl_pdf_standard, m_data->GetAttrDefinition(e_apl_pdf,S::is_standard_part));
	CHECK_ZERO_ATTR(a_apl_pdf_relevance, m_data->GetAttrDefinition(e_apl_pdf,_T("relevance")));
	CHECK_ZERO_ATTR(a_apl_pdf_cataloging_params, m_data->GetAttrDefinition(e_apl_pdf,_T("cataloging_params")));	
	CHECK_ZERO_ATTR(a_pdf_code, m_data->GetAttrDefinition(e_apl_pdf,S::code));
	CHECK_ZERO_ATTR(a_pdf_code1, m_data->GetAttrDefinition(e_apl_pdf,_T("code1")));
	CHECK_ZERO_ATTR(a_pdf_code2, m_data->GetAttrDefinition(e_apl_pdf,_T("code2")));
	CHECK_ZERO_ATTR(a_pdf_okpd_code, m_data->GetAttrDefinition(e_apl_pdf,_T("okpd_code")));
	CHECK_ZERO_ATTR(a_pdf_ils_component, m_data->GetAttrDefinition(e_apl_pdf,_T("ils_component")));
	CHECK_ZERO_ATTR(a_apl_pdf_unit, m_data->GetAttrDefinition(e_apl_pdf,_T("unit")));
	CHECK_ZERO_ATTR(a_apl_pdf_logbook, m_data->GetAttrDefinition(e_apl_pdf,_T("logbook_type")));
	CHECK_ZERO_ATTR(a_apl_pdf_first_usage, m_data->GetAttrDefinition(e_apl_pdf,_T("first_usage")));
	CHECK_ZERO_ATTR(a_apl_pdf_additional_data, m_data->GetAttrDefinition(e_apl_pdf,_T("additional_data")));
	CHECK_ZERO_ATTR(a_apl_pdf_grpz_id,                            m_data->GetAttrDefinition(e_apl_pdf, _T("grpz_id")));
	CHECK_ZERO_ATTR(a_apl_pdf_grpz_name,                          m_data->GetAttrDefinition(e_apl_pdf, _T("grpz_name")));
	CHECK_ZERO_ATTR(a_apl_pdf_grpz_pdf_id,                        m_data->GetAttrDefinition(e_apl_pdf, _T("grpz_pdf_id")));
	CHECK_ZERO_ATTR(a_apl_pdf_average_life_refusal, m_data->GetAttrDefinition(e_apl_pdf,_T("average_life_refusal")));
	CHECK_ZERO_ATTR(a_apl_pdf_par_flow_refusal, m_data->GetAttrDefinition(e_apl_pdf,_T("par_flow_refusal")));
	CHECK_ZERO_ATTR(a_apl_pdf_average_life_removal, m_data->GetAttrDefinition(e_apl_pdf,_T("average_life_removal")));
	CHECK_ZERO_ATTR(a_apl_pdf_locker, m_data->GetAttrDefinition(e_apl_pdf,_T("locker")));
	CHECK_ZERO_ATTR(a_apl_pdf_parent, m_data->GetAttrDefinition(e_apl_pdf,_T("parent")));
	CHECK_ZERO_ATTR(a_apl_pdf_guid, m_data->GetAttrDefinition(e_apl_pdf, _T("guid")));
	CHECK_ZERO_ATTR(a_apl_pdf_refusal_count, m_data->GetAttrDefinition(e_apl_pdf,_T("refusal_count")));

	CHECK_ZERO_ATTR(e_pdr, m_data->GetEntityBN(_T("product_definition_relationship")));
	CHECK_ZERO_ATTR(e_acu, m_data->GetEntityBN(S::acu));
	CHECK_ZERO_ATTR(a_acu_ref_des, m_data->GetAttrDefinition(e_acu,_T("reference_designator")));

	CHECK_ZERO_ATTR(e_nauo, m_data->GetEntityBN(S::nauo));
	CHECK_ZERO_ATTR(e_apl_qacu, m_data->GetEntityBN(S::apl_qacu));
	CHECK_ZERO_ATTR(a_pdr_id, m_data->GetAttrDefinition(e_nauo,S::id));
	CHECK_ZERO_ATTR(a_pdr_name, m_data->GetAttrDefinition(e_nauo,S::name));
	CHECK_ZERO_ATTR(a_pdr_descr, m_data->GetAttrDefinition(e_nauo,S::description));
	CHECK_ZERO_ATTR(a_pdr_r_ting, m_data->GetAttrDefinition(e_nauo,S::relating_pd));
	CHECK_ZERO_ATTR(a_pdr_r_ted, m_data->GetAttrDefinition(e_nauo,S::related_pd));
	CHECK_ZERO_ATTR(a_apl_qacu_unit, m_data->GetAttrDefinition(e_apl_qacu,S::unit_component));
	CHECK_ZERO_ATTR(a_apl_qacu_value, m_data->GetAttrDefinition(e_apl_qacu,S::value_component));
	CHECK_ZERO_ATTR(a_pdr_frames_of_reference, m_data->GetAttrDefinition(e_apl_qacu,_T("apl_frames_of_reference")));
	CHECK_ZERO_ATTR(a_pdr_inner_id,  m_data->GetAttrDefinition(e_nauo, _T("assembly_item_id")));
	CHECK_ZERO_ATTR(a_pdr_parent_reference,  m_data->GetAttrDefinition(e_nauo, _T("parent_reference")));
	CHECK_ZERO_ATTR(a_pdr_parent_reference_type,  m_data->GetAttrDefinition(e_nauo, _T("parent_reference_type")));
	CHECK_ZERO_ATTR(a_pdr_guid, m_data->GetAttrDefinition(e_nauo, _T("guid")));

	CHECK_ZERO_ATTR(e_shared_pdf_rel, m_data->GetEntityBN(_T("shared_pdf_relation")));
	CHECK_ZERO_ATTR(a_shared_pdf_rel_ed, m_data->GetAttrDefinition(e_shared_pdf_rel, _T("related_pdf")));
	CHECK_ZERO_ATTR(a_shared_pdf_rel_ing, m_data->GetAttrDefinition(e_shared_pdf_rel, _T("relating_pdf")));

	CHECK_ZERO_ATTR(e_apl_1c_upload_item,                      m_data->GetEntityBN(_T("apl_1c_upload_item")));
	CHECK_ZERO_ATTR(a_1c_upload_item_zakaz,                    m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("zakaz")));
	CHECK_ZERO_ATTR(a_1c_upload_item_sklad,                    m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("sklad")));
	CHECK_ZERO_ATTR(a_1c_upload_item_ceh,                      m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("ceh")));
	CHECK_ZERO_ATTR(a_1c_upload_item_nn,                       m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("nn")));
	CHECK_ZERO_ATTR(a_1c_upload_item_num_lim,                  m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("num_lim")));
	CHECK_ZERO_ATTR(a_1c_upload_item_pdf_name,                 m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("pdf_name")));
	CHECK_ZERO_ATTR(a_1c_upload_item_pdf_id,                   m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("pdf_id")));
	CHECK_ZERO_ATTR(a_1c_upload_item_export_result,            m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("export_result")));
	CHECK_ZERO_ATTR(a_1c_upload_item_pdf_unit,                 m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("pdf_unit")));
	CHECK_ZERO_ATTR(a_1c_upload_item_type_lim,                 m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("type_lim")));
	CHECK_ZERO_ATTR(a_1c_upload_item_prim_lim,                 m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("prim_lim")));
	CHECK_ZERO_ATTR(a_1c_upload_item_post_date,                m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("post_date")));
	CHECK_ZERO_ATTR(a_1c_upload_item_create_date,              m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("create_date")));
	CHECK_ZERO_ATTR(a_1c_upload_item_color_flag,               m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("color_flag")));
	CHECK_ZERO_ATTR(a_1c_upload_item_kol,                      m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("kol")));
	CHECK_ZERO_ATTR(a_1c_upload_item_last_upload_kol,          m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("prev_kol")));	
	CHECK_ZERO_ATTR(a_1c_upload_item_mat_rel,				   m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("material_relation")));	
	CHECK_ZERO_ATTR(a_1c_upload_item_last_last_upload_kol,     m_data->GetAttrDefinition(e_apl_1c_upload_item, _T("prev_prev_kol")));	
	
	CHECK_ZERO_ATTR(e_limit_change_upload_history,                      m_data->GetEntityBN(_T("apl_limit_change_upload_history")));
	CHECK_ZERO_ATTR(a_limit_change_upload_history_item,                    m_data->GetAttrDefinition(e_limit_change_upload_history, _T("item")));
	CHECK_ZERO_ATTR(a_limit_change_upload_history_zakaz,                    m_data->GetAttrDefinition(e_limit_change_upload_history, _T("zakaz")));
	CHECK_ZERO_ATTR(a_limit_change_upload_history_num_lim,                    m_data->GetAttrDefinition(e_limit_change_upload_history, _T("num_lim")));
	CHECK_ZERO_ATTR(a_limit_change_upload_history_type_lim,                    m_data->GetAttrDefinition(e_limit_change_upload_history, _T("type_lim")));	

	CHECK_ZERO_ATTR(e_pd_eff, m_data->GetEntityBN(_T("product_definition_effectivity")));
	CHECK_ZERO_ATTR(a_pde_id, m_data->GetAttrDefinition(e_pd_eff,S::id));
	CHECK_ZERO_ATTR(a_pde_usage, m_data->GetAttrDefinition(e_pd_eff,S::usage));
	CHECK_ZERO_ATTR(a_pde_prev, m_data->GetAttrDefinition(e_pd_eff,_T("previous")));
	CHECK_ZERO_ATTR(a_pde_not_active, m_data->GetAttrDefinition(e_pd_eff,_T("is_not_active")));

	CHECK_ZERO_ATTR(e_sn_eff, m_data->GetEntityBN(_T("serial_numbered_effectivity")));
	CHECK_ZERO_ATTR(a_sn_eff_start, m_data->GetAttrDefinition(e_sn_eff,_T("effectivity_start_id")));
	CHECK_ZERO_ATTR(a_sn_eff_end, m_data->GetAttrDefinition(e_sn_eff,_T("effectivity_end_id")));

	CHECK_ZERO_ATTR(e_dat_eff, m_data->GetEntityBN(_T("dated_effectivity")));
	CHECK_ZERO_ATTR(a_dat_eff_start_s, m_data->GetAttrDefinition(e_dat_eff,_T("effectivity_start_date_s")));
	CHECK_ZERO_ATTR(a_dat_eff_end_s, m_data->GetAttrDefinition(e_dat_eff,_T("effectivity_end_date_s")));

	CStringArray a_e_pde_dt;
	a_e_pde_dt.Add(_T("apl_configuration_effectivity"));
	a_e_pde_dt.Add(_T("dated_effectivity"));

	if(e_prd!=0) e_dat_eff=m_data->GetComplexEntityBN(a_e_pde_dt);
	else e_dat_eff=0;

	CStringArray a_e_pde_sn;
	a_e_pde_sn.Add(_T("apl_configuration_effectivity"));
	a_e_pde_sn.Add(_T("serial_numbered_effectivity"));
	if(e_prd!=0) e_sn_eff=m_data->GetComplexEntityBN(a_e_pde_sn);
	else e_sn_eff=0;

	CHECK_ZERO_ATTR(e_make_from, m_data->GetEntityBN(_T("apl_make_from_usage_option")));
	CHECK_ZERO_ATTR(e_design_make_from, m_data->GetEntityBN(_T("design_make_from_relationship")));
	CHECK_ZERO_ATTR(a_make_from_ranking, m_data->GetAttrDefinition(e_make_from,_T("ranking")));
	CHECK_ZERO_ATTR(a_make_from_ranking_rationale, m_data->GetAttrDefinition(e_make_from,_T("ranking_rationale")));
	CHECK_ZERO_ATTR(a_make_from_value, m_data->GetAttrDefinition(e_make_from,S::value_component));
	CHECK_ZERO_ATTR(a_make_from_unit, m_data->GetAttrDefinition(e_make_from,S::unit_component));
	CHECK_ZERO_ATTR(a_make_from_derive_value, m_data->GetAttrDefinition(e_make_from,_T("derive_value_component")));
	CHECK_ZERO_ATTR(a_make_from_derive_unit, m_data->GetAttrDefinition(e_make_from,_T("derive_unit_component")));
	CHECK_ZERO_ATTR(a_make_from_assortment, m_data->GetAttrDefinition(e_make_from,_T("apl_assortment")));
	CHECK_ZERO_ATTR(a_make_from_param, m_data->GetAttrDefinition(e_make_from,_T("parameter_of_sortament")));
	CHECK_ZERO_ATTR(a_make_from_waste, m_data->GetAttrDefinition(e_make_from,_T("from_waste")));

	CHECK_ZERO_ATTR(e_spr, m_data->GetEntityBN(_T("supplied_part_relationship")));

	CHECK_ZERO_ATTR(e_assortment, m_data->GetEntityBN(_T("apl_assortment")));
	CHECK_ZERO_ATTR(a_assortment_id, m_data->GetAttrDefinition(e_assortment,S::id));
	CHECK_ZERO_ATTR(a_assortment_name, m_data->GetAttrDefinition(e_assortment,S::name));
	CHECK_ZERO_ATTR(a_assortment_descr, m_data->GetAttrDefinition(e_assortment,S::description));
	CHECK_ZERO_ATTR(a_assortment_std, m_data->GetAttrDefinition(e_assortment,_T("standard")));
	CHECK_ZERO_ATTR(a_assortment_shape, m_data->GetAttrDefinition(e_assortment,_T("shape")));
	CHECK_ZERO_ATTR(a_assortment_dim_name, m_data->GetAttrDefinition(e_assortment,_T("dimension_name")));
	CHECK_ZERO_ATTR(a_assortment_possible_dim, m_data->GetAttrDefinition(e_assortment,_T("possible_dimensions")));

	CHECK_ZERO_ATTR(e_assortment_shape, m_data->GetEntityBN(_T("apl_assortment_shape")));
	CHECK_ZERO_ATTR(a_assortment_shape_id, m_data->GetAttrDefinition(e_assortment_shape,S::id));
	CHECK_ZERO_ATTR(a_assortment_shape_name, m_data->GetAttrDefinition(e_assortment_shape,S::name));
	CHECK_ZERO_ATTR(a_assortment_shape_descr, m_data->GetAttrDefinition(e_assortment_shape,S::description));
	CHECK_ZERO_ATTR(a_assortment_shape_unit, m_data->GetAttrDefinition(e_assortment_shape,_T("unit")));

	CHECK_ZERO_ATTR(e_prd_assortment, m_data->GetEntityBN(_T("apl_product_assortment")));
	CHECK_ZERO_ATTR(a_prd_assortment_prd, m_data->GetAttrDefinition(e_prd_assortment,_T("of_product")));
	CHECK_ZERO_ATTR(a_prd_assortment_assort, m_data->GetAttrDefinition(e_prd_assortment,_T("assortment")));

	CStringArray a_e_qacu_nauo;
	a_e_qacu_nauo.Add(_T("next_assembly_usage_occurrence"));
	a_e_qacu_nauo.Add(S::apl_qacu);
	if(e_prd!=0) e_qacu_nauo=m_data->GetComplexEntityBN(a_e_qacu_nauo);
	else e_qacu_nauo=0;

	CHECK_ZERO_ATTR(e_pdf_subst, m_data->GetEntityBN(_T("product_definition_substitute")));
	CHECK_ZERO_ATTR(a_pdf_subst_id, m_data->GetAttrDefinition(e_pdf_subst,_T("id")));
	CHECK_ZERO_ATTR(a_pdf_subst_name, m_data->GetAttrDefinition(e_pdf_subst,_T("name")));
	CHECK_ZERO_ATTR(a_pdf_subst_description, m_data->GetAttrDefinition(e_pdf_subst,_T("description")));
	CHECK_ZERO_ATTR(a_pdf_subst_pdr, m_data->GetAttrDefinition(e_pdf_subst,_T("context_relationship")));
	CHECK_ZERO_ATTR(a_pdf_subst_pdf, m_data->GetAttrDefinition(e_pdf_subst,_T("substitute_definition")));
	CHECK_ZERO_ATTR(a_pdf_subst_value, m_data->GetAttrDefinition(e_pdf_subst,_T("value_component")));
	CHECK_ZERO_ATTR(a_pdf_subst_unit, m_data->GetAttrDefinition(e_pdf_subst,_T("unit_component")));	
	CHECK_ZERO_ATTR(a_pdf_subst_parent_item, m_data->GetAttrDefinition(e_pdf_subst,_T("parent_item")));	
	CHECK_ZERO_ATTR(a_pdf_subst_guid, m_data->GetAttrDefinition(e_pdf_subst, _T("guid")));

	//Этот кусок добавлен для поддержки обозначений и наименований на различных языках,
	//а также сохранения истории изменения атрибутов изделия.
	CHECK_ZERO_ATTR(e_apl_language, m_data->GetEntityBN(_T("apl_language")));
	CHECK_ZERO_ATTR(a_apl_language_name, m_data->GetAttrDefinition(e_apl_language, _T("name")));
	
	CHECK_ZERO_ATTR(e_apl_export_product, m_data->GetEntityBN(_T("apl_export_product")));
	CHECK_ZERO_ATTR(a_apl_export_product_ofproduct, m_data->GetAttrDefinition(e_apl_export_product, _T("of_product")));
	CHECK_ZERO_ATTR(a_apl_export_product_language, m_data->GetAttrDefinition(e_apl_export_product, _T("language")));
	CHECK_ZERO_ATTR(a_apl_export_product_id, m_data->GetAttrDefinition(e_apl_export_product, _T("id")));
	CHECK_ZERO_ATTR(a_apl_export_product_name, m_data->GetAttrDefinition(e_apl_export_product, _T("name")));
	CHECK_ZERO_ATTR(a_apl_export_product_code, m_data->GetAttrDefinition(e_apl_export_product, _T("code")));
	CHECK_ZERO_ATTR(a_apl_export_product_pdf_id, m_data->GetAttrDefinition(e_apl_export_product, _T("pdf_id")));
	CHECK_ZERO_ATTR(a_apl_export_product_pdf_code, m_data->GetAttrDefinition(e_apl_export_product, _T("pdf_code")));
	CHECK_ZERO_ATTR(a_apl_export_product_pdf_code1, m_data->GetAttrDefinition(e_apl_export_product, _T("pdf_code1")));
	CHECK_ZERO_ATTR(a_apl_export_product_pdf_code2, m_data->GetAttrDefinition(e_apl_export_product, _T("pdf_code2")));
	CHECK_ZERO_ATTR(a_apl_export_product_descr, m_data->GetAttrDefinition(e_apl_export_product, _T("description")));
	
	CHECK_ZERO_ATTR(e_apl_product_attrs_change, m_data->GetEntityBN(_T("apl_product_attrs_change")));
	CHECK_ZERO_ATTR(a_apl_product_attrs_change_item, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("item")));
	CHECK_ZERO_ATTR(a_apl_product_attrs_change_id, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("id")));
	CHECK_ZERO_ATTR(a_apl_product_attrs_change_name, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("name")));
	CHECK_ZERO_ATTR(a_apl_product_attrs_change_code, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("code")));

	CHECK_ZERO_ATTR(a_apl_product_attrs_change_pdf_id, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("pdf_id")));
	CHECK_ZERO_ATTR(a_apl_product_attrs_change_pdf_code, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("pdf_code")));
	CHECK_ZERO_ATTR(a_apl_product_attrs_change_pdf_code1, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("pdf_code1")));
	CHECK_ZERO_ATTR(a_apl_product_attrs_change_pdf_code2, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("pdf_code2")));

	CHECK_ZERO_ATTR(a_apl_product_attrs_change_person, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("person")));
	CHECK_ZERO_ATTR(a_apl_product_attrs_change_datetime, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("datetime")));
	CHECK_ZERO_ATTR(a_apl_product_attrs_change_status, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("status")));
	CHECK_ZERO_ATTR(a_apl_product_attrs_change_next, m_data->GetAttrDefinition(e_apl_product_attrs_change, _T("next")));

	CHECK_ZERO_ATTR(e_comp_mf, m_api->m_data.GetEntityBN(_T("apl_component_make_from")));
	CHECK_ZERO_ATTR(a_comp_mf_id, m_api->m_data.GetAttrDefinition(e_comp_mf,_T("id")));
	CHECK_ZERO_ATTR(a_comp_mf_ting,m_api->m_data.GetAttrDefinition(e_comp_mf,_T("product_definition")));
	CHECK_ZERO_ATTR(a_comp_mf_ted, m_api->m_data.GetAttrDefinition(e_comp_mf,_T("material")));
	CHECK_ZERO_ATTR(a_comp_mf_unit, m_api->m_data.GetAttrDefinition(e_comp_mf,_T("unit")));
	CHECK_ZERO_ATTR(a_comp_mf_value, m_api->m_data.GetAttrDefinition(e_comp_mf,_T("value")));
	CHECK_ZERO_ATTR(a_comp_mf_derived_unit, m_api->m_data.GetAttrDefinition(e_comp_mf,_T("derived_unit")));
	CHECK_ZERO_ATTR(a_comp_mf_derived_value, m_api->m_data.GetAttrDefinition(e_comp_mf,_T("derived_value")));
	CHECK_ZERO_ATTR(a_comp_mf_type_id, m_api->m_data.GetAttrDefinition(e_comp_mf,_T("type_id")));
	CHECK_ZERO_ATTR(a_comp_mf_type, m_api->m_data.GetAttrDefinition(e_comp_mf,_T("type")));
	CHECK_ZERO_ATTR(a_comp_mf_descr, m_api->m_data.GetAttrDefinition(e_comp_mf,_T("description")));
	
	CHECK_ZERO_ATTR(e_order_eff,							m_data->GetEntityBN(_T("apl_order_effectivity")));
	CHECK_ZERO_ATTR(a_order_eff_type,							m_data->GetAttrDefinition(e_order_eff, _T("type")));
	CHECK_ZERO_ATTR(a_order_eff_number,							m_data->GetAttrDefinition(e_order_eff, _T("number")));

	CHECK_ZERO_ATTR(e_rule_rels,		m_data->GetEntityBN(_T("apl_rule_select_relation")));
	CHECK_ZERO_ATTR(a_rule_rels_item,		m_data->GetAttrDefinition(e_rule_rels, _T("item")));
	CHECK_ZERO_ATTR(a_rule_rels_rule,		m_data->GetAttrDefinition(e_rule_rels, _T("rule")));
	CHECK_ZERO_ATTR(a_rule_rels_type,       m_data->GetAttrDefinition(e_rule_rels, _T("relation_type")));
	CHECK_ZERO_ATTR(e_rule_cont,		m_data->GetEntityBN(_T("apl_rule_container")));
	CHECK_ZERO_ATTR(a_rule_cont_rule,		m_data->GetAttrDefinition(e_rule_cont, _T("rule")));

	CHECK_ZERO_ATTR(e_apl_tech_process,                        m_data->GetEntityBN(_T("apl_tech_process")));
	CHECK_ZERO_ATTR(a_tech_process_id,                         m_data->GetAttrDefinition(e_apl_tech_process, _T("id")));
	CHECK_ZERO_ATTR(a_tech_process_pdf,                        m_data->GetAttrDefinition(e_apl_tech_process, _T("pdf")));
	CHECK_ZERO_ATTR(a_tech_process_processing_class,           m_data->GetAttrDefinition(e_apl_tech_process, _T("processing_class")));
	CHECK_ZERO_ATTR(a_tech_process_minimum_quantity,           m_data->GetAttrDefinition(e_apl_tech_process, _T("minimum_quantity")));
	CHECK_ZERO_ATTR(a_tech_process_type,                       m_data->GetAttrDefinition(e_apl_tech_process, _T("type")));
	CHECK_ZERO_ATTR(a_tech_process_author,                     m_data->GetAttrDefinition(e_apl_tech_process, _T("author")));
	CHECK_ZERO_ATTR(a_tech_process_create_date,                m_data->GetAttrDefinition(e_apl_tech_process, _T("create_date")));
	CHECK_ZERO_ATTR(a_tech_process_last_edit_person,           m_data->GetAttrDefinition(e_apl_tech_process, _T("last_edit_person")));
	CHECK_ZERO_ATTR(a_tech_process_last_edit_date,             m_data->GetAttrDefinition(e_apl_tech_process, _T("last_edit_date")));
	CHECK_ZERO_ATTR(a_tech_process_approved_date,              m_data->GetAttrDefinition(e_apl_tech_process, _T("approved_date")));
	CHECK_ZERO_ATTR(a_tech_process_canceled_date,              m_data->GetAttrDefinition(e_apl_tech_process, _T("canceled_date")));
	CHECK_ZERO_ATTR(a_tech_process_ver,                        m_data->GetAttrDefinition(e_apl_tech_process, _T("ver")));
	CHECK_ZERO_ATTR(a_tech_process_xml_material,               m_data->GetAttrDefinition(e_apl_tech_process, _T("xml_material")));
	CHECK_ZERO_ATTR(a_tech_process_xml_material_value,         m_data->GetAttrDefinition(e_apl_tech_process, _T("xml_material_value")));
	CHECK_ZERO_ATTR(a_tech_process_x,               			m_data->GetAttrDefinition(e_apl_tech_process, _T("x")));
	CHECK_ZERO_ATTR(a_tech_process_y,               			m_data->GetAttrDefinition(e_apl_tech_process, _T("y")));
	CHECK_ZERO_ATTR(a_tech_process_z,               			m_data->GetAttrDefinition(e_apl_tech_process, _T("z")));
	CHECK_ZERO_ATTR(a_tech_process_l,               			m_data->GetAttrDefinition(e_apl_tech_process, _T("l")));
	CHECK_ZERO_ATTR(a_tech_process_fiber_direction,             m_data->GetAttrDefinition(e_apl_tech_process, _T("fiber_direction")));	
	CHECK_ZERO_ATTR(a_tech_process_angel_90,					m_data->GetAttrDefinition(e_apl_tech_process, _T("angel_90")));		
	CHECK_ZERO_ATTR(a_tech_process_samples_count,				m_data->GetAttrDefinition(e_apl_tech_process, _T("samples_count")));		
	CHECK_ZERO_ATTR(a_tech_process_lots_count,					m_data->GetAttrDefinition(e_apl_tech_process, _T("lots_count")));		
	CHECK_ZERO_ATTR(a_tech_process_sample_size,					m_data->GetAttrDefinition(e_apl_tech_process, _T("sample_size")));			

	CHECK_ZERO_ATTR(e_apl_supply_contract,                     m_data->GetEntityBN(_T("apl_supply_contract")));
	CHECK_ZERO_ATTR(a_sc_document,                             m_data->GetAttrDefinition(e_apl_supply_contract, _T("document")));
	CHECK_ZERO_ATTR(a_sc_abonent,                              m_data->GetAttrDefinition(e_apl_supply_contract, _T("abonent")));
	CHECK_ZERO_ATTR(a_sc_registration_date,                    m_data->GetAttrDefinition(e_apl_supply_contract, _T("registration_date")));
	CHECK_ZERO_ATTR(a_sc_activation_date,                      m_data->GetAttrDefinition(e_apl_supply_contract, _T("activation_date")));
	CHECK_ZERO_ATTR(a_sc_end_date,                             m_data->GetAttrDefinition(e_apl_supply_contract, _T("end_date")));
	CHECK_ZERO_ATTR(a_sc_notes,                                m_data->GetAttrDefinition(e_apl_supply_contract, _T("notes")));
	CHECK_ZERO_ATTR(a_sc_author,                               m_data->GetAttrDefinition(e_apl_supply_contract, _T("author")));
	CHECK_ZERO_ATTR(a_sc_annulate_date,                        m_data->GetAttrDefinition(e_apl_supply_contract, _T("annulate_date")));	

	CHECK_ZERO_ATTR(e_apl_pez_import_item,                     m_data->GetEntityBN(_T("apl_pez_import_item")));
	CHECK_ZERO_ATTR(a_pez_item_pdf,                            m_data->GetAttrDefinition(e_apl_pez_import_item, _T("pdf")));
	CHECK_ZERO_ATTR(a_pez_item_position,                       m_data->GetAttrDefinition(e_apl_pez_import_item, _T("position")));
	CHECK_ZERO_ATTR(a_pez_item_print_id,                       m_data->GetAttrDefinition(e_apl_pez_import_item, _T("print_id")));
	CHECK_ZERO_ATTR(a_pez_item_print_name,                     m_data->GetAttrDefinition(e_apl_pez_import_item, _T("print_name")));
	CHECK_ZERO_ATTR(a_pez_item_foreign_name,                   m_data->GetAttrDefinition(e_apl_pez_import_item, _T("foreign_name")));
	CHECK_ZERO_ATTR(a_pez_item_print_unit,                     m_data->GetAttrDefinition(e_apl_pez_import_item, _T("print_unit")));
	CHECK_ZERO_ATTR(a_pez_item_price,                          m_data->GetAttrDefinition(e_apl_pez_import_item, _T("price")));
	CHECK_ZERO_ATTR(a_pez_item_count,                          m_data->GetAttrDefinition(e_apl_pez_import_item, _T("count")));	    

	CHECK_ZERO_ATTR(e_apl_tech_operation,                      m_data->GetEntityBN(_T("apl_tech_operation")));
	CHECK_ZERO_ATTR(a_tech_operation_pdf,                      m_data->GetAttrDefinition(e_apl_tech_operation, _T("pdf")));
	CHECK_ZERO_ATTR(a_tech_operation_operation_level,          m_data->GetAttrDefinition(e_apl_tech_operation, _T("operation_level")));
	CHECK_ZERO_ATTR(a_tech_operation_shop,                     m_data->GetAttrDefinition(e_apl_tech_operation, _T("shop")));
	CHECK_ZERO_ATTR(a_tech_operation_level,                    m_data->GetAttrDefinition(e_apl_tech_operation, _T("level")));
	CHECK_ZERO_ATTR(a_tech_operation_fictive,	               m_data->GetAttrDefinition(e_apl_tech_operation, _T("fictive")));
	CHECK_ZERO_ATTR(a_tech_operation_limit,                    m_data->GetAttrDefinition(e_apl_tech_operation, _T("limit")));

	CHECK_ZERO_ATTR(e_kit_unload_item,                         m_data->GetEntityBN(_T("apl_kit_unload_item")));
	CHECK_ZERO_ATTR(a_kit_unload_item_kit,                     m_data->GetAttrDefinition(e_kit_unload_item, _T("kit")));
	CHECK_ZERO_ATTR(a_kit_unload_item_ks,                      m_data->GetAttrDefinition(e_kit_unload_item, _T("ks")));
	CHECK_ZERO_ATTR(a_kit_unload_item_ts,                      m_data->GetAttrDefinition(e_kit_unload_item, _T("ts")));
	CHECK_ZERO_ATTR(a_kit_unload_item_date,                    m_data->GetAttrDefinition(e_kit_unload_item, _T("unload_date")));
	CHECK_ZERO_ATTR(a_kit_unload_item_person,                  m_data->GetAttrDefinition(e_kit_unload_item, _T("person")));
	
	CHECK_ZERO_ATTR(e_apl_complectation_card,                  m_data->GetEntityBN(_T("apl_complectation_card")));
	CHECK_ZERO_ATTR(a_complectation_card_parent_pdf,           m_data->GetAttrDefinition(e_apl_complectation_card, _T("parent_pdf")));
	CHECK_ZERO_ATTR(a_complectation_card_id,		           m_data->GetAttrDefinition(e_apl_complectation_card, _T("id")));
	CHECK_ZERO_ATTR(a_complectation_card_name,		           m_data->GetAttrDefinition(e_apl_complectation_card, _T("name")));
	CHECK_ZERO_ATTR(a_complectation_card_stage,		           m_data->GetAttrDefinition(e_apl_complectation_card, _T("stage")));
	CHECK_ZERO_ATTR(a_complectation_card_dscr,		           m_data->GetAttrDefinition(e_apl_complectation_card, _T("description_ex")));
	CHECK_ZERO_ATTR(a_complectation_card_time,		           m_data->GetAttrDefinition(e_apl_complectation_card, _T("time")));

	CHECK_ZERO_ATTR(e_apl_mat_limit_change_rel,                m_data->GetEntityBN(_T("apl_material_limit_change_rel")));
	CHECK_ZERO_ATTR(a_mat_limit_change_rel_pdf,                m_data->GetAttrDefinition(e_apl_mat_limit_change_rel, _T("pdf")));
	CHECK_ZERO_ATTR(a_mat_limit_change_rel_basis,              m_data->GetAttrDefinition(e_apl_mat_limit_change_rel, _T("basis")));

	CHECK_ZERO_ATTR(e_apl_mat_limit_change_basis,              m_data->GetEntityBN(_T("apl_material_limit_change_basis")));
	CHECK_ZERO_ATTR(a_mat_limit_change_basis_id,               m_data->GetAttrDefinition(e_apl_mat_limit_change_basis, _T("id")));
	CHECK_ZERO_ATTR(a_mat_limit_change_basis_pdf,               m_data->GetAttrDefinition(e_apl_mat_limit_change_basis, _T("pdf")));
	CHECK_ZERO_ATTR(a_mat_limit_change_basis_person,             m_data->GetAttrDefinition(e_apl_mat_limit_change_basis, _T("person")));
	CHECK_ZERO_ATTR(a_mat_limit_change_basis_date_create,      m_data->GetAttrDefinition(e_apl_mat_limit_change_basis, _T("date_create")));
	CHECK_ZERO_ATTR(a_mat_limit_change_basis_date_approved,    m_data->GetAttrDefinition(e_apl_mat_limit_change_basis, _T("date_approved")));
	CHECK_ZERO_ATTR(a_mat_limit_change_basis_state,				m_data->GetAttrDefinition(e_apl_mat_limit_change_basis, _T("state")));	

	CHECK_ZERO_ATTR(e_apl_mat_limit_change_item,               m_data->GetEntityBN(_T("apl_material_limit_change_item")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_descr,            m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("description")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_change,            m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("change")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_date,              m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("date")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_delta,             m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("delta")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_new_value,          m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("new_value")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_relation,            m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("relation")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_material_relation, m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("material_relation")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_new_material, m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("new_material")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_old_material, m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("old_material")));
	
	CHECK_ZERO_ATTR(a_mat_limit_change_item_old_warehouse, m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("old_warehouse")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_new_warehouse, m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("new_warehouse")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_old_shop, m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("old_shop")));
	CHECK_ZERO_ATTR(a_mat_limit_change_item_new_shop, m_data->GetAttrDefinition(e_apl_mat_limit_change_item, _T("new_shop")));
	
	CHECK_ZERO_ATTR(e_apl_tech_process_operation,              m_data->GetEntityBN(_T("apl_tech_process_operation")));
	CHECK_ZERO_ATTR(a_tpo_production_time,                     m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("production_time")));
	CHECK_ZERO_ATTR(a_tpo_laboriousness,                       m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("laboriousness")));
	CHECK_ZERO_ATTR(a_tpo_worker_category,                     m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("worker_category")));
	CHECK_ZERO_ATTR(a_tpo_id,                                  m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("id")));
	CHECK_ZERO_ATTR(a_tpo_operation,                           m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("operation")));
	CHECK_ZERO_ATTR(a_tpo_process,                             m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("process")));
	CHECK_ZERO_ATTR(a_tpo_profession,                          m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("profession")));
	CHECK_ZERO_ATTR(a_tpo_work_condition,                      m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("work_condition")));
	CHECK_ZERO_ATTR(a_tpo_workers_count,                       m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("workers_count")));
	CHECK_ZERO_ATTR(a_tpo_units_at_same_time,                  m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("units_at_same_time")));
	CHECK_ZERO_ATTR(a_tpo_preporation_time,                    m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("preporation_time")));
	CHECK_ZERO_ATTR(a_tpo_one_unit_time,                       m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("one_unit_time")));
	CHECK_ZERO_ATTR(a_tpo_limit_operation,                     m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("limit_operation")));
	CHECK_ZERO_ATTR(a_tpo_fictive_operation,                   m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("fictive_operation")));
	CHECK_ZERO_ATTR(a_tpo_laboriousness_show_in_minutes,       m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("laboriousness_show_in_minutes")));
	CHECK_ZERO_ATTR(a_tpo_locker,							   m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("locker")));	
	CHECK_ZERO_ATTR(a_tpo_check_out_date,							   m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("check_out_date")));	
	CHECK_ZERO_ATTR(a_tpo_check_in_date,							   m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("check_in_date")));	
	CHECK_ZERO_ATTR(a_tpo_edit_person,							   m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("edit_person")));		
	CHECK_ZERO_ATTR(a_tpo_new_revision,							   m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("new_revision")));		
	CHECK_ZERO_ATTR(a_tpo_base_revision,							   m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("base_revison")));		
	CHECK_ZERO_ATTR(a_tpo_internal_number,							   m_data->GetAttrDefinition(e_apl_tech_process_operation, _T("internal_number")));	
	
	CStringArray a_e_pde_order;
	a_e_pde_order.Add(_T("apl_configuration_effectivity"));
	a_e_pde_order.Add(_T("apl_order_effectivity"));

	if(e_prd!=0) e_order_eff=m_data->GetComplexEntityBN(a_e_pde_order);
	else e_order_eff=0;

	m_list_pdf_types.RemoveAll();
	m_list_pdf_types.Add( APL_T("Сборочная единица"));
	m_list_pdf_types.Add( APL_T("Материал"));
	m_list_pdf_types.Add( APL_T("Комплект"));
	m_list_pdf_types.Add( APL_T("Комплекс"));
	m_list_pdf_types.Add( APL_T("Зона"));
	m_list_pdf_types.Add( APL_T("Программный модуль"));
	m_list_pdf_types.Add( APL_T("Система"));
	m_list_pdf_types.Add( APL_T("Деталь"));
	m_list_pdf_types.Add( APL_T("Прочее"));

	m_list_mob_types.Add( APL_T("Не известно"));
	m_list_mob_types.Add( APL_T("Покупное"));
	m_list_mob_types.Add( APL_T("Изготовляемое"));	

	m_techProcessType.push_back(std::make_pair(APL_T("Основной"), _T("main")));
	m_techProcessType.push_back(std::make_pair(APL_T("Резервный"), _T("Reserve")));

	m_techProcessClass.push_back(std::make_pair(APL_T("На универсальном участке"), _T("universal")));
	m_techProcessClass.push_back(std::make_pair(APL_T("На станке с ЧПУ"), _T("numeric")));	

	m_kvzTermoShops.insert(_T("013"));
	m_kvzTermoShops.insert(_T("018"));
	m_kvzTermoShops.insert(_T("031"));
	m_kvzTermoShops.insert(_T("035"));
	m_kvzTermoShops.insert(_T("036"));
	m_kvzTermoShops.insert(_T("045"));
	m_kvzTermoShops.insert(_T("005"));
	m_kvzTermoShops.insert(_T("008"));
	m_kvzTermoShops.insert(_T("043"));
	m_kvzTermoShops.insert(_T("037"));	

	return true;
}

//*************************************************************
void CaplProductManager::Detach()
{
	m_data=NULL;

	e_prd=0; a_prd_id=0;  a_prd_name=0; a_prd_descr=0; a_prd_guid=0;
	e_pdf=0; a_pdf_id=0;  a_pdf_prd=0;  a_pdf_descr=0; 
	e_apl_pdf=0; a_apl_pdf_type=0;  a_apl_pdf_standard=0; a_pdfwss_source=0; 
	a_apl_pdf_relevance=0;
	a_pdf_code=0; a_pdf_code1=0; a_pdf_code1=0;  a_apl_pdf_unit=0;
	a_apl_pdf_cp_state = 0;
	a_apl_pdf_first_usage=0; a_apl_pdf_guid=0;
	a_apl_pdf_average_life_refusal=0; a_apl_pdf_par_flow_refusal=0; a_apl_pdf_average_life_removal=0;
	e_acu=0;a_acu_ref_des=0; e_pdr=0; e_qacu_nauo=0;
	a_pdr_id=0;  a_pdr_name=0; a_pdr_descr=0;  a_pdr_r_ting=0; a_pdr_r_ted=0; 
	e_apl_qacu=0; a_apl_qacu_unit=0; a_apl_qacu_value=0; a_pdr_guid=0;
	a_pdr_frames_of_reference=0;
	a_pdr_inner_id= 0;
	a_apl_pdf_logbook = NULL;
	a_apl_pdf_additional_data = NULL;
	a_pdr_parent_reference= NULL;
	a_pdr_parent_reference_type = NULL;
	a_apl_pdf_locker= NULL;
	a_apl_pdf_parent= NULL;
	a_apl_pdf_refusal_count = NULL;
	a_pdf_okpd_code = NULL;
	a_pdf_ils_component = NULL;

	e_shared_pdf_rel = NULL;
	a_shared_pdf_rel_ed = NULL;
	a_shared_pdf_rel_ing = NULL;

	e_kit_unload_item = NULL;
	a_kit_unload_item_kit = NULL;
	a_kit_unload_item_ks = NULL;
	a_kit_unload_item_ts = NULL;
	a_kit_unload_item_date = NULL;
	a_kit_unload_item_person = NULL;

	e_limit_change_upload_history = NULL;
	a_limit_change_upload_history_item = NULL;
	a_limit_change_upload_history_zakaz = NULL;
	a_limit_change_upload_history_num_lim = NULL;
	a_limit_change_upload_history_type_lim = NULL;

	e_apl_1c_upload_item = NULL;
	a_1c_upload_item_zakaz = NULL;
	a_1c_upload_item_sklad = NULL;
	a_1c_upload_item_ceh = NULL;
	a_1c_upload_item_nn = NULL;
	a_1c_upload_item_num_lim = NULL;
	a_1c_upload_item_pdf_name = NULL;
	a_1c_upload_item_pdf_id = NULL;
	a_1c_upload_item_export_result = NULL;
	a_1c_upload_item_pdf_unit = NULL;
	a_1c_upload_item_type_lim = NULL;
	a_1c_upload_item_prim_lim = NULL;
	a_1c_upload_item_post_date = NULL;
	a_1c_upload_item_color_flag = NULL;
	a_1c_upload_item_kol = NULL;
	a_1c_upload_item_last_upload_kol = NULL;
	a_1c_upload_item_create_date = NULL;	
	a_1c_upload_item_mat_rel = NULL;
	a_1c_upload_item_last_last_upload_kol = NULL;

	e_alt=0; a_alt_base=0;a_alt_alt=0;a_alt_basis=0;a_alt_name=0;a_alt_descr=0;a_alt_koeff=0;
	e_alt_bidir=0;a_alt_bidir_type=0;a_alt_bidir_type_descr=0;a_alt_bidir_reserved=0;

	e_alt_pdf=0;		
	a_alt_pdf_base=0; a_alt_pdf_alt=0; 	a_alt_pdf_id=0; a_alt_pdf_basis=0;  a_alt_pdf_descr=0;  a_alt_pdf_koeff=0;

	e_pd_eff=0; a_pde_id=0; a_pde_usage=0; 
	e_sn_eff=0; a_sn_eff_start=0; a_sn_eff_end=0; 
	e_dat_eff=0; a_dat_eff_start_s=0; a_dat_eff_end_s=0; 

	e_make_from=0; e_design_make_from=0;
	a_make_from_ranking=0; a_make_from_ranking_rationale=0;
	a_make_from_value=0; a_make_from_unit=0;
	a_make_from_derive_value=0; a_make_from_derive_unit=0;
	a_make_from_assortment=0; a_make_from_param=0;

	e_apl_tech_process_operation = NULL;
	a_tpo_production_time = NULL;
	a_tpo_laboriousness = NULL;
	a_tpo_worker_category = NULL;
	a_tpo_id = NULL;
	a_tpo_operation = NULL;
	a_tpo_process = NULL;
	a_tpo_profession = NULL;
	a_tpo_work_condition = NULL;
	a_tpo_workers_count = NULL;
	a_tpo_limit_operation = NULL;
	a_tpo_fictive_operation = NULL;
	a_tpo_units_at_same_time = NULL;
	a_tpo_laboriousness_show_in_minutes = NULL;
	a_tpo_preporation_time = NULL;
	a_tpo_one_unit_time = NULL;
	a_tpo_locker = NULL;
	a_tpo_check_out_date = NULL;
	a_tpo_check_in_date = NULL;
	a_tpo_edit_person = NULL;
	a_tpo_base_revision = NULL;
	a_tpo_new_revision = NULL;
	a_tpo_internal_number = NULL;

	e_apl_pez_import_item = NULL;
	a_pez_item_pdf = NULL;
	a_pez_item_position = NULL;
	a_pez_item_print_id = NULL;
	a_pez_item_print_name = NULL;
	a_pez_item_foreign_name = NULL;
	a_pez_item_print_unit = NULL;
	a_pez_item_price = NULL;
	a_pez_item_count = NULL;

	e_apl_supply_contract = NULL;
	a_sc_document = NULL;
	a_sc_abonent = NULL;
	a_sc_annulate_date = NULL;
	a_sc_registration_date = NULL;
	a_sc_activation_date = NULL;
	a_sc_end_date = NULL;
	a_sc_notes = NULL;
	a_sc_author = NULL;

	a_pdf_code=0; a_prd_code=0;

	e_assortment=0; e_assortment_shape=0; e_prd_assortment=0; 
	a_assortment_id=0; a_assortment_name=0; a_assortment_descr=0; 
	a_assortment_std=0; a_assortment_shape=0; a_assortment_dim_name=0; a_assortment_possible_dim=0; 
	a_assortment_shape_id=0; a_assortment_shape_name=0; a_assortment_shape_descr=0; a_assortment_shape_unit=0; 
	a_prd_assortment_prd=0; a_prd_assortment_assort=0; 

	e_spr=0;

	e_pdf_subst=0;
	a_pdf_subst_id=0;a_pdf_subst_name=0;a_pdf_subst_description=0;
	a_pdf_subst_pdr=0;a_pdf_subst_pdf=0;
	a_pdf_subst_value=0;a_pdf_subst_unit=0;	
	a_pdf_subst_parent_item = NULL;
	a_pdf_subst_guid = 0;

	e_apl_language = NULL;
	a_apl_language_name = NULL;
	
	e_apl_export_product = NULL;
	a_apl_export_product_ofproduct = NULL;
	a_apl_export_product_language = NULL;
	a_apl_export_product_id = NULL;
	a_apl_export_product_name = NULL;
	a_apl_export_product_code = NULL;
	a_apl_export_product_descr = NULL;

	e_apl_tech_process = NULL;
	a_tech_process_id = NULL;
	a_tech_process_pdf = NULL;
	a_tech_process_processing_class = NULL;
	a_tech_process_minimum_quantity = NULL;
	a_tech_process_type = NULL;
	a_tech_process_author = NULL;
	a_tech_process_create_date = NULL;
	a_tech_process_last_edit_person = NULL;
	a_tech_process_last_edit_date = NULL;
	a_tech_process_approved_date = NULL;
	a_tech_process_canceled_date = NULL;
	a_tech_process_ver = NULL;
	a_tech_process_xml_material = NULL;
	a_tech_process_xml_material_value = NULL;
	a_tech_process_x = NULL;
	a_tech_process_y = NULL;
	a_tech_process_z = NULL;
	a_tech_process_l = NULL;
	a_tech_process_fiber_direction = NULL;
	a_tech_process_angel_90 = NULL;
	a_tech_process_samples_count = NULL;
	a_tech_process_lots_count = NULL;
	a_tech_process_sample_size = NULL;

	e_apl_tech_operation = NULL;
	a_tech_operation_pdf = NULL;
	a_tech_operation_operation_level = NULL;
	a_tech_operation_shop = NULL;
	a_tech_operation_level = NULL;
	a_tech_operation_fictive = NULL;
	a_tech_operation_limit = NULL;

	e_apl_complectation_card = NULL;
	a_complectation_card_parent_pdf = NULL;
	a_complectation_card_id = NULL;
	a_complectation_card_name = NULL;
	a_complectation_card_stage = NULL;
	a_complectation_card_dscr = NULL;
	a_complectation_card_time = NULL;

	e_apl_product_attrs_change = NULL;
	a_apl_product_attrs_change_item = NULL;
	a_apl_product_attrs_change_id = NULL;
	a_apl_product_attrs_change_name = NULL;
	a_apl_product_attrs_change_code = NULL;
	a_apl_product_attrs_change_person = NULL;
	a_apl_product_attrs_change_datetime = NULL;
	a_apl_product_attrs_change_status = NULL;
	a_apl_product_attrs_change_next = NULL;
	a_apl_product_attrs_change_pdf_id = NULL;
	a_apl_product_attrs_change_pdf_code = NULL;
	a_apl_product_attrs_change_pdf_code1 = NULL;
	a_apl_product_attrs_change_pdf_code2 = NULL;

	e_order_eff = NULL;
	a_order_eff_type = NULL;
	a_order_eff_number = NULL;
	
	e_rule_rels= NULL;
	a_rule_rels_item= NULL;
	a_rule_rels_rule= NULL;
	a_rule_rels_type= NULL;
	e_rule_cont= NULL;
	a_rule_cont_rule= NULL;

	e_apl_mat_limit_change_rel = NULL;  
	a_mat_limit_change_rel_pdf = NULL; 
	a_mat_limit_change_rel_basis = NULL;

	e_apl_mat_limit_change_basis = NULL;
	a_mat_limit_change_basis_id = NULL;
	a_mat_limit_change_basis_pdf = NULL;
	a_mat_limit_change_basis_person = NULL;
	a_mat_limit_change_basis_date_create = NULL;
	a_mat_limit_change_basis_date_approved = NULL;
	a_mat_limit_change_basis_state = NULL;

	e_apl_mat_limit_change_item = NULL;
	a_mat_limit_change_item_change = NULL;
	a_mat_limit_change_item_descr = NULL;
	a_mat_limit_change_item_date = NULL;
	a_mat_limit_change_item_delta = NULL;
	a_mat_limit_change_item_relation = NULL;
	a_mat_limit_change_item_new_value = NULL;
	a_mat_limit_change_item_material_relation = NULL;
	a_mat_limit_change_item_new_material = NULL;
	a_mat_limit_change_item_old_material = NULL;
	a_mat_limit_change_item_old_warehouse = NULL;
	a_mat_limit_change_item_new_warehouse = NULL;
	a_mat_limit_change_item_old_shop = NULL;
	a_mat_limit_change_item_new_shop = NULL;
} 

//*************************************************************
// Пустышки функций на случай отсутствия aplCompareSN.dll"

BOOL InitCompareLib_Default(CaplAPI *pAPI) {return TRUE;}
BOOL IntervalIsVerified_Default(CString &sn1, CString &sn2) {return FALSE;}
BOOL IsKVZSN_Default(CString &sn) {return FALSE;}
		
int CompareSN_Default(CString &sn1, CString &sn2)
{
	if (sn1.GetLength() != sn2.GetLength())
	{
		if (sn1.GetLength() > sn2.GetLength())
			return 1;
		else
			return -1;
	}
	return sn1.Compare(sn2);
}

//*************************************************************


CString GetPrevSN_Default(CString &sn)
{
	CString strSymbol = APL_NO_T("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщьыъэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯ");
	if(sn.IsEmpty())
		return _T("");
	CString strPrev = sn;
	BOOL bShouldBeCut = TRUE;

	if (strPrev.IsEmpty())
		return strPrev;

	for (int iIndex = 0; iIndex < strPrev.GetLength(); iIndex++)
	{
		if (strPrev[iIndex] != strSymbol[0])
		{
			bShouldBeCut = FALSE;
			break;
		}
	}

	if (bShouldBeCut)
	{
		strPrev.Empty();

		for (int iIndex = 0; iIndex < (sn.GetLength() - 1); iIndex++)
			strPrev += strSymbol[strSymbol.GetLength() - 1];

		return strPrev;
	}

	for (int iIndex = 0; iIndex < strPrev.GetLength(); iIndex++)
	{
		BOOL bChangePrevSymbol = FALSE;
		int  iFoundItemIndex = strSymbol.Find(strPrev[strPrev.GetLength() - iIndex - 1]);

		if (iFoundItemIndex != -1)
		{
			if (iFoundItemIndex == 0)				
			{
				strPrev.SetAt(strPrev.GetLength() - iIndex - 1, strSymbol[strSymbol.GetLength() - 1]);
				bChangePrevSymbol = TRUE;
			}
			else
				strPrev.SetAt(strPrev.GetLength() - iIndex - 1, strSymbol[iFoundItemIndex - 1]);
		}
		else
			strPrev.SetAt(strPrev.GetLength() - iIndex - 1, strSymbol[strSymbol.GetLength() - 1]);

		if (!bChangePrevSymbol)
			break;
	}
	return strPrev;
}

CString GetNextSN_Default(CString &sn)
{
	CString strSymbol = APL_NO_T("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщьыъэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯ");
	if(sn.IsEmpty())
		return _T("");
	CString strNext = sn;

	BOOL bShouldBeExpanded = TRUE;

	for (int iIndex = 0; iIndex < strNext.GetLength(); iIndex++)
	{
		if (strNext[iIndex] != strSymbol[strSymbol.GetLength() - 1])
		{
			bShouldBeExpanded = FALSE;
			break;
		}
	}

	if (bShouldBeExpanded)
	{
		strNext.Empty();

		for (int iIndex = 0; iIndex < (sn.GetLength() + 1); iIndex++)
			strNext += strSymbol[0];

		return strNext;
	}

	for (int iIndex = 0; iIndex < strNext.GetLength(); iIndex++)
	{
		BOOL bChangePrevSymbol = FALSE;
		int  iFoundItemIndex = strSymbol.Find(strNext[strNext.GetLength() - iIndex - 1]);

		if (iFoundItemIndex != -1)
		{
			if (iFoundItemIndex == (strSymbol.GetLength() - 1))
			{
				strNext.SetAt(strNext.GetLength() - iIndex - 1, strSymbol[0]);
				bChangePrevSymbol = TRUE;
			}
			else
				strNext.SetAt(strNext.GetLength() - iIndex - 1, strSymbol[iFoundItemIndex + 1]);
		}
		else
			strNext.SetAt(strNext.GetLength() - iIndex - 1, strSymbol[0]);

		if (!bChangePrevSymbol)
			break;
	}

	return strNext;
}



//*************************************************************
BOOL CaplProductManager::InitCompareSNLibrary()
{
#ifdef _DEBUG
	CString strLibraryName = CString(_T("aplCompareSN_D.dll"));
#else
	CString strLibraryName = CString(_T("aplCompareSN.dll"));
#endif

	HINSTANCE hCompareSNLibDLL = NULL;		
	int (*funcInitSN)(CaplAPI*) = NULL;

	hCompareSNLibDLL = AfxLoadLibrary(strLibraryName);

	if (hCompareSNLibDLL == NULL)
	{
		funcInitSN=&InitCompareLib_Default;
		funcIsKVZSN=&IsKVZSN_Default;
		funcIntervalIsVerified=&IntervalIsVerified_Default;
		funcCompareSN=&CompareSN_Default;
		funcGetPrevSN=&GetPrevSN_Default;
		funcGetNextSN=&GetNextSN_Default;

		return FALSE;
	}

	(FARPROC&)funcInitSN = ::GetProcAddress(hCompareSNLibDLL, "InitCompareLib");

	if (funcInitSN == NULL)
		return FALSE;

	funcInitSN(m_api);

	(FARPROC&)funcCompareSN = ::GetProcAddress(hCompareSNLibDLL, "CompareSN");

	if (funcCompareSN == NULL)
		return FALSE;

	(FARPROC&)funcGetPrevSN = ::GetProcAddress(hCompareSNLibDLL, "GetPrevSN");

	if (funcGetPrevSN == NULL)
		return FALSE;

	(FARPROC&)funcGetNextSN = ::GetProcAddress(hCompareSNLibDLL, "GetNextSN");

	if (funcGetNextSN == NULL)
		return FALSE;

	(FARPROC&)funcIsKVZSN = ::GetProcAddress(hCompareSNLibDLL, "IsKVZSN");

	if (funcIsKVZSN == NULL)
		return FALSE;

	(FARPROC&)funcIntervalIsVerified = ::GetProcAddress(hCompareSNLibDLL, "IntervalIsVerified");

	if (funcIntervalIsVerified == NULL)
		return FALSE;

	return TRUE;
}

/************************************************************************/

void CaplProductManager::FillTechProcessTypeCombo(CComboBox &combo, CaplInstance *process)
{
	CString str;
	if(process)
		m_data->GetAttr(process, a_tech_process_type, str);

	combo.ResetContent();
	for(unsigned int i=0; i<m_techProcessType.size(); ++i)
	{
		combo.AddString(m_techProcessType[i].first);
		if(0 == m_techProcessType[i].second.CompareNoCase(str))
			combo.SetCurSel(i);
	}

	if(0 == process)
		combo.SetCurSel(0);
}

void CaplProductManager::FillTechProcessClassCombo(CComboBox &combo, CaplInstance *process)
{
	CString str;
	if(process)
		m_data->GetAttr(process, a_tech_process_processing_class, str);

	combo.ResetContent();
	for(unsigned int i=0; i<m_techProcessClass.size(); ++i)
	{
		combo.AddString(m_techProcessClass[i].first);
		if(0 == m_techProcessClass[i].second.CompareNoCase(str))
			combo.SetCurSel(i);
	}

	if(0 == process && m_techProcessClass.size() >= 2)
		combo.SetCurSel(1);	
}

void CaplProductManager::SaveTechProcessClass(const CString &str, CaplInstance *process)
{
	if(false == str.IsEmpty() && 0 != process)
	{
		for(unsigned int i=0; i<m_techProcessClass.size(); ++i)
		{
			if(0 == m_techProcessClass[i].first.CompareNoCase(str))
			{
				m_data->PutAttr(process, a_tech_process_processing_class, m_techProcessClass[i].second);
				break;
			}
		}
	}
}

void CaplProductManager::SaveTechProcessClass(CComboBox &combo, CaplInstance *process)
{
	CString str;

	combo.GetWindowText(str);
	SaveTechProcessClass(str, process);
}

void CaplProductManager::SaveTechProcessType(const CString &type, CaplInstance *process)
{
	if(false == type.IsEmpty() && 0 != process)
	{
		for(unsigned int i=0; i<m_techProcessType.size(); ++i)
		{
			if(0 == m_techProcessType[i].first.CompareNoCase(type))
			{
				m_data->PutAttr(process, a_tech_process_type, m_techProcessType[i].second);
				break;
			}
		}
	}
}

bool CaplProductManager::IsGalvanicKvzShop(LPCTSTR shop)
{
	CString value(shop);
	if(value.GetLength() == 2) value = _T("0") + value;

	return (m_kvzTermoShops.find(value) != m_kvzTermoShops.end());
}

void CaplProductManager::SaveTechProcessType(CComboBox &combo, CaplInstance *process)
{
	CString str;

	combo.GetWindowText(str);
	SaveTechProcessType(str, process);
}	

//*************************************************************
bool CaplProductManager::LoadAllSubProduct(CaplInstance *ci, CaplInstance *context,
		CaplInstance *pdf, aplExtent &ext_rel, aplExtent &ext_pdf, bool from_base)
{
	ext_rel.Clear();
	ext_pdf.Clear();
	if(m_data==0) return false;
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	};
	if(pdf->GetType()==0) return false;
	if(e_apl_qacu==0) return false;
	if(e_prd==0) return false;
	if(!m_data->IsKindOf(pdf,e_pdf))return false;

	int i;
	aplExtent ext0;
	if(from_base)
	{
		if((m_data->IsConnected())&&(pdf->GetId()!=0))
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
			int i1,i8,i12,i14,i27,i28;
			i1=	ld.AddQuery(_T('b'), pdf->GetId(), e_apl_qacu, a_pdr_r_ting, true,true);
			i8=	ld.AddQuery(_T('d'), i1, 0, a_pdr_r_ted, true,true);
			i12=ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);
			// чтение effectivity
			i14=ld.AddQuery(_T('r'), i1, e_pd_eff, a_pde_usage, true,true);
			// правила
			i27=ld.AddQuery(_T('r'), i1, e_rule_rels, a_rule_rels_item, true,true);
			i28=ld.AddQuery(_T('d'), i27, 0, a_rule_rels_rule, true,true);
				if (!ld.LoadEx()){
					if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
						if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
					}
				}
		}
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}
	m_data->GetEntityExtent(e_apl_qacu,ext0);
	for(i=0;i<ext0.Size;i++)
	{
		if(m_bContinue)
		{
			if(*m_bContinue==false) break;
		}
		CaplInstance *inst0,*inst1;
		m_data->GetAttr(ext0[i],a_pdr_r_ting,inst0);
		if(inst0!=0)
		{
			if(inst0==pdf)
			{
				m_data->GetAttr(ext0[i],a_pdr_r_ted,inst1);
				if(inst1!=0)
				{
					bool bAdd=true;
					if(context!=0)
					{
						if(!IsItemInContext(ext0[i],context,a_pdr_frames_of_reference)) bAdd=false;
					}
					if(bAdd)
					{
						ext_rel.Add(ext0[i]);
						ext_pdf.Add(inst1);
					}
				}
			}
		}
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}
	return true;
}

bool CaplProductManager::FindPdfsByIds(const std::set<CString> &ids, aplExtent &result, bool loadAttrs) const
{
	int count = 0;
	result.Clear();

	CaplFinder ff(DEF_SOURCE);
	int prdIndex = ff.CreateExt(m_api->m_prd_mgr.e_prd, 0, 0, CaplFinder::grpOR);

	for(std::set<CString>::const_iterator it=ids.begin(); it!=ids.end(); ++it, ++count)	
	{
		std::set<CString>::const_iterator nextIt = it;
		nextIt++;

		// еще сделаем поиск по версии, если придет обозначение вида "483-7514-01-01"
		int index = (*it).ReverseFind('-');
		if(-1 != index)
		{
			CString idWithoutVersion = (*it).Left(index);
			ff.AddAttr(prdIndex, m_api->m_prd_mgr.a_prd_id, idWithoutVersion, CaplFinder::cmpEqual);
		}

		ff.AddAttr(prdIndex, m_api->m_prd_mgr.a_prd_id, *it, CaplFinder::cmpEqual);
		if(count == 300 || nextIt == ids.end())
		{
			int pdfIndex = ff.CreateExt(m_api->m_prd_mgr.e_pdf);
			ff.AddAttr(pdfIndex, m_api->m_prd_mgr.a_pdf_prd, prdIndex);

			ff.AddToResult(pdfIndex);
			ff.Find(m_api->m_data, true, false, false, false, true);

			if(loadAttrs)
				m_api->m_prd_mgr.LoadPrdInfo(ff.m_innerExtent);			

			result.Append(ff.m_innerExtent);

			ff.Clear();
			prdIndex = ff.CreateExt(m_api->m_prd_mgr.e_prd, 0, 0, CaplFinder::grpOR);
			count = 0;
		}
	}

	return true;
}

CString CaplProductManager::GetProductId(CaplInstance *pdfOrProduct, CString *name)
{
	if(0 == m_api) return _T("");
	if(0 == pdfOrProduct) return _T("");
	if(false == m_api->m_data.IsConnected()) return _T("");
	
	CString ver;
	CaplInstance *prd = 0;

	if(m_api->m_data.IsKindOf(pdfOrProduct, m_api->m_prd_mgr.e_pdf))
	{
		m_api->m_data.GetAttr(pdfOrProduct, m_api->m_prd_mgr.a_pdf_id, ver);
		m_api->m_data.GetAttr(pdfOrProduct, m_api->m_prd_mgr.a_pdf_prd, prd);		
	}
	else if(m_api->m_data.IsKindOf(pdfOrProduct, m_api->m_prd_mgr.e_prd))
	{
		prd = pdfOrProduct;
	}
	else
	{
		return _T("");
	}

	if(0 == prd)
		return _T("");
	
	CString prdId;
	m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_id, prdId);

	if(0 != name)
		m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_name, *name);

	return prdId + (ver.IsEmpty() ? _T("") : _T("-") + ver);
}

bool CaplProductManager::LoadAllSubProduct(aplExtent &parents, aplExtent &ext_rel, aplExtent &ext_pdf, bool from_base)
{
	ext_rel.Clear();
	ext_pdf.Clear();

	if(m_api==NULL) return false;
	if(!m_api->m_data.IsDictLoad()) return false;

	CaplInstance *inst;
	aplExtent rels;
	int i;
	int iCurIndex= 0;
	CString buf;
	
	CaplSetResourceHandle setres(module_inst);
	
	CSortClass::SortExtentById(parents);

	if(from_base && m_api->m_data.IsConnected())
	{
			// чтение из базы
		CaplLoadData ld(m_data,DEF_SOURCE);
		int i1,i8,i12,i14,i27,i28;
		
		CDisAsmStatusDlg* dlg=0;
		if(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"), (int)((parents.Size-1)/m_MaxItemsLoad)+1);
			dlg->m_count.SetWindowText(buf);	
			dlg->ShowWindow(SW_SHOW);
			dlg->BringWindowToTop();
		}		
		
		for(i=0; i<parents.Size; i++)
		{
			if(parents[i]!=NULL)
				if(parents[i]->GetId()!=0)
					if(parents[i]->GetAccessmode()<=aplRO)
						ld.AddQuery(0, parents[i]);
			
			iCurIndex++;
			
			if(iCurIndex==m_MaxItemsLoad || i+1==parents.Size)
			{
				if(ld.IsQueryNotEmpty())
				{
					i1=	ld.AddQuery(_T('r'), 0, e_pdr, a_pdr_r_ting, true,true);
					i8=	ld.AddQuery(_T('d'), i1, 0, a_pdr_r_ted, true,true);
					i12=ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);
					// чтение effectivity
					i14=ld.AddQuery(_T('r'), i1, e_pd_eff, a_pde_usage, true,true);
					// правила
					i27=ld.AddQuery(_T('r'), i1, e_rule_rels, a_rule_rels_item, true,true);
						i28=ld.AddQuery(_T('d'), i27, 0, a_rule_rels_rule, true,true);
					if (!ld.LoadEx())
					{
						if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS)
						{
							if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
						}
					}
				}

				if(dlg)
				{
					buf.Format( APL_T("%i из %i"), (int)(i+1)/m_MaxItemsLoad, (int)((parents.Size-1)/m_MaxItemsLoad)+1);
					dlg->m_count.SetWindowText(buf);	
					dlg->BringWindowToTop();
				}

				ld.ClearQuery();
				iCurIndex= 0;
			}
		}

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

	m_api->m_data.GetEntityExtent(e_pdr, rels);
	for(i=0; i<rels.Size; i++)
	{
		if(rels[i]->GetAccessmode()>aplRO) continue;
		m_api->m_data.GetAttr(rels[i], a_pdr_r_ting, inst);
		if(!inst) continue;
		if(aplQFindInstIdInExtent(parents,inst->GetId())!=-1)
		{
			m_api->m_data.GetAttr(rels[i], a_pdr_r_ted, inst);
			if(!inst) continue;

			ext_rel.Add(rels[i]);
			ext_pdf.Add(inst);
		}
	}
	return true;
}
//*************************************************************
bool CaplProductManager::LoadAllSubProduct(CaplInstance *ci, CaplInstance *context,
		CaplInstance *prd, aplExtent &out_ext, aplExtent &ext_rel, aplExtent &ext_pdf, bool from_base)
{
	ext_rel.Clear();
	ext_pdf.Clear();
	out_ext.Clear();
	if(m_data==0) return false;
	if(prd==0) return false;
	if(prd==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	};
	if(prd->GetType()==0) return false;
	if(e_apl_qacu==0) return false;
	if(e_prd==0) return false;
	if(!m_data->IsKindOf(prd,e_prd))return false;

	int i;
	aplExtent ext0;
	if(from_base)
	{
		if((m_data->IsConnected())&&(prd->GetId()!=0))
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
			int ipdf,i1,i8,i12,i14,i27,i28;
			ipdf = ld.AddQuery(_T('b'),prd->GetId(),e_apl_pdf,a_pdf_prd,true,true);
			i1=	ld.AddQuery(_T('r'), ipdf, e_apl_qacu, a_pdr_r_ting, true,true);
			i8=	ld.AddQuery(_T('d'), i1, 0, a_pdr_r_ted, true,true);
			i12=ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);
			// чтение effectivity
			i14=ld.AddQuery(_T('r'), i1, e_pd_eff, a_pde_usage, true,true);
			// правила
			i27=ld.AddQuery(_T('r'), i1, e_rule_rels, a_rule_rels_item, true,true);
			i28=ld.AddQuery(_T('d'), i27, 0, a_rule_rels_rule, true,true);
				if (!ld.LoadEx()){
					if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
						if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
					}
				}
		}
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}

	m_data->GetEntityExtent(e_apl_pdf,ext0);
	
	for (i=0;i<ext0.Size;i++)
	{
		if(m_bContinue)
		{
			if(*m_bContinue==false) break;
		}
		CaplInstance *inst0;
		m_data->GetAttr(ext0[i],a_pdf_prd,inst0);
		if ((inst0!=0)&&(inst0==prd))
			out_ext.Add(ext0[i]);
	}
	if (out_ext.Size)
	{
		ext0.Clear();
		m_data->GetEntityExtent(e_apl_qacu,ext0);

		
		for(i=0;i<ext0.Size;i++)
		{
			if(m_bContinue)
			{
				if(*m_bContinue==false) break;
			}
			CaplInstance *inst0,*inst1;
			m_data->GetAttr(ext0[i],a_pdr_r_ting,inst0);
			
			if(inst0!=0)
			{
				if(out_ext.Find(inst0)>=0)
				{
					m_data->GetAttr(ext0[i],a_pdr_r_ted,inst1);
					if(inst1!=0)
					{
						ext_rel.Add(ext0[i]);
						ext_pdf.Add(inst1);
					}
				}
			}
		}
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}
	return true;
}

//*************************************************************
bool CaplProductManager::LoadAllSubProductEx(CaplInstance *ci, CaplInstance *context,
		CaplInstance *pdf, aplExtent &ext_rel, aplExtent &ext_pdf, bool from_base, UINT flag)
{
	ext_rel.Clear();
	ext_pdf.Clear();
	if(m_data==0) return false;
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	};
	if(pdf->GetType()==0) return false;
	if(e_apl_qacu==0) return false;
	if(e_prd==0) return false;
	if(!m_data->IsKindOf(pdf,e_pdf))return false;
	if(flag==0) return false;

	int i;
	aplExtent ext0;
	if(from_base)
	{
		if((m_data->IsConnected())&&(pdf->GetId()!=0))
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
			int i1,i8,i12,i14;
			i1=	ld.AddQuery(_T('b'), pdf->GetId(), e_apl_qacu, a_pdr_r_ting, true,true);
				/*
				ld.AddQuery(_T('d'), i1, 0, a_pdr_r_ting, true);
				ld.AddQuery(_T('d'), i1, 0, a_pdr_id, true);
				ld.AddQuery(_T('d'), i1, 0, a_pdr_name, true);
				ld.AddQuery(_T('d'), i1, 0, a_pdr_descr, true);
				ld.AddQuery(_T('d'), i1, 0, a_pdr_frames_of_reference, true);
				ld.AddQuery(_T('d'), i1, 0, a_pdr_inner_id, true);
				ld.AddQuery(_T('d'), i1, 0, a_apl_qacu_value, true);
				ld.AddQuery(_T('d'), i1, 0, a_apl_qacu_unit, true);
				*/
			i8=	ld.AddQuery(_T('d'), i1, 0, a_pdr_r_ted, true,true);
				/*
				ld.AddQuery(_T('d'), i8, 0, a_pdf_id, true);
				ld.AddQuery(_T('d'), i8, 0, a_pdf_descr, true);
				ld.AddQuery(_T('d'), i8, 0, a_pdfwss_source, true);
				ld.AddQuery(_T('d'), i8, 0, a_apl_pdf_type, true);
				ld.AddQuery(_T('d'), i8, 0, a_apl_pdf_standard, true);
			    ld.AddQuery(_T('d'), i8, 0, a_apl_pdf_state, true);
				ld.AddQuery(_T('d'), i8, 0, a_apl_pdf_unit, true);
				ld.AddQuery(_T('d'), i8, 0, a_pdf_code, true);
				ld.AddQuery(_T('d'), i8, 0, a_pdf_code1, true);
				ld.AddQuery(_T('d'), i8, 0, a_pdf_code2, true);
				*/
			//DIV - запрос i12 имеет смысл только при втором параметре true, 
			// так как иначе в запросе i8 для всех pdf уже зачитаны все атрибуты
			i12=ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true); 
				/*
				ld.AddQuery(_T('d'), i12, 0, a_prd_id, true);
				ld.AddQuery(_T('d'), i12, 0, a_prd_name, true);
				ld.AddQuery(_T('d'), i12, 0, a_prd_descr, true);
				ld.AddQuery(_T('d'), i12, 0, a_prd_code, true);
				*/
			// чтение effectivity
			i14=ld.AddQuery(_T('r'), i1, e_pd_eff, a_pde_usage, true,true);
				/*
				ld.AddQuery(_T('d'), i14, 0, a_pde_usage, true);
				ld.AddQuery(_T('d'), i14, 0, a_pde_id, true);
				ld.AddQuery(_T('d'), i14, 0, a_pde_prev, true);
				ld.AddQuery(_T('d'), i14, 0, a_pde_not_active, true);
				ld.AddQuery(_T('d'), i14, 0, a_sn_eff_start, true);
				ld.AddQuery(_T('d'), i14, 0, a_sn_eff_end, true);
			    ld.AddQuery(_T('d'), i14, 0, a_dat_eff_start_s, true);
			    ld.AddQuery(_T('d'), i14, 0, a_dat_eff_end_s, true);
				*/
			
			if(!ld.LoadEx()){
				if(apidata.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
					if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
				}
			}
		}
	}
	aplExtent dmfr, amfuo;
	if(flag&APL_LOAD_ASSEMBLY_COMPONENT_USAGE) m_data->GetEntityExtent(e_apl_qacu,ext0);
	if(flag&APL_LOAD_DESING_MAKE_FROM_RELATIONSHIP) m_data->GetEntityExtent(e_design_make_from,dmfr);
	if(flag&APL_LOAD_MAKE_FROM_USAGE_OPTION) m_data->GetEntityExtent(e_make_from,amfuo);
	ext0.Append(dmfr);
	ext0.Append(amfuo);
	for(i=0;i<ext0.Size;i++)
	{
		CaplInstance *inst0,*inst1;
		m_data->GetAttr(ext0[i],a_pdr_r_ting,inst0);
		if(inst0!=0)
		{
			if(inst0==pdf)
			{
				m_data->GetAttr(ext0[i],a_pdr_r_ted,inst1);
				if(inst1!=0)
				{
					bool bAdd=true;
					if(context!=0)
					{
						if(!IsItemInContext(ext0[i],context,a_pdr_frames_of_reference)) bAdd=false;
					}
					if(bAdd)
					{
						ext_rel.Add(ext0[i]);
						ext_pdf.Add(inst1);
					}
				}
			}
		}
	}
	return true;
}
//*************************************************************

bool CaplProductManager::LoadAllZagotov(CaplInstance *pdf, aplExtent &ext_rel, aplExtent &ext_pdf,
		bool include_design , bool from_base)
{
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(pdf->GetAccessmode()>aplRO) return false;
	if(!m_data->IsKindOf(pdf,e_pdf))return false;
	
	aplExtent ext0;
	ext0.Add(pdf);
	return LoadAllZagotov(ext0,ext_rel,ext_pdf,include_design,from_base);	
	/*
	ext_rel.Clear();
	ext_pdf.Clear();
	if(m_data==0) return false;
	if(pdf==0) return false;
	if(pdf->GetType()==0) return false;
	if(e_make_from==0) return false;
	if(e_prd==0) return false;
	if(!m_data->IsKindOf(pdf,e_pdf))return false;

	aplExtent ext0;
	int i;

	if(from_base)
	{
		if((m_data->IsConnected())&&(pdf->GetId()!=0))
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
			int i1,i8,i12;
			i1=	ld.AddQuery(_T('b'), pdf->GetId(), e_make_from, a_pdr_r_ting, true,true);
				if(include_design)
					ld.AddQuery(i1,_T('b'), pdf->GetId(), e_design_make_from, a_pdr_r_ting, true,true);
			i8=	ld.AddQuery(_T('d'), i1, 0, a_pdr_r_ted, true,true);
			i12=ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);

		int i14=ld.AddQuery(_T('r'), i1, e_pd_eff, a_pde_usage, true,true);
			if (!ld.LoadEx())
			{
				if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
					if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
				}
			}
		}
	}
	m_data->GetEntityExtent(e_make_from,ext0);
	if(include_design)
	{
		aplExtent ext1;
		m_data->GetEntityExtent(e_design_make_from,ext1);
		ext0.Append(ext1);
	}
	for(i=0;i<ext0.Size;i++)
	{
		CaplInstance *inst0;
		m_data->GetAttr(ext0[i],a_pdr_r_ting,inst0);
		if(inst0!=0)
		{
			if(inst0==pdf)
			{
				m_data->GetAttr(ext0[i],a_pdr_r_ted,inst0);
				if(inst0!=0)
				{
					ext_rel.Add(ext0[i]);
					ext_pdf.Add(inst0);
				}
			}
		}
	}
	return true;
	*/
}

bool CaplProductManager::LoadAllZagotov(aplExtent &ext_pdf, aplExtent &ext_rel, aplExtent &out_ext,
		bool include_design , bool from_base,bool show_status_dlg)
{
	ext_rel.Clear();
	out_ext.Clear();
	if(m_data==0) return false;
	if(ext_pdf.GetSize()==0) return false;
	if(e_make_from==0) return false;
	if(e_prd==0) return false;

	aplExtent ext0;
	int i;

	if(from_base)
	{
		CaplSetResourceHandle setres(module_inst);

		CDisAsmStatusDlg dlg;
		dlg.Create(IDD_DISASM_STATUS);
		dlg.m_name.SetWindowText( APL_T("Обработано:"));
		if(show_status_dlg) dlg.ShowWindow(TRUE);
		
		CString buf;
		if(m_data->IsConnected())
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
			int i1,i8,i12,i14;
			bool b_load=false;
			int l_count=0;
			int all_l_count=0;
			for(i=0;i<ext_pdf.GetSize();i++)
			{
				if(m_bContinue)
				{
					if(*m_bContinue==false) break;
				}
				if(ext_pdf[i]!=0) 
					if(ext_pdf[i]->GetId()!=0) 
						if(ext_pdf[i]->GetAccessmode()<aplNO) 
						{
							l_count++;
							ld.AddQuery(0,ext_pdf[i]);
							b_load=true;
						}
				
				if((l_count==m_MaxItemsLoad || i==ext_pdf.GetSize()-1) && b_load)
				{
					i1=	ld.AddQuery(_T('r'), 0, e_make_from, a_pdr_r_ting, true,true);
						if(include_design)
							ld.AddQuery(i1,_T('r'), 0, e_design_make_from, a_pdr_r_ting, true,true);
					i8=	ld.AddQuery(_T('d'), i1, 0, a_pdr_r_ted, true,true);
					i12=ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);

					i14=ld.AddQuery(_T('r'), i1, e_pd_eff, a_pde_usage, true,true);
					if (!ld.LoadEx())
					{
						if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
							if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
						}
					}
					all_l_count+=l_count;
					if(show_status_dlg)
					{
						buf.Format(_T("%d"),int(((double)all_l_count/(double)ext_pdf.Size)*100));
						buf+=_T("%");
						dlg.m_count.SetWindowText(buf);	
					}
					l_count=0;
					b_load=false;
				}
			}
		}
		dlg.ShowWindow(FALSE);
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}
	m_data->GetEntityExtent(e_make_from,ext0);
	if(include_design)
	{
		aplExtent ext1;
		m_data->GetEntityExtent(e_design_make_from,ext1);
		ext0.Append(ext1);
	}
	for(i=0;i<ext0.Size;i++)
	{
		if(m_bContinue)
		{
			if(*m_bContinue==false) break;
		}
		CaplInstance *inst0;
		m_data->GetAttr(ext0[i],a_pdr_r_ting,inst0);
		if(inst0!=0)
		{
			for(int j=0;j<ext_pdf.GetSize();j++)
			{
				if(inst0==ext_pdf[j])
				{
					m_data->GetAttr(ext0[i],a_pdr_r_ted,inst0);
					if(inst0!=0)
					{
						ext_rel.Add(ext0[i]);
						out_ext.Add(inst0);
					}
					break;
				}
			}
		}
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}
	return true;
}


bool CaplProductManager::LoadAllOGmet(CaplInstance *pdf, aplExtent &ext_rel, aplExtent &ext_pdf,
									  bool from_base)
{
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(pdf->GetAccessmode()>aplRO) return false;
	if(!m_data->IsKindOf(pdf,e_pdf))return false;
	
	aplExtent ext0;
	ext0.Add(pdf);
	return LoadAllOGmet(ext0,ext_rel,ext_pdf,from_base);	
}
bool CaplProductManager::LoadAllOGmet(aplExtent &ext_pdf, aplExtent &ext_rel, aplExtent &out_ext,
									  bool from_base,bool show_status_dlg)
{
	ext_rel.Clear();
	out_ext.Clear();
	if(m_data==0) return false;
	if(ext_pdf.GetSize()==0) return false;
	if(e_comp_mf==0) return false;
	if(e_prd==0) return false;

	aplExtent ext0;
	int i;
	if(from_base)
	{
		CaplSetResourceHandle setres(module_inst);

		CDisAsmStatusDlg dlg;
		dlg.Create(IDD_DISASM_STATUS);
		dlg.m_name.SetWindowText( APL_T("Обработано:"));
		if(show_status_dlg) dlg.ShowWindow(TRUE);
		
		CString buf;
		if(m_data->IsConnected())
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
			int i1,i8,i12;
			bool b_load=false;
			int l_count=0;
			int all_l_count=0;
			for(i=0;i<ext_pdf.GetSize();i++)
			{
				if(m_bContinue)
				{
					if(*m_bContinue==false) break;
				}
				if(ext_pdf[i]!=0) 
					if(ext_pdf[i]->GetId()!=0) 
						if(ext_pdf[i]->GetAccessmode()<aplNO) 
						{
							l_count++;
							ld.AddQuery(0,ext_pdf[i]);
							b_load=true;
						}
				
				if((l_count==m_MaxItemsLoad || i==ext_pdf.GetSize()-1) && b_load)
				{

					i1 = ld.AddQuery(_T('r'), 0, e_comp_mf, a_comp_mf_ting, true, true);
					i8=	ld.AddQuery(_T('d'), i1, 0, a_comp_mf_ted, true,true);
					i12=ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);
					if (!ld.LoadEx())
					{
						if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
							if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
						}
					}
					all_l_count+=l_count;
					if(show_status_dlg)
					{
						buf.Format(_T("%d"),int(((double)all_l_count/(double)ext_pdf.Size)*100));
						buf+=_T("%");
						dlg.m_count.SetWindowText(buf);	
					}
					l_count=0;
					b_load=false;
				}
			}
		}
		dlg.ShowWindow(FALSE);
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}
	m_data->GetEntityExtent(e_comp_mf,ext0);
	for(i=0;i<ext0.Size;i++)
	{
		if(m_bContinue)
		{
			if(*m_bContinue==false) break;
		}
		CaplInstance *inst0;
		m_data->GetAttr(ext0[i],a_comp_mf_ting,inst0);
		if(inst0!=0)
		{
			for(int j=0;j<ext_pdf.GetSize();j++)
			{
				if(inst0==ext_pdf[j])
				{
					m_data->GetAttr(ext0[i],a_comp_mf_ted,inst0);
					if(inst0!=0)
					{
						ext_rel.Add(ext0[i]);
						out_ext.Add(inst0);
					}
					break;
				}
			}
		}
	}
	if(m_bContinue)
	{
		if(*m_bContinue==false) return false;
	}
	return true;
}
//*************************************************************
bool CaplProductManager::LoadProductAlternates(CaplInstance *prd, aplExtent &ext_rel, aplExtent &ext_prd)
{
	ext_rel.Clear();
	ext_prd.Clear();
	if(m_data==0) return false;
	if(prd==0) return false;
	if(prd==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	};
	if(prd->GetType()==0) return false;
	if(e_prd==0) return false;
	
	if((m_data->IsConnected())&&(prd->GetId()!=0))
	{
		// чтение из базы
		CaplLoadData ld(m_data,DEF_SOURCE);
		int i1,i2;
		i1=	ld.AddQuery(_T('b'), prd->GetId(), e_alt, a_alt_base, true,true);
		i2=	ld.AddQuery(_T('d'), i1, 0, a_alt_alt, true,true);
		
		if(!ld.LoadEx()){
			if(apidata.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
				if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
			}
		}
	}

	aplExtent ext0;
	CaplInstance *inst0;
	m_data->GetEntityExtent(e_alt,ext0);
	for(int i=0;i<ext0.GetSize();i++)
	{
		m_data->GetAttr(ext0[i],a_alt_base,inst0);
		if(inst0!=prd) continue;
		m_data->GetAttr(ext0[i],a_alt_alt,inst0);
		ext_rel.Add(ext0[i]);
		ext_prd.Add(inst0);
	}
	return true;
}

bool CaplProductManager::LoadPdfAlternates(CaplInstance *pdf, aplExtent &ext_rel, aplExtent &ext_pdf)
{
	ext_rel.Clear();
	ext_pdf.Clear();
	if(m_data==0) return false;
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	};
	if(pdf->GetType()==0) return false;
	if(e_pdf==0) return false;

	aplExtent ext0;
	if((m_data->IsConnected())&&(pdf->GetId()!=0))
	{
		// чтение из базы
		CaplLoadData ld(m_data,DEF_SOURCE);
		int i1,i2,i3;
		i1=	ld.AddQuery(_T('b'), pdf->GetId(), e_alt_pdf, a_alt_pdf_base, true,true);
		i2=	ld.AddQuery(_T('d'), i1, 0, a_alt_pdf_alt, true,true);
		i3=	ld.AddQuery(_T('d'), i2, 0, a_pdf_prd, true,true);

		if(!ld.LoadEx(true,&ext0)){
			if(apidata.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
				if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
			}
		}
	}
	else
	{
		m_data->GetEntityExtent(e_alt_pdf,ext0);

	}

	CaplInstance *inst0;
	for(int i=0;i<ext0.GetSize();i++)
	{
		CaplInstance *rel=ext0[i];
		if(!m_data->IsKindOf(rel,e_alt_pdf)) continue;
		m_data->GetAttr(rel,a_alt_pdf_base,inst0);
		if(inst0!=pdf) continue;
		ext_rel.Add(rel);
		m_data->GetAttr(rel,a_alt_pdf_alt,inst0);
		ext_pdf.Add(inst0);
	}
	return true;
}



bool CaplProductManager::LoadPdfAlternateReady(CaplInstance *pdf, aplExtent &ext_rel, aplExtent &ext_pdf)
{
	ext_rel.Clear();
	ext_pdf.Clear();
	if(m_data==0) return false;
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	};
	if(pdf->GetType()==0) return false;
	if(e_pdf==0) return false;

	aplExtent ext0;
	if((m_data->IsConnected())&&(pdf->GetId()!=0))
	{
		// чтение из базы
		CaplLoadData ld(m_data,DEF_SOURCE);
		int i1,i2,i3;
		i1=	ld.AddQuery(_T('b'), pdf->GetId(), e_alt_pdf, a_alt_pdf_alt, true,true);
		i2=	ld.AddQuery(_T('d'), i1, 0, a_alt_pdf_alt, true,true);
		i3=	ld.AddQuery(_T('d'), i2, 0, a_pdf_prd, true,true);

		if(!ld.LoadEx(true,&ext0)){
			if(apidata.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
				if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
			}
		}
	}
	else
	{
		m_data->GetEntityExtent(e_alt_pdf,ext0);

	}

	CaplInstance *inst0;
	for(int i=0;i<ext0.GetSize();i++)
	{
		CaplInstance *rel=ext0[i];
		if(!m_data->IsKindOf(rel,e_alt_pdf)) continue;
		m_data->GetAttr(rel,a_alt_pdf_alt,inst0);
		if(inst0!=pdf) continue;
		ext_rel.Add(rel);
		m_data->GetAttr(rel,a_alt_pdf_base,inst0);
		ext_pdf.Add(inst0);
	}
	return true;
}





bool CaplProductManager::LoadProductBidirectAlternates(CaplInstance *prd, aplExtent &ext_relBase, aplExtent &ext_prdBase, aplExtent &ext_relAlt, aplExtent &ext_prdAlt)
{
	ext_prdBase.Clear();
	ext_relBase.Clear();
	ext_relAlt.Clear();
	ext_prdAlt.Clear();
	if(m_data==0) return false;
	if(prd==0) return false;
	if(prd==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	};
	if(prd->GetType()==0) return false;
	if(e_prd==0) return false;

	if((m_data->IsConnected())&&(prd->GetId()!=0))
	{
		// чтение из базы
		CaplLoadData ld(m_data,DEF_SOURCE);
		int i1,i7;
		i1=	ld.AddQuery(_T('b'), prd->GetId(), e_alt_bidir, a_alt_base_pdf, true,true);
		i7=	ld.AddQuery(_T('d'), i1, 0, a_alt_alt_pdf, true,true);
		int j1,j7; 
		j1=	ld.AddQuery(_T('b'), prd->GetId(), e_alt_bidir, a_alt_alt_pdf, true,true);
		j7=	ld.AddQuery(_T('d'), j1, 0, a_alt_base_pdf, true,true);
		if(!ld.LoadEx())
		{
			if(apidata.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS)
			{
				if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
			}
		}
	}

	aplExtent ext0;
	CaplInstance *inst0;
	m_data->GetEntityExtent(e_alt_bidir,ext0);
	for(int i=0;i<ext0.GetSize();i++)
	{
		m_data->GetAttr(ext0[i],a_alt_base_pdf,inst0);
		if(inst0==prd)
		{
			m_data->GetAttr(ext0[i],a_alt_alt_pdf,inst0);
			ext_relAlt.Add(ext0[i]);
			ext_prdAlt.Add(inst0);
		}

		m_data->GetAttr(ext0[i],a_alt_alt_pdf,inst0);
		if (inst0==prd)
		{
			m_data->GetAttr(ext0[i],a_alt_base_pdf,inst0);
			ext_relBase.Add(ext0[i]);
			ext_prdBase.Add(inst0);
		}
	}

	return true;
}
//*************************************************************
bool CaplProductManager::LoadSupliedProduct(CaplInstance *pdf, aplExtent &ext_rel, aplExtent &ext_pdf, bool from_base)
{
	ext_rel.Clear();
	ext_pdf.Clear();
	if(m_data==0) return false;
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(pdf->GetType()==0) return false;
	if(e_apl_qacu==0) return false;
	if(e_prd==0) return false;

	aplExtent ext0;
	int i;

	if(from_base)
	{
		if((m_data->IsConnected())&&(pdf->GetId()!=0))
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
			int i1,i8;
			i1=	ld.AddQuery(_T('b'), pdf->GetId(), e_spr, a_pdr_r_ted, true,true);
			i8=	ld.AddQuery(_T('d'), i1, 0, a_pdr_r_ting, true,true);
				ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);
			i1=	ld.AddQuery(_T('b'), pdf->GetId(), e_spr, a_pdr_r_ting, true,true);
			i8=	ld.AddQuery(_T('d'), i1, 0, a_pdr_r_ted, true,true);
				ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);
			if (!ld.LoadEx())
			{
				if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
					if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
				}
			}
		}
	}
	CaplInstance *inst0,*inst1;
	m_data->GetEntityExtent(e_spr,ext0);
	for(i=0;i<ext0.Size;i++)
	{
		m_data->GetAttr(ext0[i],a_pdr_r_ted,inst0);
		m_data->GetAttr(ext0[i],a_pdr_r_ting,inst1);
		if(inst0!=0)
		{
			if(inst0==pdf)
			{
				m_data->GetAttr(ext0[i],a_pdr_r_ting,inst0);
				if(inst0!=0)
				{
					ext_rel.Add(ext0[i]);
					ext_pdf.Add(inst0);
				}
			}
		}
		if(inst1!=0)
		{
			if(inst1==pdf)
			{
				m_data->GetAttr(ext0[i],a_pdr_r_ted,inst0);
				if(inst0!=0)
				{
					ext_rel.Add(ext0[i]);
					ext_pdf.Add(inst0);
				}
			}
		}	
	}
	return true;
}

bool CaplProductManager::LoadAllSubstitutes(CaplInstance *pdr, aplExtent &ext_rel, aplExtent &ext_pdf,bool from_base)
{
	ext_rel.Clear();
	ext_pdf.Clear();
	if(m_data==0) return false;
	if(pdr==0) return false;
	if(pdr==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(pdr->GetType()==0) return false;

	aplExtent ext0;
	int i;

	if(from_base)
	{
		if((m_data->IsConnected())&&(pdr->GetId()!=0))
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
			int i1,i8,i12;
			i1=	ld.AddQuery(_T('b'), pdr->GetId(), e_pdf_subst, a_pdf_subst_pdr, true,true);
			i8=	ld.AddQuery(_T('d'), i1, 0, a_pdf_subst_pdr, true,true);
			i12=ld.AddQuery(_T('d'), i8, 0, a_pdr_r_ted, true,true);//что можно заменить
				ld.AddQuery(_T('d'), i12,0, a_pdf_prd, true,true);
			i8=	ld.AddQuery(_T('d'), i1, 0, a_pdf_subst_pdf, true,true);//на что можно заменить
				ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);

			if (!ld.LoadEx())
			{
				if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
					if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
				}
			}
		}
	}
	CaplInstance *inst0,*inst1;
	m_data->GetEntityExtent(e_pdf_subst,ext0);
	for(i=0;i<ext0.Size;i++)
	{
		m_data->GetAttr(ext0[i],a_pdf_subst_pdr,inst0);
		if(inst0==pdr)
		{
			m_data->GetAttr(ext0[i],a_pdf_subst_pdf,inst1);
			if(inst1==0) continue;
			if(inst1->GetAccessmode()>aplRO) continue;
			ext_rel.Add(ext0[i]);
			ext_pdf.Add(inst1);
		}	
	}
	return true;
}

bool CaplProductManager::FindPdfSubstitutes(CaplInstance *pdr, CaplInstance *parent_item, aplExtent &ext_pdfs, aplExtent *ext_subst, bool bFromBase)
{
	if(!m_api->m_data.IsDictLoad()) return false;
	if(pdr==NULL) return false;
	if(pdr->GetType()==NULL) return false;
	if(parent_item==NULL) return false;

	aplExtent pdrs;
	pdrs.Add(pdr);
	return FindPdfSubstitutes(pdrs, parent_item, ext_pdfs, ext_subst, bFromBase);
}

bool CaplProductManager::FindPdfSubstitutes(aplExtent &pdrs, CaplInstance *parent_item, aplExtent &ext_pdfs, aplExtent *ext_subst, bool bFromBase)
{
	if(!m_api->m_data.IsDictLoad()) return false;
	if(!pdrs.Size) return false;
	if(parent_item==NULL) return false;

	if(bFromBase)
	{
		if(m_api->m_data.IsConnected())
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
			int i1,i8,i12;
			bool bLoad = false;
			for(int i=0; i<pdrs.Size; ++i)
			{
				if(!pdrs[i]) 
					continue;
				if(!pdrs[i]->GetId()) 
					continue;

				ld.AddQuery(0, pdrs[i]);
				bLoad = true;
			}
			i1=	ld.AddQuery(_T('r'), 0, e_pdf_subst, a_pdf_subst_pdr, true,true);
			i8=	ld.AddQuery(_T('d'), i1, 0, a_pdf_subst_pdr, true,true);
			i12=ld.AddQuery(_T('d'), i8, 0, a_pdr_r_ted, true,true);//что можно заменить
			ld.AddQuery(_T('d'), i12,0, a_pdf_prd, true,true);
			i8=	ld.AddQuery(_T('d'), i1, 0, a_pdf_subst_pdf, true,true);//на что можно заменить
			ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);

			if (bLoad)
			{
				if (!ld.LoadEx())
				{
					if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
						if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
					}
				}
			}
		}
	}
	int i;
	aplExtent ext;
	CaplInstance *inst;
	m_data->GetEntityExtent(e_pdf_subst,ext);

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

		m_api->m_data.GetAttr(ext[i], a_pdf_subst_pdr, inst);
		if(pdrs.Find(inst)<0) continue;
		m_api->m_data.GetAttr(ext[i], a_pdf_subst_parent_item, inst);
		if(parent_item!=inst) continue;
		m_api->m_data.GetAttr(ext[i], a_pdf_subst_pdf, inst);
		ext_pdfs.Add(inst);
		if(ext_subst)
			ext_subst->Add(ext[i]);
	}

	return true;
}

void CaplProductManager::ReNumberOperations(aplExtent &tpo, bool bSaveChanes)
{
	// сгруппируем по сквозному номеру
	CString tpoId;
	std::map<CString, CaplInstance*> tpoByNumber;

	for(int i=0; i<tpo.Size; ++i)
	{
		m_api->m_data.GetAttr(tpo[i], a_tpo_id, tpoId);
		if(tpoId.IsEmpty() == false)
			tpoByNumber[tpoId] = tpo[i];
	}

	// поменяем внутреение номера
	int nStep = 5;
	CString lastShop;
	std::map<CString, int> idByShop;

	for(std::map<CString, CaplInstance*>::iterator tpoIt=tpoByNumber.begin(); tpoIt!=tpoByNumber.end(); ++tpoIt)
	{
		CaplInstance *operation = 0;
		CaplInstance *tpo = tpoIt->second;
		
		m_api->m_data.GetAttr(tpo, m_api->m_prd_mgr.a_tpo_operation, operation);
		if(0 != operation)
		{
			int tpoId = 0;
			CString shop, buf, sRouteID;
			CaplInstance* ciLevel;
			m_api->m_data.GetAttr(operation, a_tech_operation_shop, shop);
			m_api->m_data.GetAttr(operation, a_tech_operation_operation_level, ciLevel);
			m_api->m_data.GetAttr(ciLevel, m_api->m_classifier_mgr.a_apl_classifier_level_id, sRouteID);

			// цеха покрытия продолжаю нумерацию предыдущего цеха
			if(shop == _T("45") || shop == _T("5") || (shop==_T("42") && sRouteID==_T("0378")))
				shop = lastShop;

			m_api->m_data.GetAttr(tpo, a_tpo_internal_number, buf);
			std::map<CString, int>::iterator shopIt = idByShop.find(shop);

			if(buf.IsEmpty() == false)
			{
				tpoId = _atoi(buf);
			}
			else
			{
				if(shopIt == idByShop.end())
				{
					if(buf.IsEmpty())
						tpoId = nStep;															
				}
				else
				{				
					if(buf.IsEmpty())
						tpoId = shopIt->second + nStep;										
				}
			}			

			buf.Format(_T("%.3d"), tpoId);
			idByShop[shop] = tpoId;
			lastShop = shop;

			m_api->m_data.PutAttr(tpo, m_api->m_prd_mgr.a_tpo_internal_number, buf);
		}
	}

	if(true == bSaveChanes)
		m_api->SaveChanges();
}

bool CaplProductManager::WhereUsedAsSubstitute(CaplInstance *subst_pdf, aplExtent &ext_rel, aplExtent &ext_pdr,bool from_base)
{
	ext_rel.Clear();
	ext_pdr.Clear();
	if(m_data==0) return false;
	if(subst_pdf==0) return false;
	if(subst_pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(subst_pdf->GetType()==0) return false;

	aplExtent ext0;
	int i;

	if(from_base)
	{
		if((m_data->IsConnected())&&(subst_pdf->GetId()!=0))
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
		/*	//dmibor так и не понял, почему этот вариант не работает :(
			int i1,i21,i22,i3;
			i1=	ld.AddQuery(_T('b'), subst_pdf->GetId(), e_pdf_subst, a_pdf_subst_pdf, true,true);
			i21=ld.AddQuery(_T('d'), i1, 0, a_pdf_subst_pdf, true,true);//на что можно заменить
			i22=ld.AddQuery(_T('d'), i1, 0, a_pdf_subst_pdr, true,true);
			//загрузим заодно все замены для найденных связей - 
			//чтобы легче можно было выяснить, совместно с чем используется subst_pdf в замене
			i3= ld.AddQuery(_T('r'), i22, e_pdf_subst, a_pdf_subst_pdr, true,true);
				ld.AddQuery(i21,_T('d'), i3, 0, a_pdf_subst_pdf, true,true);//на что можно заменить
			    ld.AddQuery(i22,_T('d'), i3, 0, a_pdf_subst_pdr, true,true);
			    ld.AddQuery(i21,_T('d'), i22, 0, a_pdr_r_ting, true,true);
			    ld.AddQuery(i21,_T('d'), i22, 0, a_pdr_r_ted, true,true);//что можно заменить
				ld.AddQuery(_T('d'), i21,0, a_pdf_prd, true,true);*/
			int i1,i21,i22,i3;
			i1=	ld.AddQuery(_T('b'), subst_pdf->GetId(), e_pdf_subst, a_pdf_subst_pdf, true,true);
			i21=ld.AddQuery(_T('d'), i1, 0, a_pdf_subst_pdf, true,true);//на что можно заменить
			i22=ld.AddQuery(_T('d'), i1, 0, a_pdf_subst_pdr, true,true);
				ld.AddQuery(i21,_T('d'), i22, 0, a_pdr_r_ting, true,true);
			    ld.AddQuery(i21,_T('d'), i22, 0, a_pdr_r_ted, true,true);//что можно заменить
				ld.AddQuery(_T('d'), i21,0, a_pdf_prd, true,true);
			//загрузим заодно все замены для найденных связей - 
			//чтобы легче можно было выяснить, совместно с чем используется subst_pdf в замене
			i3= ld.AddQuery(_T('r'), i22, e_pdf_subst, a_pdf_subst_pdr, true,true);
			i21=ld.AddQuery(_T('d'), i3, 0, a_pdf_subst_pdf, true,true);//на что можно заменить
			i22=ld.AddQuery(_T('d'), i3, 0, a_pdf_subst_pdr, true,true);
			    ld.AddQuery(i21,_T('d'), i22, 0, a_pdr_r_ting, true,true);
			    ld.AddQuery(i21,_T('d'), i22, 0, a_pdr_r_ted, true,true);//что можно заменить
				ld.AddQuery(_T('d'), i21,0, a_pdf_prd, true,true);
			if (!ld.LoadEx())
			{
				if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
					if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
				}
			}
		}
	}
	CaplInstance *inst0,*inst1;
    m_data->GetEntityExtent(e_pdf_subst,ext0);
	for(i=0;i<ext0.Size;i++)
	{
		m_data->GetAttr(ext0[i],a_pdf_subst_pdf,inst0);
		if(inst0==subst_pdf)
		{
			m_data->GetAttr(ext0[i],a_pdf_subst_pdr,inst1);
			if(inst1==0) continue;
			if(inst1->GetAccessmode()>aplRO) continue;
			ext_rel.Add(ext0[i]);
			ext_pdr.Add(inst1);
		}	
	}
	return true;
}
//*************************************************************
bool CaplProductManager::WhereUsedProduct(aplExtent &pdfs, aplExtent &ext_rel, aplExtent &ext_pdf, bool from_base, bool bPdr, bool bAlt)
{
	ext_rel.Clear();
	ext_pdf.Clear();

	if(m_data==0) return false;
	if(!m_data->IsDictLoad()) return false;
	
	aplExtent ext0, ext1;
	int i;
	
	if(from_base)
	{
		if(m_data->IsConnected())
		{
			// чтение из базы
			CaplLoadData ld(m_data,DEF_SOURCE);
			int i1,i8,i12,i14;
			int i;

			CDisAsmStatusDlg* dlg=0;
			CString buf;
			int iCurIndex(0);

			if(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"), (int)((pdfs.Size-1)/m_MaxItemsLoad)+1);
				dlg->m_count.SetWindowText(buf);	
				dlg->ShowWindow(SW_SHOW);
				dlg->BringWindowToTop();
			}		

			if(pdfs.GetSize()>0)
			{
				// а иначе и запрашивать нечего
				for(i=0; i<pdfs.GetSize(); i++)
				{
					if(pdfs[i]==NULL) continue;
					if(pdfs[i]->GetId()==0) continue;
					if(pdfs[i]->GetType()==0) continue;

					ld.AddQuery(0, pdfs[i], true);
					iCurIndex++;

					if(iCurIndex==m_MaxItemsLoad || i+1==pdfs.Size)
					{
						if(ld.IsQueryNotEmpty())
						{
							i1=	ld.AddQuery(_T('r'), 0, e_pdr, a_pdr_r_ted, true,true);
							i8=	ld.AddQuery(_T('d'), i1, 0, a_pdr_r_ting, true,true);
							i12=ld.AddQuery(_T('d'), i8, 0, a_pdf_prd, true,true);
							// чтение effectivity
							i14=ld.AddQuery(_T('r'), i1, e_pd_eff, a_pde_usage, true,true);
							//Загружаем информацию об альтернативах
							int i2;
							i2=	ld.AddQuery(_T('r'), 0, e_alt_bidir, a_alt_base_pdf, true,true);
								ld.AddQuery(_T('d'), i2, 0, a_alt_alt_pdf, true,true);
							i2=	ld.AddQuery(_T('r'), 0, e_alt_bidir, a_alt_alt_pdf, true,true);
								ld.AddQuery(_T('d'), i2, 0, a_alt_base_pdf, true,true);
							if (!ld.LoadEx())
							{
								if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS)
								{
									if(m_api->m_ModeInteractive)
										AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
								}
							}
						}

						if(dlg)
						{
							buf.Format( APL_T("%i из %i"), (int)(i+1)/m_MaxItemsLoad, (int)((pdfs.Size-1)/m_MaxItemsLoad)+1);
							dlg->m_count.SetWindowText(buf);	
							dlg->BringWindowToTop();
						}

						ld.ClearQuery();
						iCurIndex= 0;
					}
				}
			}
			if(dlg)
			{
				dlg->ShowWindow(SW_HIDE);
				dlg->DestroyWindow();
				delete dlg;		
			}
		}
	}
	m_data->GetEntityExtent(e_pdr,ext0);
	for(i=0;i<ext0.Size;i++)
	{
		CaplInstance *inst0;
		m_data->GetAttr(ext0[i],a_pdr_r_ted,inst0);
		if(inst0!=0)
		{
			if(pdfs.Find(inst0)>-1)
			{
				m_data->GetAttr(ext0[i],a_pdr_r_ting,inst0);
				if(inst0!=0 && bPdr==true)
				{
					ext_rel.Add(ext0[i]);
					ext_pdf.Add(inst0);
				}
			}
		}
	}

	m_data->GetEntityExtent(e_alt_bidir, ext1);
	for(i=0; i<ext1.Size ; i++)
	{
		CaplInstance *inst1;
		m_data->GetAttr(ext1[i], a_alt_alt_pdf,inst1);
		if (inst1!=0)
		{
			if (pdfs.Find(inst1)>-1)
			{
				m_data->GetAttr(ext1[i],a_alt_base_pdf, inst1);
				if (inst1!=0 && bAlt==true)
				{
					ext_rel.Add(ext1[i]);
					ext_pdf.Add(inst1);
				}
			}
		}
		m_data->GetAttr(ext1[i], a_alt_base_pdf,inst1);
		if (inst1!=0)
		{
			if (pdfs.Find(inst1)>-1)
			{
				m_data->GetAttr(ext1[i],a_alt_alt_pdf, inst1);
				if (inst1!=0 && bAlt==true)
				{
					ext_rel.Add(ext1[i]);
					ext_pdf.Add(inst1);
				}
			}
		}
	}

	return true;
}

bool CaplProductManager::WhereUsedProduct(CaplInstance *pdf, aplExtent &ext_rel, aplExtent &ext_pdf, bool from_base, bool bPdr, bool bAlt)
{
	aplExtent pdfs;
	pdfs.Add(pdf);
	return WhereUsedProduct(pdfs, ext_rel, ext_pdf, from_base, bPdr, bAlt);
}
//*************************************************************
bool CaplProductManager::FilterlByLastSN(aplExtent &inExt, aplExtent &outExt)
{
	outExt.Clear();
	if(e_prd==0) return false;
	if(m_data==0) return false;
	int iUse = 0;
	if(!m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("kvz\\VARIABLES\\m_bUseParentsRel"),iUse))
		iUse = 0;

	int i,j;
	bool has_eff, bHide;
	CString sn_start,sn_end;
	CaplInstance *inst, *inst1;
	CaplInstance* ciBufInst;
	aplExtent ext_sne;
	m_data->GetEntityExtent(e_sn_eff,ext_sne);

	for(i=0; i<inExt.Size; i++)
	{
		inst=inExt[i];
		has_eff=false;
		for(j=0; j<ext_sne.Size; j++)
		{
			m_data->GetAttr(ext_sne[j],a_pde_usage,inst1);
			if(inst==inst1)
			{				
				has_eff=true;
				m_data->GetAttr(ext_sne[j], a_pde_not_active, bHide);
				if(bHide) continue;
				m_data->GetAttr(ext_sne[j],a_sn_eff_start,sn_start);
				m_data->GetAttr(ext_sne[j],a_sn_eff_end,sn_end);
				if(sn_start==_T("") && sn_end==_T(" "))continue;

				if(sn_start!=_T("") && sn_end==_T("") || sn_start==_T("") && sn_end==_T(""))
				{
					has_eff= false;
					break;
				}
			}
		}
		if(!has_eff)
		{
			if (iUse!=0)
			{
				m_api->m_data.GetAttr(inExt[i],a_pdr_parent_reference,ciBufInst);
				if (ciBufInst)
				{
					has_eff=false;
					for(j=0; j<ext_sne.Size; j++)
					{
						bool bHide= false;
						m_data->GetAttr(ext_sne[j], a_pde_not_active, bHide);
						if(bHide) continue;
						m_data->GetAttr(ext_sne[j],a_pde_usage,inst1);
						if(ciBufInst==inst1)
						{
							m_data->GetAttr(ext_sne[j],a_sn_eff_start,sn_start);
							if(sn_start==_T("") && sn_end==_T(" "))continue;

							if(sn_start!=_T("") && sn_end==_T(""))
							{
								has_eff= false;
								break;
							}
						}
					}				
				}
			}
		}
		if(!has_eff) outExt.Add(inst);
	}
	return true;
}

bool CaplProductManager::FilterlBySN(aplExtent &inExt, const TCHAR *sn, aplExtent &outExt)
{
	outExt.Clear();
	if(e_prd==0) return false;
	if(m_data==0) return false;
	if(sn==0) return false;
	int iUse = 0;
	if(!m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("kvz\\VARIABLES\\m_bUseParentsRel"),iUse))
		iUse = 0;	

	int i,j;
	bool has_eff;
	CString sn_start,sn_end;
	CString strSN = CString(sn);
	CaplInstance *inst, *inst1;
	CaplInstance* ciBufInst;
	aplExtent ext_sne;
	m_data->GetEntityExtent(e_sn_eff,ext_sne);
	for(i=0; i<inExt.Size; i++)
	{
		inst=inExt[i];
		has_eff=false;
		for(j=0; j<ext_sne.Size; j++)
		{
			bool bHide= false;
			m_data->GetAttr(ext_sne[j],a_pde_usage,inst1);
			if(inst==inst1)
			{
				has_eff=true;
				m_data->GetAttr(ext_sne[j], a_pde_not_active, bHide);
				if(bHide) continue;
				m_data->GetAttr(ext_sne[j],a_sn_eff_start,sn_start);
				m_data->GetAttr(ext_sne[j],a_sn_eff_end,sn_end);
 				if(sn_start==_T("") && sn_end==_T(" "))continue;

//				if(sn_start>sn) continue;
				if(funcCompareSN == NULL) 
					continue;
				if (sn_start!=_T("") && funcCompareSN(sn_start, strSN) == 1)
					continue;

				if(sn_end==_T("")){has_eff=false; break;}

//				if(sn_end>=sn){has_eff=false; break;}
				if (funcCompareSN(sn_end, strSN) != -1)
				{
					has_eff = false;
					break;
				}
			}
		}
		if(!has_eff)
		{
			if (iUse!=0)
			{
				m_api->m_data.GetAttr(inExt[i],a_pdr_parent_reference,ciBufInst);
				if (ciBufInst)
				{
					has_eff=false;
					for(j=0; j<ext_sne.Size; j++)
					{
						bool bHide= false;
						m_data->GetAttr(ext_sne[j], a_pde_not_active, bHide);
						if(bHide) continue;
						m_data->GetAttr(ext_sne[j],a_pde_usage,inst1);
						if(ciBufInst==inst1)
						{
							has_eff=true;
							m_data->GetAttr(ext_sne[j],a_sn_eff_start,sn_start);
							if(sn_start==_T(""))continue;

							//				if(sn_start>sn) continue;
							if(funcCompareSN == NULL) 
								continue;

							if (funcCompareSN(sn_start, strSN) == 1)
								continue;

							m_data->GetAttr(ext_sne[j],a_sn_eff_end,sn_end);

							if(sn_end==_T("")){has_eff=false; break;}

							//				if(sn_end>=sn){has_eff=false; break;}
							if (funcCompareSN(sn_end, strSN) != -1)
							{
								has_eff = false;
								break;
							}
						};
					}				
				}
			}
		}
		if(!has_eff) outExt.Add(inst);
	}
	return true;
}
//*************************************************************
bool CaplProductManager::FilterByChange(aplExtent &rels, CaplInstance *change, aplExtent &extOut, aplExtent *extParents, bool bLoadFromBase)
{
	CaplInstance *cit = NULL;
	bool bOldUnc = extOut.Unique;
	extOut.Unique = false;
	extOut.Clear();
	if(!change) {	extOut.Append(rels);	extOut.Unique = bOldUnc;	return true;}
	if(!change->GetId() || !change->GetType() || !m_api->m_data.IsKindOf(change, m_api->m_change_mgr.e_chng))
	{	extOut.Append(rels);	extOut.Unique = bOldUnc;	return true;}

	if(bLoadFromBase && m_data->IsConnected() && change->GetId())
	{
// 		int qpsc;
// 		CaplLoadData ld(m_data,DEF_SOURCE);
// 		ld.AddQuery(change, true);
// 		qpsc = ld.AddQuery(_T('d'), 0, 0, m_api->m_change_mgr.a_chng_items, true, true);
		if(!m_api->m_change_mgr.LoadChangeInfo(change))
//		if(!ld.LoadEx())
		{
		//	if(m_api->m_ModeInteractive) AfxMessageBox(_T(""));
			extOut.Append(rels);	extOut.Unique = bOldUnc;	return false;
		}
	}


	aplExtent extPSC;  extPSC.Unique  = false;
	aplExtent extAdd;  extAdd.Unique  = false;

	std::sort(rels.Data, rels.Data + rels.Size);
	extOut.SetSize(rels.GetSize()+2);
	extOut.Append(rels);
	
	CString sState;
	m_api->m_data.GetAttr(change, m_api->m_change_mgr.a_chng_items, sState);
	if(sState==_T("applied"))
	{
		extOut.Unique = bOldUnc;
		return true;
	}

	// get change items
	m_data->GetAttr(change, m_api->m_change_mgr.a_chng_items, extPSC);
	std::sort(extPSC.Data, extPSC.Data + extPSC.Size);
	CSortClass::MakeExtUnique(extPSC, true); // на всякий случай
	if(extParents)
		extParents->Sort();
	rels.Sort();

	int i, fi;
	CaplInstance *ted, *ting, *ch;
	for (i=0; i<extPSC.GetSize(); i++)
	{
		ch = extPSC[i];
		if(!ch) continue;
		if((ch->GetType() != m_api->m_change_mgr.e_psc) || (ch->GetAccessmode() > aplRO)) continue;
		m_data->GetAttr(ch, m_api->m_change_mgr.a_psc_changed_product, ted);
		m_data->GetAttr(ch, m_api->m_change_mgr.a_psc_changing_product, ting);
		if(!ted) continue;
// 		if(!ting) continue;
		if(m_data->IsKindOf(ted, e_pdf))
		{
			// добавление
			if(extParents) 
			{
				if(aplQFindInstIdInExtent(*extParents, ted->GetId()) == -1) continue;
				//if(!std::binary_search(extParents->Data, extParents->Data + extParents->Size, ted))
				//	continue;
			}

			extAdd.Add(ch);
		}
		else
		{
			if(extParents)
			{
				m_api->m_data.GetAttr(ted, a_pdr_r_ting, cit);
				if(!cit) continue;
				if(aplQFindInstIdInExtent(*extParents, cit->GetId()) == -1) continue;
				//if(!std::binary_search(extParents->Data, extParents->Data + extParents->Size, cit))
				//	continue;
			}

			// удаление или замена
			fi = aplQFindInstIdInExtent(rels, ted->GetId());
			if(fi == -1) continue;
			//fi = std::lower_bound(rels.Data, rels.Data+rels.Size, ted) - rels.Data;
			//if(fi == rels.GetSize()) continue;
			extOut.SetAt(fi, ting ? ch : NULL);
		}
	}

	// выбрасываем удаленные
#if _MSC_VER >= 1400
	//extOut.Size = std::remove_if(extOut.Data, extOut.Data + extOut.Size, FnNULLInst) - extOut.Data;
	for (i = extOut.GetSize() - 1; i >= 0; i--)
	{
		if (extOut[i] == NULL)
			extOut.Remove(i);
			
	}
#else
	extOut.Size = std::remove_if(extOut.Data, extOut.Data + extOut.Size, FnNULLInst) - extOut.Data;
#endif
	extOut.Append(extAdd); // добавляем новые позиции
	extOut.Unique = bOldUnc;
	return true;
}
//*************************************************************
bool CaplProductManager::FilterlByDate(aplExtent &inExt, COleDateTime &time, aplExtent &outExt)
{
	outExt.Clear();
	if(e_prd==0) return false;
	if(m_data==0) return false;
	int i,j,countDatedEff;
	CaplInstance *inst0;
	CString s_start, s_end, dt,sStr, sEnd, pdeId;
	aplExtent ext_pd_eff, all_eff,ext_dat_eff;
	bool bFictiveEff, bHasEff, bActual, bHasFictive, bHide;

	int iUse = 0;
	if(!m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("kvz\\VARIABLES\\m_bUseParentsRel"),iUse))
		iUse = 0;

	if(!aplDate2String(time,dt))return false;
	//
	m_data->GetEntityExtent(e_pd_eff,ext_pd_eff);
	m_data->GetEntityExtent(e_dat_eff,ext_dat_eff);
	aepedeMap aepedeMapRel;
	aepedeMapIt aepedeMapIter;
	for (i=0;i<ext_pd_eff.Size;i++)
	{
		m_data->GetAttr(ext_pd_eff[i],a_pde_usage,inst0);
		aepedeMapIter = aepedeMapRel.find(inst0);
		if (aepedeMapIter == aepedeMapRel.end())
		{
			CPdEffDatEff* aepedeItem = new CPdEffDatEff;
			aepedeMapIter = aepedeMapRel.insert(std::make_pair(inst0,aepedeItem)).first;
		}
		aepedeMapIter->second->aePdEff.Add(ext_pd_eff[i]);
	}
	for (i=0;i<ext_dat_eff.Size;i++)
	{
		m_data->GetAttr(ext_dat_eff[i],a_pde_usage,inst0);
		aepedeMapIter = aepedeMapRel.find(inst0);
		if (aepedeMapIter == aepedeMapRel.end())
		{
			CPdEffDatEff* aepedeItem = new CPdEffDatEff;
			aepedeMapIter = aepedeMapRel.insert(std::make_pair(inst0,aepedeItem)).first;
		}
		aepedeMapIter->second->aeDatEff.Add(ext_dat_eff[i]);

	}
	for (i=0;i<inExt.Size;i++)
	{
		inst0 = inExt[i];		

		//используем не только связь, но и ссылку с нее на другую
		int l;
		int iGood = 0;
		aplExtent aeBufExt;
		CaplInstance* ciBufInst = NULL;
		aeBufExt.Add(inst0);
		if (iUse!=0)
		{
			m_api->m_data.GetAttr(inst0,m_api->m_prd_mgr.a_pdr_parent_reference,ciBufInst);
			if (ciBufInst)
				aeBufExt.Add(ciBufInst);
		}

		for (l=0;l<aeBufExt.GetSize(); l++)
		{
			bFictiveEff= true;
			bHasEff= false;
			sStr=_T("");	
			ciBufInst = aeBufExt[l];
			aepedeMapIter = aepedeMapRel.find(ciBufInst);
			if (aepedeMapIter!=aepedeMapRel.end())
			{
				for (j=0;j<aepedeMapIter->second->aePdEff.Size;j++)
				{
					m_data->GetAttr(aepedeMapIter->second->aePdEff[j], a_pde_not_active, bHide);
					if(bHide)
						continue;

					bHasEff = true;
					all_eff.Add(aepedeMapIter->second->aePdEff[j]);

					if(m_data->IsKindOf(aepedeMapIter->second->aePdEff[j], m_api->m_prd_mgr.e_dat_eff))
					{
						m_data->GetAttr(aepedeMapIter->second->aePdEff[j], m_api->m_prd_mgr.a_dat_eff_start_s, sStr);
						m_data->GetAttr(aepedeMapIter->second->aePdEff[j], m_api->m_prd_mgr.a_dat_eff_end_s, sEnd);
						//""->"" ""->"1901 0101 000000" "1900 0101 000000"->"1901 0101 000000"
						if(!((sStr==_T("") && sEnd==_T("")) || (sStr==_T("") && sEnd==_T("19010101000000")) || (sStr==_T("19000101000000") && sEnd==_T("19010101000000"))))
						{
							bFictiveEff= false;
							break;
						}
					}
					else if(m_data->IsKindOf(aepedeMapIter->second->aePdEff[j], m_api->m_prd_mgr.e_sn_eff))
					{
						m_data->GetAttr(aepedeMapIter->second->aePdEff[j], m_api->m_prd_mgr.a_pde_id, pdeId);
						m_data->GetAttr(aepedeMapIter->second->aePdEff[j], m_api->m_prd_mgr.a_sn_eff_start, sStr);
						m_data->GetAttr(aepedeMapIter->second->aePdEff[j], m_api->m_prd_mgr.a_sn_eff_end, sEnd);

						if(sStr == _T(" ") && sEnd == _T(" ") && pdeId == _T("fictive"))
							continue;;

						if(!sStr.IsEmpty() || !sEnd.IsEmpty()) 
						{
							bFictiveEff= false;
							break;
						}

						// если правило одно и концы серийных номеров не указаны, то pdf оставляем
						if(sStr.IsEmpty() && sEnd.IsEmpty() && aeBufExt.Size == 1)
							iGood++;
					}

				}
				//или нет фиктивных правил, или есть, но оно не одно

				if(!bFictiveEff)
				{
					bActual=false;
					bHasFictive=false;
					countDatedEff=0;
					s_start=_T("");
					s_end=_T("");
					for (j=0;j<aepedeMapIter->second->aeDatEff.Size;j++)
					{
						bHide= false;
						m_data->GetAttr(aepedeMapIter->second->aeDatEff[j], a_pde_not_active, bHide);
						if(bHide) continue;
						
						m_data->GetAttr(aepedeMapIter->second->aeDatEff[j], a_dat_eff_start_s, s_start);
						m_data->GetAttr(aepedeMapIter->second->aeDatEff[j], a_dat_eff_end_s, s_end);
						if(s_start.IsEmpty() || s_start==_T("19000101000000"))
						{
							if(s_end.IsEmpty()|| s_end==_T("19010101000000")) {bHasFictive=true; /*countDatedEff--;*/}
							else if(dt<s_end) 
							{
								countDatedEff++;
								bActual=true;
							}
						}
						else 
						{
							countDatedEff++;

							if(dt>=s_start)
							{
								if(s_end==_T("")) bActual=true;
								else 
								{
									if(dt<s_end) bActual=true;
								}
							}
						}

					}
					//if(((!bActual)&&(countDatedEff>0))||(bHasFictive && (countDatedEff==0)))
					if(false == bActual && countDatedEff > 0)
						continue;
				}
				else
				if (bHasEff)
					continue;

			}
			iGood++;
		}
		if (iGood==aeBufExt.Size )
			outExt.Add(inst0);
	}
	for (aepedeMapIter = aepedeMapRel.begin();aepedeMapIter != aepedeMapRel.end();++aepedeMapIter)
		delete aepedeMapIter->second;
	aepedeMapRel.clear();

		

// 
// 	for (i=0;i<inExt.Size;i++)
// 	{
// 		inst = inExt[i];
// 		bFictiveEff= true;
// 		bHasEff= false;
// 		sStr=_T("");	
// 		for(j=0;j<ext_pd_eff.Size; j++)
// 		{
// 			m_data->GetAttr(ext_pd_eff[j], m_api->m_prd_mgr.a_pde_usage, inst0);
// 			if(inst0==inst)
// 			{
// 				bHasEff= true;
// 				all_eff.Add(ext_pd_eff[j]);
// 				
// 				if(m_data->IsKindOf(ext_pd_eff[j], m_api->m_prd_mgr.e_dat_eff))
// 				{
// 					m_data->GetAttr(ext_pd_eff[j], m_api->m_prd_mgr.a_dat_eff_start_s, sStr);
// 					if(!sStr.IsEmpty() && sStr.CompareNoCase(_T("19000101000000"))) 
// 					{
// 						bFictiveEff= false;
// 						break;
// 					}
// 				}
// 				else if(m_data->IsKindOf(ext_pd_eff[j], m_api->m_prd_mgr.e_sn_eff))
// 				{
// 					m_data->GetAttr(ext_pd_eff[j], m_api->m_prd_mgr.a_sn_eff_start, sStr);
// 					if(!sStr.IsEmpty()) 
// 					{
// 						bFictiveEff= false;
// 						break;
// 					}
// 				}
// 			}
// 		}
// 		//или нет фиктивных правил, или есть, но оно не одно
// 
// 		if(!bFictiveEff)
// 		{
// 			bActual=false;
// 			bHasFictive=false;
// 			countDatedEff=0;
// 			s_start=_T("");
// 			s_end=_T("");
// 			for (j=0;j<ext_sne.Size;j++)
// 			{
// 				bHide= false;
// 				m_data->GetAttr(ext_sne[j], a_pde_not_active, bHide);
// 				if(bHide) continue;
// 				m_data->GetAttr(ext_sne[j], a_pde_usage, inst0);
// 				if(inst0==inst)
// 				{
// 					countDatedEff++;
// 					m_data->GetAttr(ext_sne[j], a_dat_eff_start_s, s_start);
// 					m_data->GetAttr(ext_sne[j], a_dat_eff_end_s, s_end);
// 					if(s_start.IsEmpty() || s_start==_T("19000101000000"))
// 					{
// 						if(s_end.IsEmpty()|| s_end==_T("19000101000000")) {bHasFictive=true; /*countDatedEff--;*/}
// 						else if(dt<s_end) bActual=true;
// 					}
// 					else 
// 					{
// 						if(dt>=s_start)
// 						{
// 							if(s_end==_T("")) bActual=true;
// 							else 
// 							{
// 								if(dt<s_end) bActual=true;
// 							}
// 						}
// 					}
// 				}
// 			}
// 			if(((!bActual)&&(countDatedEff>0))||(bHasFictive && (countDatedEff==0)))
// 				continue;
// 		}
// 		else
// 		if (bHasEff)
// 			continue;
// 		outExt.Add(inst);
// 	}





	


/*


	m_data->GetEntityExtent(e_dat_eff,ext_sne);
	for(i=0; i<inExt.Size; i++)
	{
		inst=inExt[i];
		has_eff=false;
		for(j=0; j<ext_sne.Size; j++)
		{
			bool bHide= false;
			m_data->GetAttr(ext_sne[j], a_pde_not_active, bHide);
			if(bHide) continue;
			m_data->GetAttr(ext_sne[j],a_pde_usage,inst1);
			if(inst==inst1)
			{
				has_eff=true;
				m_data->GetAttr(ext_sne[j],a_dat_eff_start_s,start);
				if(start==_T("")) continue;
				if(start>dt) continue;
				m_data->GetAttr(ext_sne[j],a_dat_eff_end_s,end);
				if(end==_T("")){has_eff=false; break;}
				if(end>=dt){has_eff=false; break;}
			}
		}
		if(!has_eff) outExt.Add(inst);
	}*/
	return true;
}     

bool CaplProductManager::SelectDateSN(CString &sn, COleDateTime &time, CaplInstance *context, CaplInstance **chosen_context)
{
	CaplSetResourceHandle setres(module_inst);
	
	CAddDateSn dlg;
	dlg.m_sn= sn;
	if(time.GetStatus()==COleDateTime::valid) dlg.m_dt=time;
		else dlg.m_dt.SetStatus(COleDateTime::null);

	dlg.m_context=context;
	dlg.m_api=m_api;

 	if(dlg.DoModal()==IDOK)
 	{
		sn=dlg.m_sn;
		time=dlg.m_dt;
		if(dlg.m_context) *chosen_context=dlg.m_context;
		
		return true;
	}
	
	return false;
}
//*************************************************************
bool CaplProductManager::SelectConfiguration(CaplInstance *pPdf, CaplInstance** pConfiguration, CaplInstance** pOrder/*=NULL*/)
{

	CChooseConfigDlg dlg;

	dlg.m_api = m_api;
	dlg.m_bLoadConfigurationMgr = true;
	if(pConfiguration!=NULL)
	{
		dlg.m_pSelectedItem = *pConfiguration;
	}
	if(pOrder!=NULL)
	{
		dlg.m_pOrder= *pOrder;
	}
	dlg.m_pProductPDF = pPdf;

	if (dlg.DoModal() == IDOK)
	{
		if(pConfiguration!=NULL)
		{
			*pConfiguration = dlg.m_pSelectedItem;
		}
		if(pOrder!=NULL)
		{
			*pOrder= dlg.m_pOrder;
		}

		if(pConfiguration!=NULL)
		{
			return true;
		}
	}
	return false;
}

bool CaplProductManager::GetAllProductVersion(CaplInstance *prd,aplExtent &outExt)
{
	outExt.Clear();
	if(e_prd==0) return false;
	if(m_data==0) return false;
	if(prd==0) return false;
	if(prd==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(prd->GetType()==0) return false;
//	int i,j;
//	if(prd->id!=0)
//	{
//		// Чтение из базы
//		CaplLoadData ld(m_data,DEF_SOURCE);
//		// документ
//		j=ld.AddQuery(_T('b'), prd->id, e_pdf,a_pdf_prd, true,true);
//		ld.LoadEx();
//	}
//	CaplInstance *inst;
//	aplExtent ext_pdf;
//	// Чтение версий
//	m_data->GetEntityExtent(e_pdf,ext_pdf);
//	for(i=0;i<ext_pdf.Size;i++)
//	{
//		if(ext_pdf[i]==0) continue;
//		if(ext_pdf[i]->GetType()==0) continue;
//		if(ext_pdf[i]->GetAccessmode()>aplRO) continue;
//		m_data->GetAttr(ext_pdf[i],a_pdf_prd,inst);
//		if(inst==prd) outExt.Add(ext_pdf[i]);
//	}
	aplExtent ext;
	ext.Add(prd);
	return GetAllProductVersion(ext, outExt);
}
/************************************************************************/
bool CaplProductManager::GetAllProductVersion(aplExtent &prds,aplExtent &outExt)
{
	outExt.Clear();
	if(e_prd==0) return false;
	if(m_data==0) return false;
	if(prds.GetSize()==0) return false;

	int i;
	if(m_api->m_data.IsConnected() && prds.GetSize()>0)
	{
		CaplLoadData ld(m_data,DEF_SOURCE);
		bool bLoad = false;
		for(i=0; i<prds.GetSize(); i++)
		{
			if(prds[i]->GetId()!=0)
			{
				ld.AddQuery(0, prds[i]);
				bLoad = true;
			}
		}
		if(bLoad)
		{
			ld.AddQuery(_T('r'), 0, e_pdf, a_pdf_prd, true,true);
			ld.LoadEx();
		}
	}
	CaplInstance *inst;
	aplExtent ext_pdf;
	// Чтение версий
	m_data->GetEntityExtent(e_pdf,ext_pdf);
	for(i=0;i<ext_pdf.Size;i++)
	{
		if(ext_pdf[i]==0) continue;
		if(ext_pdf[i]->GetType()==0) continue;
		if(ext_pdf[i]->GetAccessmode()>aplRO) continue;
		m_data->GetAttr(ext_pdf[i],a_pdf_prd,inst);
		if(prds.Find(inst)>-1)
			outExt.Add(ext_pdf[i]);
	}
	return true;
}
//*************************************************************
CaplInstance *CaplProductManager::FindPrdById(const TCHAR *id, bool bIgnoreSpaces)
{
	if (id==0)return 0;
	if (m_data==0)return 0;
	if(e_prd==0) return 0;

	aplExtent ext;
	CaplAttrValue tst_value;

	tst_value.value.Set(id);
	tst_value.attr=a_prd_id;
	m_data->NET_FindInstancesWithAttrValues2(e_prd,1,&tst_value,ext,false,false,NULL,aplSBMiddle,bIgnoreSpaces,DEF_SOURCE);
	if(ext.Size==0) return 0;
	
	CaplInstance *prd=ext[0];
	return prd;
}
//*************************************************************
CaplInstance *CaplProductManager::FindPdfById(CaplInstance *prd, const TCHAR *id, bool bIgnoreSpaces)
{
	if (id==0)return 0;
	if (m_data==0)return 0;
	if (prd==0)return 0;
	if (prd==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if (prd->GetType()==0)return 0;
	if(e_prd==0) return 0;

	aplExtent ext;
	CaplAttrValue tst_value[2];

	tst_value[0].value.Set(id);
	tst_value[0].attr=a_pdf_id;;
	tst_value[1].value.Set(prd);
	tst_value[1].attr=a_pdf_prd;
	m_data->NET_FindInstancesWithAttrValues2(e_pdf,2,&tst_value[0],ext,false,false,NULL,aplSBMiddle,bIgnoreSpaces,DEF_SOURCE);
	if(ext.Size==0) return 0;
	
	CaplInstance *pdf=ext[0];
	return pdf;
}

//*************************************************************
CaplInstance *CaplProductManager::FindPdfByCode(const TCHAR *code, bool bIgnoreSpaces)
{
	if (code==0)return 0;
	if (m_data==0)return 0;
	
	aplExtent ext;
	CaplAttrValue tst_value[1];

	tst_value[0].value.Set(code);
	tst_value[0].attr=a_pdf_code;
	m_data->NET_FindInstancesWithAttrValues2(e_apl_pdf, 1, &tst_value[0], ext,false,false,NULL,aplSBMiddle,bIgnoreSpaces,DEF_SOURCE);
	if(ext.Size==0) return 0;
	
	CaplInstance *pdf=ext[0];
	return pdf;
}

//*************************************************************
CaplInstance *CaplProductManager::FindPdfByCode1(const TCHAR *code1, bool bIgnoreSpaces)
{
	if (code1==0)return 0;
	if (m_data==0)return 0;
	
	aplExtent ext;
	CaplAttrValue tst_value[1];

	tst_value[0].value.Set(code1);
	tst_value[0].attr=a_pdf_code1;
	m_data->NET_FindInstancesWithAttrValues2(e_apl_pdf, 1, &tst_value[0], ext,false,false,NULL,aplSBMiddle,bIgnoreSpaces,DEF_SOURCE);
	if(ext.Size==0) return 0;
	
	CaplInstance *pdf=ext[0];
	return pdf;
}

//*************************************************************
bool CaplProductManager::LoadPrdInfo(CaplInstance *inst)
{
	if (inst==0)return 0;
	if (inst==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if (inst->GetType()==0)return 0;
	if (m_data==0)return 0;
	if(e_prd==0) return false;

	if(inst->GetId()==0) return true;

	aplExtent ext; ext.Unique=false; ext.Add(inst);
	return LoadPrdInfo(ext);	
}
//*************************************************************
bool CaplProductManager::LoadPrdInfo(aplExtent &ext)
{
	CaplStackLogger logger(_T("CaplProductManager::LoadPrdInfo"));
	if (m_data==0)return false;
	if(e_prd==0) return false;

	if(!m_data->IsConnected()) return true;
	
	// Чтение из базы
	CaplLoadData ld(m_data,DEF_SOURCE);
	int indx_load_prd=-1;
	int indx_load_pdf=-1;
	int load_p=0;

	int i,j;
	for(i=0;i<ext.Size;i++)
	{
		if(m_bContinue)
		{
			if(*m_bContinue==false) break;
		}
		CaplInstance *prd=ext[i];
		// DIV: переделал на серию else if. Если оставить конструкции типа if(prd==0) continue; - то при последнем инстансе в экстенте ==0 запрос для первых выполнен не будет
		if (prd==0){;}
		else if(prd==(CaplInstance*)-1)
		{
			if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
			return false;
		}
		else if(prd->GetId()==0 || prd->GetType()==0){;}
		else if(m_data->IsKindOf(prd,e_prd))
		{
			if(indx_load_prd==-1){indx_load_prd = ld.AddQuery(-1,prd,true);}
			else{ld.AddQuery(indx_load_prd,prd,true);}
			load_p++;
		}
		else if(m_data->IsKindOf(prd,e_pdf))
		{
			if(indx_load_pdf==-1){indx_load_pdf = ld.AddQuery(-1,prd,true);}
			else{ld.AddQuery(indx_load_pdf,prd,true);}
			load_p++;
		}
		if(m_bContinue)
		{
			if(*m_bContinue==false) return false;
		}
		if((load_p==m_MaxItemsLoad || i==(ext.Size-1)) && (indx_load_pdf!=-1 || indx_load_prd!=-1))
		{
			if(indx_load_pdf!=-1)
			{
				j=ld.AddQuery(_T('d'), indx_load_pdf, 0,a_pdf_prd, true,true);
				j=ld.AddQuery(_T('d'), indx_load_pdf, 0,a_apl_pdf_first_usage, true,true);
				j=ld.AddQuery(_T('d'), j, 0,a_pdf_prd, true,true);
			}
			if(!ld.LoadEx())
			{
				if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
					if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
				}
				return false;
			}
			load_p=0;
			indx_load_prd=-1;
			indx_load_pdf=-1;
		}
		if(m_bContinue)
		{
			if(*m_bContinue==false) return false;
		}
	}

	return true;
}
//*************************************************************
CaplInstance *CaplProductManager::CreatePdf(CaplInstance* prd, const TCHAR *ver, bool testunique)
{
	if(m_api==NULL) return NULL;
	if(bNoCreateAndChangePDF)
	{
		CaplSetResourceHandle setres(module_inst);

		if(m_api->m_ModeInteractive)AfxMessageBox(IDS_NO_CREATE_PDF,MB_OK|MB_ICONSTOP);
		return 0;
	}

	if(!m_api->m_data.IsDictLoad()) return NULL;
	if(prd==NULL) return NULL;
	if(prd==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}

	CaplInstance *pdf=NULL;
	if(testunique)
	{
		pdf=FindPdfById(prd, ver);
		if(pdf!=NULL) return pdf;
	}

	pdf=m_data->CreateInstance(e_apl_pdf);
	m_data->PutAttr(pdf,a_pdf_prd,prd);
	m_data->PutAttr(pdf,a_pdf_id,ver);
	m_data->PutAttr(pdf,a_apl_pdf_state,_T("working"));

	if(m_AutoSave)
		m_api->SaveChanges();
	if(m_AutoUsurpire==true && m_api->m_data.IsConnected())
	{
		CaplEntity*	et	=NULL;
		aplExtent	aet;
		CString		csAccPat;
		
		et=e_pdf;
		
		if(NULL!=prd)
			if(aplOWN==prd->GetAccessmode())
				aet.Add(prd);
			if(NULL!=pdf)
				if(aplOWN==pdf->GetAccessmode())
					aet.Add(pdf);
				if(TRUE==m_api->m_options_mgr.GetDefPatern(et,csAccPat))
					apidata.NET_SetAccessFromPattern(&aet,csAccPat);
	}

	return pdf;
}
//*************************************************************
CaplInstance *CaplProductManager::CreatePdf(const TCHAR *id,const TCHAR *name, const TCHAR *ver, bool testunique)
{
	if(bNoCreateAndChangePDF)
	{
		CaplSetResourceHandle setres(module_inst);

		if(m_api->m_ModeInteractive)AfxMessageBox(IDS_NO_CREATE_PDF,MB_OK|MB_ICONSTOP);

		return 0;
	}

	if (e_prd==0)return 0;
	if (m_data==0)return 0;
	if(id==0) return 0;
	if(name==0) return 0;
	if(ver==0) return 0;

	CaplInstance *pdf=0, *prd=0;

	if(testunique)
	{
		prd=FindPrdById(id);
		if(prd!=0) pdf=FindPdfById(prd,ver);
		if(pdf!=0) return pdf;
	}
	if(prd==0)
	{
		prd=m_data->CreateInstance(e_prd);
		m_data->PutAttr(prd,a_prd_id,id);
		m_data->PutAttr(prd,a_prd_name,name);
	}
	pdf=m_data->CreateInstance(e_apl_pdf);
	m_data->PutAttr(pdf,a_pdf_prd,prd);
	m_data->PutAttr(pdf,a_pdf_id,ver);
	m_data->PutAttr(pdf,a_apl_pdf_state,_T("working"));
	if(m_AutoSave) 
		m_api->SaveChanges();

	if(true==m_AutoUsurpire)
	{
		CaplEntity*	et	=NULL;
		aplExtent	aet;
		CString		csAccPat;

		et=e_pdf;

		if(NULL!=prd)
			if(aplOWN==prd->GetAccessmode())
				aet.Add(prd);
		if(NULL!=pdf)
			if(aplOWN==pdf->GetAccessmode())
				aet.Add(pdf);
		if(TRUE==m_api->m_options_mgr.GetDefPatern(et,csAccPat))
			apidata.NET_SetAccessFromPattern(&aet,csAccPat);
	}
	
	return pdf;
}

//*************************************************************
CaplInstance *CaplProductManager::CreatePdfRelation(CaplInstance *context,
		CaplInstance *relating_pdf, CaplInstance *related_pdf,
		const TCHAR *id,const TCHAR *name, double count, CaplInstance *unit, bool bTestUnique, bool bTestForCycle)
{
	if(m_data==0) return 0;
	if(relating_pdf==0) return 0;
	if(relating_pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(relating_pdf->GetType()==0) return 0;
	if(related_pdf==0) return 0;
	if(related_pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(related_pdf->GetType()==0) return 0;
	if(e_alt_bidir==0) return 0;
	if(e_prd==0) return 0;

	aplExtent ext0;
	CaplInstance *pd_ing=0, *pd_ed=0;

	if(related_pdf==relating_pdf) return NULL;

	if(bTestUnique)
	{
		CaplAttrValue tst_val[2];
		aplExtent res;
		tst_val[0].attr = a_pdr_r_ted;
		tst_val[0].value.Set(related_pdf);
		tst_val[1].attr = a_pdr_r_ting;
		tst_val[1].value.Set(relating_pdf);
		if(m_api->m_data.NET_FindInstancesWithAttrValues(e_pdr, 2, &tst_val[0], res, false)>0)
		{
			aplExtent contexts;
			m_api->m_data.GetAttr(res[0], a_pdr_frames_of_reference, contexts);
			if(contexts.Size==0) return res[0];
			else
			{
				contexts.Add(context);
				m_api->m_data.GetAttr(res[0], a_pdr_frames_of_reference, contexts);
				if(m_AutoSave) m_api->SaveChanges();
				return res[0];
			}
		}
	}

	//Проверяем на зацикливание
	if(bTestForCycle && !m_api->m_data.TestCycleInRelation(e_pdr, a_pdr_r_ting, a_pdr_r_ted, relating_pdf, related_pdf))
		return NULL;

	CaplInstance *pdr=m_data->CreateInstance(e_qacu_nauo);

	if(pdr==0) return 0;

	m_data->PutAttr(pdr,a_pdr_id,id);
	m_data->PutAttr(pdr,a_pdr_name,name);
	m_data->PutAttr(pdr,a_apl_qacu_value,count);
	m_data->PutAttr(pdr,a_apl_qacu_unit,unit);
	m_data->PutAttr(pdr,a_pdr_r_ting,relating_pdf);
	m_data->PutAttr(pdr,a_pdr_r_ted,related_pdf);
	if(context!=0)
	{
		CaplAggr aggr0;
		aggr0.Add(context);
		m_data->PutAttr(pdr,a_pdr_frames_of_reference,aggr0);
	}
	if(m_AutoSave) m_api->SaveChanges();
	return pdr;
}

//*************************************************************
bool CaplProductManager::TestCycleInAlternateRelation (CaplEntity *ent, CaplAttr *in_attr, CaplAttr *out_attr, CaplInstance *in_val, CaplInstance *out_val)
{
	if(ent==0) return false;
	if(in_attr==0) return false;
	if(out_attr==0) return false;
	if(in_val==0) return false;
	if(in_val->GetType()==0) return false;
	if(out_val==0) return false;
	if(out_val->GetType()==0) return false;

	if(in_val==out_val) return false;

	aplExtent ext0,ext1,ext2;
	ext2.Unique=true;
	CaplInstance *inst0;
	CaplInstance *inst1;

	m_api->m_data.GetEntityExtent(ent,ext0);
	m_api->LoadExtentInfo(ext0) ;
	
	for ( int i = 0 ; i < ext0.GetSize() ; i++ )
	{
		m_api->m_data.GetAttr(ext0[i],in_attr,inst0);
		m_api->m_data.GetAttr(ext0[i],out_attr,inst1);

		if ( (inst0 == in_val && inst1 == out_val) || 
			 (inst1 == in_val && inst0 == out_val) )
		{
			return false ;
		}
	}

	return true ;

}

//*************************************************************
CaplInstance *CaplProductManager::CreatePdfAlternateRelation(CaplInstance *context,
		CaplInstance *base_pdf, CaplInstance *alternate_pdf,
		const TCHAR *name, const TCHAR *descr, int type, const TCHAR* type_descr, const TCHAR* reserved, bool bTestUnique)
{
	if(m_data==0) return 0;
	if(alternate_pdf==0) return 0;
	if(alternate_pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(alternate_pdf->GetType()==0) return 0;
	if(base_pdf==0) return 0;
	if(base_pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(base_pdf->GetType()==0) return 0;
	if(e_apl_qacu==0) return 0;
	if(e_prd==0) return 0;

	aplExtent ext0;
	CaplInstance *pd_base=0, *pd_alt=0;

	if(base_pdf==alternate_pdf) return NULL;

	if(bTestUnique)
	{
		CaplAttrValue tst_val[2];
		aplExtent res;
		tst_val[0].attr = a_alt_base_pdf;
		tst_val[0].value.Set(base_pdf);
		tst_val[1].attr = a_alt_alt_pdf;
		tst_val[1].value.Set(alternate_pdf);
		if(m_api->m_data.NET_FindInstancesWithAttrValues(e_pdr, 2, &tst_val[0], res, false)>0)
		{
			aplExtent contexts;
			m_api->m_data.GetAttr(res[0], a_pdr_frames_of_reference, contexts);
			if(contexts.Size==0) return res[0];
			else
			{
				contexts.Add(context);
				m_api->m_data.GetAttr(res[0], a_pdr_frames_of_reference, contexts);
				if(m_AutoSave) m_api->SaveChanges();
				return res[0];
			}
		}
	}

	//Проверяем на зацикливание
	//if(!m_api->m_data.TestCycleInRelation(e_alt_bidir, a_alt_alt_pdf , a_alt_base_pdf, alternate_pdf, base_pdf))
	if(!TestCycleInAlternateRelation(e_alt_bidir, a_alt_alt_pdf , a_alt_base_pdf, alternate_pdf, base_pdf))
		return NULL;

	CaplInstance *alt_rel=m_data->CreateInstance(e_alt_bidir);

	if(alt_rel==0) return 0;

	m_data->PutAttr(alt_rel,a_alt_name,name);
	m_data->PutAttr(alt_rel,a_alt_bidir_type_descr,type_descr);
	m_data->PutAttr(alt_rel,a_alt_bidir_type,type);
	m_data->PutAttr(alt_rel,a_alt_base_pdf,base_pdf);
	m_data->PutAttr(alt_rel,a_alt_alt_pdf,alternate_pdf);
	
	if(context!=0)
	{

	}

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

//*************************************************************
class CaplDisAssemblyPart;
class CaplDisAssemblyElement;

typedef CaplTAggr <CaplDisAssemblyElement*,CaplDisAssemblyElement*,APLAGGR_AUTOKILLREF> TCaplDisAssemblyElements;
typedef CaplTAggr <CaplDisAssemblyPart*,CaplDisAssemblyPart*,APLAGGR_AUTOKILLREF> TCaplDisAssemblyParts;

class CaplDisAssemblyElement
{
public:
	CaplDisAssemblyElement() {pdf=0; unit=0; parent=0; count=0;}
	CaplInstance *pdf;
	CaplInstance *unit;
	double count;
	CaplDisAssemblyPart *parent;
};

class CaplDisAssemblyPart
{
public:
	CaplDisAssemblyPart() {pdf=0;unit=0; count=-1; has_subitem=false;}
	CaplInstance *pdf;
	CaplInstance *unit;
	double count;
	bool has_subitem;
	TCaplDisAssemblyElements elements;
};

//*************************************************************

double GetPartsCount(CaplDisAssemblyPart *part)
{
	if(part==0) return false;
	if(part->count!=-1) return part->count;
	int k=0;
	double count=0;
	for(int i=0;i<part->elements.Size;i++)
	{
		if(part->elements[i]->parent==0)
			count+=part->elements[i]->count;
		else
			count+=part->elements[i]->count*GetPartsCount(part->elements[i]->parent);
	}
	part->count=count;
	return count;
}
//*************************************************************
bool GetFullProductContentsEx(CaplProductManager* prd_mgr, CaplNetStepData *m_data, CaplInstance *pdf,
							TCaplDisAssemblyParts &parts, CaplDisAssemblyPart *my_part,
							CaplInstance *context,	COleDateTime *time, const TCHAR *sn,
							CDisAsmStatusDlg *dlg=0, CaplInstance *pComplectation = NULL,
							bool (*IsNoDisasemblyItem)(CaplInstance *pdf)=0)
{
	if(prd_mgr==0)return false;
	if(m_data==0)return false;
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(prd_mgr->m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}

	int iUse = 0;
	if(!prd_mgr->m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("kvz\\VARIABLES\\m_bUseParentsRel"),iUse))
		iUse = 0;

	// Чтение из базы
	if((m_data->IsConnected())&&(pdf->GetId()!=0))
	{
		// чтение из базы
		CaplLoadData ld(m_data,DEF_SOURCE);
		int i1,i2,i3,i27,i28;
		i1=	ld.AddQuery(_T('b'), pdf->GetId(), prd_mgr->e_apl_qacu, prd_mgr->a_pdr_r_ting, true,true);
		
		if (iUse!=0)
			i3 = ld.AddQuery(_T('d'), i1, 0, prd_mgr->a_pdr_parent_reference, true, true);
			/*
			ld.AddQuery(_T('d'), i1, 0, prd_mgr->a_pdr_r_ting, true);
			ld.AddQuery(_T('d'), i1, 0, prd_mgr->a_pdr_r_ted, true);
			ld.AddQuery(_T('d'), i1, 0, prd_mgr->a_pdr_frames_of_reference, true);
			ld.AddQuery(_T('d'), i1, 0, prd_mgr->a_pdr_id, true);
			ld.AddQuery(_T('d'), i1, 0, prd_mgr->a_apl_qacu_value, true);
			ld.AddQuery(_T('d'), i1, 0, prd_mgr->a_apl_qacu_unit, true);
			*/

			if((time!=0)||(sn!=0))
			{
				// чтение effectivity
				i2=ld.AddQuery(_T('r'), i1, prd_mgr->e_pd_eff, prd_mgr->a_pde_usage, true,true);
				if (iUse!=0)
					i2=ld.AddQuery(_T('r'), i3, prd_mgr->e_pd_eff, prd_mgr->a_pde_usage, true,true);
				/*
					ld.AddQuery(_T('d'), i2, 0, prd_mgr->a_pde_usage, true);
					ld.AddQuery(_T('d'), i2, 0, prd_mgr->a_pde_id, true);
					ld.AddQuery(_T('d'), i2, 0, prd_mgr->a_sn_eff_start, true);
					ld.AddQuery(_T('d'), i2, 0, prd_mgr->a_sn_eff_end, true);
					ld.AddQuery(_T('d'), i2, 0, prd_mgr->a_dat_eff_start_s, true);
					ld.AddQuery(_T('d'), i2, 0, prd_mgr->a_dat_eff_end_s, true);
					*/
			}
			if(pComplectation!=0)
			{
				i27=ld.AddQuery(_T('r'), i1, prd_mgr->e_rule_rels, prd_mgr->a_rule_rels_item, true,true);
					i28=ld.AddQuery(_T('d'), i27, 0, prd_mgr->a_rule_rels_rule, true,true);
			}
			
		if (!ld.LoadEx())
		{
			if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
				if(prd_mgr->m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
			}
		}
	}
	if(dlg!=0)
	{
		CString buf; buf.Format(_T("%i"),parts.Size);
		dlg->m_count.SetWindowText(buf);
	}

	// Разбор данных
	int i;
	CaplInstance *inst;
	bool has_subitem=false;
	aplExtent ext_acu,ext_acu_in,ext_acu_out;
	m_data->GetEntityExtent(prd_mgr->e_acu,ext_acu);
	for(i=0;i<ext_acu.Size;i++)
	{
		m_data->GetAttr(ext_acu[i],prd_mgr->a_pdr_r_ting,inst);
		if(inst!=pdf) continue;
		
		if(context!=0)
		{
			if(!prd_mgr->IsItemInContext(ext_acu[i],context,prd_mgr->a_pdr_frames_of_reference)) continue;
		}
		ext_acu_in.Add(ext_acu[i]);
	}

	if(sn!=0)
	{ 
		if(prd_mgr->FilterlBySN(ext_acu_in,sn,ext_acu_out))
		{ext_acu_in.Clear();ext_acu_in.Append(ext_acu_out);}

	}

	if(time!=0)
	{ 
		if(prd_mgr->FilterlByDate(ext_acu_in,*time,ext_acu_out))
			{ext_acu_in.Clear();ext_acu_in.Append(ext_acu_out);}
	}

	if (pComplectation != NULL)
	{
		if (funcFilterByAppOrComplectation == NULL)
		{
#ifdef _DEBUG
			CString strLibFileName = CString(_T("aplConfiguratorMgrD.dll"));
#else
			CString strLibFileName = CString(_T("aplConfiguratorMgr.dll"));
#endif

			HINSTANCE hConfigMgrLib = AfxLoadLibrary(strLibFileName);

			if (hConfigMgrLib != NULL)
				(FARPROC&)funcFilterByAppOrComplectation = ::GetProcAddress(hConfigMgrLib, "add_BasisAndComplectationFilter");		
		}

		if ((funcFilterByAppOrComplectation != NULL) && (funcFilterByAppOrComplectation(prd_mgr->m_api, ext_acu_in, pComplectation, ext_acu_out, false,0)))
		{
			ext_acu_in.Clear();
			ext_acu_in.Append(ext_acu_out);
		}
	}

	for(i=0;i<ext_acu_in.Size;i++)
	{
		has_subitem=true;
		
		m_data->GetAttr(ext_acu_in[i],prd_mgr->a_pdr_r_ted,inst);
		CaplDisAssemblyElement *el= new CaplDisAssemblyElement;
		el->pdf=inst;
		el->parent=my_part;
		m_data->GetAttr(ext_acu_in[i],prd_mgr->a_apl_qacu_value,el->count);
		m_data->GetAttr(ext_acu_in[i],prd_mgr->a_apl_qacu_unit,el->unit);
		bool found=false;
		for(int j=0;j<parts.Size;j++)
		{
			if(parts[j]->pdf==inst)
			{
				if(parts[j]->unit==el->unit)
				{
					found=true;
					parts[j]->elements.Add(el);
					break;
				}
			}
		}
		if(!found)
		{
			CaplDisAssemblyPart *part=new CaplDisAssemblyPart;
			part->pdf=inst;
			part->unit=el->unit;
			part->elements.Add(el);
			parts.Add(part);
			bool bNoDisasembly=false;
			if(0!=IsNoDisasemblyItem) bNoDisasembly= IsNoDisasemblyItem(inst);
			if(!bNoDisasembly) GetFullProductContentsEx(prd_mgr, m_data, inst, parts, part, context, time, sn, dlg, pComplectation,IsNoDisasemblyItem);
		}
	}
	if(has_subitem)	{ if(my_part) my_part->has_subitem=true;}
	return true;
}
bool GetFullProductContentsEx(CaplAPI *m_api,aplExtent &ext_parent,aplRealArray &count_parent,
							  aplExtent &ext_rel_out,aplExtent &ext_out,
							  aplRealArray &count_out,aplExtent &ext_unit_out,CaplInstance *context=0,CDisAsmStatusDlg *dlg=0,const TCHAR *filter_date=0,const TCHAR *filter_sn=0,CStringArray *not_disas_types=0,CStringArray *not_disas_sources=0, CaplInstance *pComplectation = NULL)
{
	// Чтение из базы

	int iUse = 0;
	if(!m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("kvz\\VARIABLES\\m_bUseParentsRel"),iUse))
		iUse = 0;

	int i;
	CString buf; 
	if(m_api->m_data.IsConnected())
	{
		CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
		int l_count=0;
		int i1,i2,i8,i12, i3;
		bool b_load=false;
		for(i=0;i<ext_parent.GetSize();i++)
		{
			if(m_api->m_prd_mgr.m_bContinue)
			{
				if(*(m_api->m_prd_mgr.m_bContinue)==false) break;
			}
			if(ext_parent[i]) 
				if(ext_parent[i]->GetId()) 
					if(ext_parent[i]->GetAccessmode()<aplNO) 
					{
						ld.AddQuery(0,ext_parent[i],true);
						l_count++;
						b_load=true;
					}

			if((l_count==m_api->m_prd_mgr.m_MaxItemsLoad || i==ext_parent.GetSize()-1) && b_load)
			{
				i1=ld.AddQuery(_T('r'), 0, m_api->m_prd_mgr.e_acu, m_api->m_prd_mgr.a_pdr_r_ting, true,true);
				if (iUse!=0)
					i3 = ld.AddQuery(_T('d'), i1, 0, m_api->m_prd_mgr.a_pdr_parent_reference, true, true);
				i8=	ld.AddQuery(_T('d'), i1, 0, m_api->m_prd_mgr.a_pdr_r_ted, true,true);
				i12=ld.AddQuery(_T('d'), i8, 0, m_api->m_prd_mgr.a_pdf_prd, true,true);
				if((filter_date!=0)||(filter_sn!=0))
				{
					// чтение effectivity
					i2=ld.AddQuery(_T('r'), i1, m_api->m_prd_mgr.e_pd_eff, m_api->m_prd_mgr.a_pde_usage, true,true);
					if (iUse!=0)
						i2=ld.AddQuery(_T('r'), i3, m_api->m_prd_mgr.e_pd_eff, m_api->m_prd_mgr.a_pde_usage, true,true);
				}
				if (!ld.LoadEx())
				{
					if(m_api->m_data.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
						if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
					}
				}
				if(dlg!=0)
				{
					buf.Format(_T("%i"),ext_rel_out.GetSize()+i);
					dlg->m_count.SetWindowText(buf);
				}
				l_count=0;
				b_load=false;
			}
		}
	}
	if(m_api->m_prd_mgr.m_bContinue)
	{
		if(*(m_api->m_prd_mgr.m_bContinue)==false) return false;
	}
	aplExtent ext_acu;
	CaplInstance *r_ted_inst,*inst;
	double val;
	m_api->m_data.GetEntityExtent(m_api->m_prd_mgr.e_acu,ext_acu);
	aplExtent ext_new_parent;
	aplRealArray new_count_parent;
	int map_size=1000;
	if(ext_rel_out.GetSize()>map_size) map_size=ext_rel_out.GetSize();
	CaplMap map(map_size);
	for(i=0;i<ext_rel_out.GetSize();i++)
	{
		if(m_api->m_prd_mgr.m_bContinue)
		{
			if(*(m_api->m_prd_mgr.m_bContinue)==false) break;
		}

		map.Add((long)ext_rel_out[i],long(i));
	}
	if(m_api->m_prd_mgr.m_bContinue)
	{
		if(*(m_api->m_prd_mgr.m_bContinue)==false) return false;
	}
	map.SortIn();
	map.bAutoSort=true;
	CaplMap p_map(ext_parent.GetSize());
	for(i=0;i<ext_parent.GetSize();i++)
	{
		p_map.Add((long)ext_parent[i],long(i));
	}
	p_map.SortIn();
	COleDateTime filter_dt;
	filter_dt.SetStatus(COleDateTime::invalid);
	if(filter_date)	
	{
		buf=filter_date;
		if(buf!=_T(""))	aplString2Date(buf,filter_dt);
	}

	aplExtent ext_acu_pr, ext_acu_fl;

	for(i=0;i<ext_acu.GetSize();i++)
	{
		if(m_api->m_prd_mgr.m_bContinue)
		{
			if(*(m_api->m_prd_mgr.m_bContinue)==false) break;
		}
		if(ext_acu[i]->GetType()==0) 
			continue;

		m_api->m_data.GetAttr(ext_acu[i],m_api->m_prd_mgr.a_pdr_r_ting,inst);
		if(!inst) continue;

		if(not_disas_types || not_disas_sources)
		{
			CString type=_T(""),source=_T("");//не разузловываемые типы и источники
			m_api->m_data.GetAttr(inst,m_api->m_prd_mgr.a_apl_pdf_type,type);
			m_api->m_data.GetAttr(inst,m_api->m_prd_mgr.a_pdfwss_source,source);
			bool bFoundType=false;
			if(not_disas_types)
			{
				for(int k=0;k<not_disas_types->GetSize();k++)
				{
					if(not_disas_types->GetAt(k)==type)
					{
						bFoundType=true;break;
					}
				}
			}
			bool bFoundSource=false;
			if(not_disas_sources)
			{
				for(int k=0;k<not_disas_sources->GetSize();k++)
				{
					if(not_disas_sources->GetAt(k)==source)
					{
						bFoundSource=true;break;
					}
				}
			}
			if(bFoundType || bFoundSource)
			{
				continue;
			}
		}

		int num=p_map.QFindByIn((long)inst);
		if(num>-1)
		{
			if(context)
				if(!m_api->m_prd_mgr.IsItemInContext(ext_acu[i],context)) continue;
			aplExtent ext,ext0;
			ext.Add(ext_acu[i]);

			ext_acu_pr.Add(ext_acu[i]);
		}
	}

	aplExtent ext,ext0,ext1,ext2;
	if(filter_date && filter_dt.GetStatus()==COleDateTime::valid)
		m_api->m_prd_mgr.FilterlByDate(ext_acu_pr, filter_dt, ext0);
	else
		ext0.Append(ext_acu_pr);

	if(filter_sn)
	{
		buf=filter_sn;
		if(buf!=_T(""))
			m_api->m_prd_mgr.FilterlBySN(ext0, buf, ext1);
		else
			ext1.Append(ext0);
	}
	else
		ext1.Append(ext0);

	if (pComplectation != NULL)
	{
		if (funcFilterByAppOrComplectation == NULL)
		{
#ifdef _DEBUG
			CString strLibFileName = CString(_T("aplConfiguratorMgrD.dll"));
#else
			CString strLibFileName = CString(_T("aplConfiguratorMgr.dll"));
#endif

			HINSTANCE hConfigMgrLib = AfxLoadLibrary(strLibFileName);

			if (hConfigMgrLib != NULL)
				(FARPROC&)funcFilterByAppOrComplectation = ::GetProcAddress(hConfigMgrLib, "add_BasisAndComplectationFilter");		
		}

		if (funcFilterByAppOrComplectation != NULL)
			funcFilterByAppOrComplectation(m_api, ext1, pComplectation, ext_acu_fl, false,0);
	}
	else
		ext_acu_fl.Append(ext1);
		
	for(i=0;i<ext_acu_fl.GetSize();i++)
	{
		m_api->m_data.GetAttr(ext_acu_fl[i],m_api->m_prd_mgr.a_pdr_r_ting,inst);
		if(!inst) continue;

		int num=p_map.QFindByIn((long)inst);
		if(num>-1)
		{
			m_api->m_data.GetAttr(ext_acu_fl[i],m_api->m_prd_mgr.a_pdr_r_ted,r_ted_inst);
			if(r_ted_inst==0) continue;
			m_api->m_data.GetAttr(ext_acu_fl[i],m_api->m_prd_mgr.a_apl_qacu_value,val);

			val*=count_parent[p_map[num].out];
			int parent_num=ext_new_parent.Find(r_ted_inst);//для уникальности родительских pdf одного уровня
			if(parent_num>-1)
			{
				new_count_parent[parent_num]+=val;
			}
			else
			{
				ext_new_parent.Add(r_ted_inst);
				new_count_parent.Add(val);
			}
								
			int rel_num=map.QFindByIn((long)ext_acu_fl[i]);//если такая связь уже есть, суммируем колво входящих деталей для одинаковых связей
			if(rel_num>-1)
			{
				count_out[map[rel_num].out]+=val;
			}
			else
			{
				num=ext_rel_out.Add(ext_acu_fl[i]);
				map.Add((long)ext_acu_fl[i],(long)num);
				ext_out.Add(r_ted_inst);
				count_out.Add(val);	
				m_api->m_data.GetAttr(ext_acu_fl[i],m_api->m_prd_mgr.a_apl_qacu_unit,inst);
				ext_unit_out.Add(inst);
			}
		}
	}
	if(m_api->m_prd_mgr.m_bContinue)
	{
		if(*(m_api->m_prd_mgr.m_bContinue)==false) return false;
	}
	if(ext_new_parent.GetSize()) GetFullProductContentsEx(m_api,ext_new_parent,new_count_parent,
							  ext_rel_out,ext_out,count_out,ext_unit_out,context,dlg,filter_date,filter_sn,not_disas_types,not_disas_sources, pComplectation);
	return true;
}
//*************************************************************
bool CaplProductManager::DisassemblyProduct(CaplInstance *ci, CaplInstance *context, CaplInstance *pdf, 
		aplInstArray &ext_pdf, aplRealArray &count_array, aplInstArray &ext_unit, bool ReturnOnlyPart, CaplInstance *pComplectation)
{
	return DisassemblyProductEx(ci, context, pdf, 
		ext_pdf, count_array, ext_unit,0,0, ReturnOnlyPart, pComplectation);
}
bool CaplProductManager::DisassemblyProduct(CaplInstance *context,CaplInstance *pdf, 
		aplExtent &ext_rel,aplExtent &ext_out, aplRealArray &count_array, aplExtent &ext_unit,const TCHAR *filter_date,const TCHAR *filter_sn, bool ReturnOnlyPart,CStringArray *not_disas_types,CStringArray *not_disas_sources, CaplInstance *pComplectation)
{
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(pdf->GetAccessmode()>aplRO) {
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight());
		return false;
	}
	ext_rel.Clear();
	ext_out.Clear();
	ext_out.Unique=false;
	count_array.RemoveAll();
	ext_unit.Clear();
	ext_unit.Unique=false;
	aplExtent ext;
	aplRealArray count_parent;
	ext.Add(pdf);
	count_parent.Add(1);

	CaplSetResourceHandle setres(module_inst);

	CDisAsmStatusDlg dlg;
	dlg.Create(IDD_DISASM_STATUS);
	dlg.ShowWindow(TRUE);

	aplExtent ext_all_rel;
	aplExtent ext_all_out;
	ext_all_out.Unique=false;
	aplExtent ext_all_unit;
	ext_all_unit.Unique=false;
	aplRealArray count_all_array;
	GetFullProductContentsEx(m_api,ext,count_parent,ext_all_rel,ext_all_out,count_all_array,ext_all_unit,context,&dlg,filter_date,filter_sn,not_disas_types,not_disas_sources, pComplectation);
	
	if(ReturnOnlyPart)
	{
		for(int i=0;i<ext_all_rel.GetSize();i++)
		{
			CaplInstance *rel_ed,*rel_ing;
			m_api->m_data.GetAttr(ext_all_rel[i],m_api->m_prd_mgr.a_pdr_r_ted,rel_ed);
			bool f_has_content=false;
			for(int j=0;j<ext_all_rel.GetSize();j++)
			{
				if(ext_all_rel[i]==ext_all_rel[j]) continue;
				m_api->m_data.GetAttr(ext_all_rel[j],m_api->m_prd_mgr.a_pdr_r_ting,rel_ing);
				if(rel_ing==rel_ed) {f_has_content=true;break;}
			}
			if(!f_has_content)
			{
				ext_rel.Add(ext_all_rel[i]);
				ext_out.Add(ext_all_out[i]);
				count_array.Add(count_all_array[i]);
				ext_unit.Add(ext_all_unit[i]);
			}
		}
	}
	else
	{
		ext_rel.Append(ext_all_rel);
		ext_out.Append(ext_all_out);
		count_array.Append(count_all_array);
		ext_unit.Append(ext_all_unit);
	}
	
	dlg.ShowWindow(FALSE);
	return true;
	
}
//*************************************************************
bool CaplProductManager::DisassemblyProductEx(CaplInstance *ci, CaplInstance *context,	CaplInstance *pdf, 
		aplInstArray &ext_pdf, aplRealArray &count_array, aplInstArray &ext_unit,
		COleDateTime *time, const TCHAR *sn, bool ReturnOnlyPart, CaplInstance *pComplectation,
		bool (*IsNoDisasemblyItem)(CaplInstance *pdf))
{
	ext_pdf.Clear();
	//count_array.Clear();
	count_array.RemoveAll();
	ext_unit.Clear();

	if(m_data==0) return false;
	if(e_apl_qacu==0) return false;
	if(e_prd==0) return false;
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(pdf->GetType()==0) return false;

	TCaplDisAssemblyParts parts;
	aplExtent ext0 ;
	int i,j;

	CaplSetResourceHandle setres(module_inst);

	CDisAsmStatusDlg dlg;
	dlg.Create(IDD_DISASM_STATUS);
	if(m_api->m_ModeInteractive)
		dlg.ShowWindow(SW_SHOW);

	GetFullProductContentsEx(this, m_data, pdf, parts, 0, context, time, sn, &dlg, pComplectation,IsNoDisasemblyItem);

	dlg.m_count.SetWindowText(_T(""));
	dlg.m_name.SetWindowText( APL_T("Чтение данных ..."));
	
	CaplLoadData ld_pdf(m_data,DEF_SOURCE);
	bool b_load=false;

	for(i=0;i<parts.Size;i++)
	{
		if(parts[i]->has_subitem==false)
		{
			parts[i]->count=GetPartsCount(parts[i]);
			if(ReturnOnlyPart==true){ ld_pdf.AddQuery(0,parts[i]->pdf,true);b_load=true;}
		}
		if(ReturnOnlyPart==false) {ld_pdf.AddQuery(0,parts[i]->pdf,true); b_load=true;}
	}
	// Чтение из базы
	if(m_data->IsConnected() && b_load)
	{
		/*
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_id, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_descr, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_apl_pdf_unit, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_code, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_code1, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_code2, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_apl_pdf_type, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_apl_pdf_standard, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdfwss_source, true);
			*/
		j=	ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_prd, true,true);
		/*
			ld_pdf.AddQuery(_T('d'), j, 0, a_prd_id, true);
			ld_pdf.AddQuery(_T('d'), j, 0, a_prd_name, true);
			ld_pdf.AddQuery(_T('d'), j, 0, a_prd_descr, true);
			ld_pdf.AddQuery(_T('d'), j, 0, a_prd_code, true);
			*/
		if (!ld_pdf.LoadEx())
		{
			if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
				if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
			}
		}
	}
	for(i=0;i<parts.Size;i++)
	{
		bool f=true;
		if(ReturnOnlyPart==true)
		{
			if(parts[i]->has_subitem!=false) f=false;
		}
		if(f)
		{
			ext_pdf.Add(parts[i]->pdf);
			count_array.Add(parts[i]->count);
			ext_unit.Add(parts[i]->unit);
		}
	}

	if(m_api->m_ModeInteractive)
		dlg.ShowWindow(SW_HIDE);
	return true;
}

//*************************************************************
bool CaplProductManager::DisassemblyProductEx2(CaplInstance *ci, CaplInstance *context,	CaplInstance *pdf, 
		aplInstArray &ext_pdf, aplRealArray &count_array, aplInstArray &ext_unit,
		COleDateTime *time, const TCHAR *sn, bool ReturnOnlyPart, CaplInstance *pComplectation,
		bool (*IsNoDisasemblyItem)(CaplInstance *pdf))
{
	ext_pdf.Clear();
	//count_array.Clear();
	count_array.RemoveAll();
	ext_unit.Clear();

	if(m_data==0) return false;
	if(e_apl_qacu==0) return false;
	if(e_prd==0) return false;
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(pdf->GetType()==0) return false;

	TCaplDisAssemblyParts parts;
	aplExtent ext0 ;
	int i,j;

	CaplSetResourceHandle setres(module_inst);

	CDisAsmStatusDlg dlg;
	dlg.Create(IDD_DISASM_STATUS);
	if(m_api->m_ModeInteractive)
		dlg.ShowWindow(SW_SHOW);

	//GetFullProductContentsEx(this, m_data, pdf, parts, 0, context, time, sn, &dlg, pComplectation,IsNoDisasemblyItem);


	/*CaplLoadData ld(&(m_api->m_data),DEF_SOURCE);
	for (i=0;i <ext_base_pi.GetSize();i++) ld.AddQuery(0,ext_base_pi[i]);
	for (i=0,j=0; i <100;i++) // Считаем что иерархия максимум 100 уровней
	{
		j=ld.AddQuery(_T('r'),j,m_api->m_prd_inst_mgr.e_apl_component,m_api->m_prd_inst_mgr.a_prd_inst_rel_related,true,true);
		j=ld.AddQuery(_T('d'),j,m_api->m_prd_inst_mgr.e_apl_component,m_api->m_prd_inst_mgr.a_prd_inst_rel_relating,true,true);
		int k=ld.AddQuery(_T('d'),j,m_api->m_prd_inst_mgr.e_apl_component,m_api->m_prd_inst_mgr.a_prd_inst_pdf,true,true);
		ld.AddQuery(_T('d'),k,m_api->m_prd_mgr.e_pdf,m_api->m_prd_mgr.a_pdf_prd,true,true);
	}
	ld.LoadEx(true,&ext_comp_rel,APL_T("Определение нахождения"));*/

	CaplLoadData ld_struct(m_data,DEF_SOURCE);
	int k=ld_struct.AddQuery(0,pdf);
	for(i=0;i<100;i++)
	{
		k=ld_struct.AddQuery(_T('r'),k,m_api->m_prd_mgr.e_pdr,m_api->m_prd_mgr.a_pdr_r_ting,true,true);
		k=ld_struct.AddQuery(_T('d'),k,m_api->m_prd_mgr.e_pdr,m_api->m_prd_mgr.a_pdr_r_ted,true,true);
	}

	DWORD t0=GetTickCount();
	ld_struct.LoadEx(true,0,APL_T("Чтение структуры"));

	DWORD t1=GetTickCount()-t0;



	dlg.m_count.SetWindowText(_T(""));
	dlg.m_name.SetWindowText( APL_T("Чтение данных ..."));
	
	CaplLoadData ld_pdf(m_data,DEF_SOURCE);
	bool b_load=false;

	for(i=0;i<parts.Size;i++)
	{
		if(parts[i]->has_subitem==false)
		{
			parts[i]->count=GetPartsCount(parts[i]);
			if(ReturnOnlyPart==true){ ld_pdf.AddQuery(0,parts[i]->pdf,true);b_load=true;}
		}
		if(ReturnOnlyPart==false) {ld_pdf.AddQuery(0,parts[i]->pdf,true); b_load=true;}
	}
	// Чтение из базы
	if(m_data->IsConnected() && b_load)
	{
		/*
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_id, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_descr, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_apl_pdf_unit, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_code, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_code1, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_code2, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_apl_pdf_type, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_apl_pdf_standard, true);
			ld_pdf.AddQuery(_T('d'), 0, 0, a_pdfwss_source, true);
			*/
		j=	ld_pdf.AddQuery(_T('d'), 0, 0, a_pdf_prd, true,true);
		/*
			ld_pdf.AddQuery(_T('d'), j, 0, a_prd_id, true);
			ld_pdf.AddQuery(_T('d'), j, 0, a_prd_name, true);
			ld_pdf.AddQuery(_T('d'), j, 0, a_prd_descr, true);
			ld_pdf.AddQuery(_T('d'), j, 0, a_prd_code, true);
			*/
		if (!ld_pdf.LoadEx())
		{
			if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
				if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
			}
		}
	}
	for(i=0;i<parts.Size;i++)
	{
		bool f=true;
		if(ReturnOnlyPart==true)
		{
			if(parts[i]->has_subitem!=false) f=false;
		}
		if(f)
		{
			ext_pdf.Add(parts[i]->pdf);
			count_array.Add(parts[i]->count);
			ext_unit.Add(parts[i]->unit);
		}
	}

	if(m_api->m_ModeInteractive)
		dlg.ShowWindow(SW_HIDE);
	return true;
}

//*************************************************************
bool CaplProductManager::StartEffectivityManager(CaplInstance *ci, CaplInstance *pdf, CaplInstance *context, CaplEntity *rel)
{
	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(pdf->GetType()==0) return false;
	if(pdf->GetAccessmode()>aplRO)
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight());
		return 0;
	}
	if(rel==0) return false;
	aplExtent ext0, ext2;
	LoadAllSubProduct(0,0,pdf,ext0, ext2);

	CaplSetResourceHandle setres(module_inst);
	
	CManagerEffGanttDlg dlg;
	dlg.m_api=m_api;
	dlg.m_pdf=pdf;
	dlg.m_rel=rel;
	int nResponse = dlg.DoModal();
	/*
	CManagerEffectivityDlg dlg;
	dlg.m_api=m_api;
	dlg.m_counterCom=0;
	dlg.m_pdf=pdf;
	dlg.m_rel=rel;
	int nResponse = dlg.DoModal();
	*/

	return true;
}
//*************************************************************
bool CaplProductManager::StartCompareProduct(aplExtent &exp_pdf)
{
	CaplSetResourceHandle setres(module_inst);

	CProductCompare dlg;
	dlg.inExt.Append(exp_pdf);
	dlg.m_api=m_api;
	dlg.DoModal();
	return true;
}
//*************************************************************
bool CaplProductManager::DeleteProductWithAllVersion(CaplInstance *prd, bool recursive)
{
	aplExtent ext0, ext_rel, ext_pdf1, ext_rel1;
	CaplInstance *i_rel=0;
	int i,j;
	if(prd==0) return false;
	if(prd==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(prd->GetType()==0) return false;
	if(!m_data->IsKindOf(prd,e_prd)) return false;
	if(prd->GetAccessmode()!=aplOWN) 
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight());
		return false;
	}
	GetAllProductVersion(prd,ext0);
	for(i=0;i<ext0.GetSize();i++){
		if(ext0[i]->GetAccessmode()!=aplOWN) 
		{
			if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight());
			return false;
		}
		//Определяем число вхождений в изделия сборку
		WhereUsedProduct(ext0[i],ext_rel,ext_pdf1);

		if(ext_pdf1.GetSize()>1)/* return ;*/ // используется многократно
		{
			if(!m_api->m_ModeInteractive) return false;
			if(AfxMessageBox( APL_T("Эта версия используется неоднократно !!!\n\nВcе равно ее удалить  ?"),
				MB_YESNO|MB_ICONQUESTION)!=IDYES) return false;
		}
	}
	for(i=0;i<ext0.GetSize();i++){
		//Удаление Product	
		LoadAllSubProduct(0,0,ext0[i],ext_rel1, ext_pdf1);
		
		for(j=0;j<ext_rel1.GetSize();j++)
		{
			if(ext_rel1[j]->GetType()==0) continue;
			m_data->GetAttr(ext_rel1[j], a_pdr_r_ted,i_rel);
			if(recursive==true)
				DeleteProductVersion(i_rel, true);
			if(ext_rel1[j]->GetType()==0) continue;
			m_data->DeleteInstance(ext_rel1[j]);
		}
		
		for(j=0;j<ext_rel.GetSize();j++)
		{
			if(ext_rel[j]->GetType()==0) continue;
			m_data->DeleteInstance(ext_rel[j]);
		}
		
		//Удаление Product Definition Formation	
		//удалим ассоциации со справочником
		m_api->m_classifier_mgr.DeleteClassifierAssociation(ext0[i],0);
		// удаляем статусы и характеристики объекта
		m_api->m_appr_mgr.DeleteAllApproval(ext0[i]);
		m_api->m_charact_mgr.DeleteAllAssociatedCharacteristic(ext0[i]);
		
		m_data->DeleteInstance(ext0[i]);
	}		
	//удалим ассоциации со справочником
	m_api->m_classifier_mgr.DeleteClassifierAssociation(prd,0);
	// удаляем статусы и характеристики объекта
	m_api->m_appr_mgr.DeleteAllApproval(prd);
	m_api->m_charact_mgr.DeleteAllAssociatedCharacteristic(prd);
	
	m_data->DeleteInstance(prd);
	return true;
}
//*************************************************************
bool CaplProductManager::DeleteProductVersion(CaplInstance *pdf, bool recursive)
{
	aplExtent ext0, ext_rel, ext_pdf1, ext_rel1;
	CaplInstance *prd=0, *pdfor=0, *prod=0, * i_rel=0;
	
	int i=0, size=0;

	if(pdf==0) return false;
	if(pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(pdf->GetType()==0) return false;
	if(!m_data->IsKindOf(pdf,e_pdf)) return false;

	if(pdf->GetAccessmode()!=aplOWN) 
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight());
		return false;
	}

	m_data->GetAttr(pdf,a_pdf_prd,prd);
	//Определяем число вхождений в изделия сборку
	WhereUsedProduct(pdf,ext_rel,ext_pdf1);

	if(ext_pdf1.GetSize()>1)/* return ;*/ // используется многократно
	{
		if(!m_api->m_ModeInteractive) return false;
		if(AfxMessageBox( APL_T("Эта версия используется неоднократно !!!\n\nВcе равно ее удалить  ?"),
			MB_YESNO|MB_ICONQUESTION)!=IDYES) return false;
	}
	aplExtent ext_prd_ver,ext_eff;
	CaplAttrValue tst_value[1];

	tst_value[0].value.Set(prd);
	tst_value[0].attr=a_pdf_prd;;
	m_data->NET_FindInstancesWithAttrValues(e_pdf,1,&tst_value[0],ext_prd_ver,false);

	if(ext_prd_ver.Size>1)
		prd=0;
	else
	{
		if(m_api->m_ModeInteractive==true)
		{
			if(AfxMessageBox( APL_T("Эта версия единственная.\n\nУдалить вместе с ней описание изделия ?"),
				MB_YESNO|MB_ICONQUESTION)!=IDYES)
				prd=0;
		}
	}
		
	if(prd!=0) 
	{
		if(prd->GetAccessmode()!=aplOWN) 
		{
			if(m_api->m_ModeInteractive)aplErrorMessage( APL_T("Недостаточно прав для удаления изделия !"));
			return false;
		}
	}
	//Удаление Product	
	LoadAllSubProduct(0,0,pdf,ext_rel1, ext_pdf1);

	for(i=0;i<ext_rel1.GetSize();i++)
	{
		if(ext_rel1[i]->GetType()==0) continue;
		m_data->GetAttr(ext_rel1[i], a_pdr_r_ted,i_rel);
		if(recursive==true)
			DeleteProductVersion(i_rel, true);
		if(ext_rel1[i]->GetType()==0) continue;
		// применяемости!
		FindAllPDFEffectiviti(ext_rel1[i],ext_eff);
		for(int k=0;k<ext_eff.GetSize();k++){
			m_data->DeleteInstance(ext_eff[k]);
		}
		
		m_data->DeleteInstance(ext_rel1[i]);
	}

	for(i=0;i<ext_rel.GetSize();i++)
	{
		if(ext_rel[i]->GetType()==0) continue;
		m_data->DeleteInstance(ext_rel[i]);
	}
	
	//Удаление Product Definition Formation	
	if(pdf!=0){
		//удалим ассоциации со справочником
		m_api->m_classifier_mgr.DeleteClassifierAssociation(pdf,0);
		// удаляем статусы и характеристики объекта
		m_api->m_appr_mgr.DeleteAllApproval(pdf);
		m_api->m_charact_mgr.DeleteAllAssociatedCharacteristic(pdf);
		
		m_data->DeleteInstance(pdf);
	}

	if(prd!=0) 
	{
		//удалим ассоциации со справочником
		m_api->m_classifier_mgr.DeleteClassifierAssociation(prd,0);
		// удаляем статусы и характеристики объекта
		m_api->m_appr_mgr.DeleteAllApproval(prd);
		m_api->m_charact_mgr.DeleteAllAssociatedCharacteristic(prd);
	
		m_data->DeleteInstance(prd);
	}
	return true;
}
//*************************************************************
bool CaplProductManager::LoadAssortment()
{	
	if(m_data==0) return false;
	if(e_prd==0) return false;

	if(!m_data->IsConnected()) return true;

	CaplLoadData ld(m_data,DEF_SOURCE);
		
	ld.AddQuery(_T('e'), 0, e_assortment, 0, true,true);
	ld.AddQuery(_T('e'), 0, e_assortment_shape, 0, true,true);
	if(!ld.LoadEx(true,0, APL_T("Чтение сортамента")))
	{
		if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
			if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
		}
		return false;
	}
	return true;
}
//*************************************************************
bool CaplProductManager::ChangeMkState(CaplInstance *pdf)
{
	if(0 == pdf) return false;
	if(m_api==0) return false;
	if(m_data==0) return false;
	
	aplExtent pdfs;
	pdfs.Add(pdf);

	return ChangeMkState(pdfs);
}
//*************************************************************
bool CaplProductManager::ChangeMkState(aplExtent &pdfs)
{
	if(m_api==0) return false;
	if(m_data==0) return false;
	if(e_prd==0) return false;
	if(pdfs.Size==0) return false;

	CString mkState, prevMkState;
	for(int i=0; i<pdfs.Size; ++i)
	{
		m_api->m_data.GetAttr(pdfs[i], a_apl_pdf_additional_data, mkState);
		if(0 == i)
		{
			prevMkState = mkState;
		}
		else
		{
			if(prevMkState != mkState)
			{
				if(m_api->m_ModeInteractive == true)
					AfxMessageBox(APL_T("Для совершения операции изделия должны иметь одинаковое состояние!"), MB_ICONERROR);

				return false;
			}
		}
	}

	CaplSetResourceHandle setres(module_inst);
	CChangeMkStateDlg dlg(m_api, pdfs);
	
	return (dlg.DoModal() == IDOK);
}
//*************************************************************

bool CaplProductManager::LoadPrdAssortment(CaplInstance *prd, aplExtent &out_ext)
{
	out_ext.Clear();
	if(m_data==0) return false;
	if(prd==0) return false;
	if(prd==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(prd->GetType()==0) return false;
	if(e_prd==0) return false;

	int i;
	if((m_data->IsConnected())&&(prd->GetId()!=0))
	{
		// чтение из базы
		CaplLoadData ld(m_data,DEF_SOURCE);
		i=	ld.AddQuery(_T('b'), prd->GetId(), e_prd_assortment, a_prd_assortment_prd, true,true);
		if(!ld.LoadEx())
		{
			if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
				if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
			}
		}
	}
	aplExtent ext;
	CaplInstance *inst;
	m_data->GetEntityExtent(e_prd_assortment,ext);
	for(i=0;i<ext.Size;i++)
	{
		m_data->GetAttr(ext[i],a_prd_assortment_prd,inst);
		if(inst!=prd) continue;
		m_data->GetAttr(ext[i],a_prd_assortment_assort,inst);
		if(inst!=0) out_ext.Add(inst);
	}
	return true;
}
//*************************************************************
const TCHAR *CaplProductManager::StrConvertPdfType2Rus(const TCHAR *type)
{
	if(type==0) return 0;
	CString type_rus=type;
	if(type_rus==_T("assembly")) return  APL_T("Сборочная единица");
	else if(type_rus==_T("material")) return  APL_T("Материал");
	else if(type_rus==_T("kit")) return  APL_T("Комплект");
	else if(type_rus==_T("komplex")) return  APL_T("Комплекс");
	else if(type_rus==_T("zone")) return  APL_T("Зона");
	else if(type_rus==_T("module"))return  APL_T("Программный модуль");
	else if(type_rus==_T("system"))return  APL_T("Система");
	else if(type_rus==_T("other"))return  APL_T("Прочее");
	else return  APL_T("Деталь");
}

const TCHAR *CaplProductManager::StrConvertRus2PdfType(const TCHAR *type)
{
	if(type==0) return 0;
	
	CString st=type;
	st.MakeLower();
	if (!CaplTranslate::IsNeedTranslate()) // Чтобы без перевода ничего не менялось
	{
		if(st== APL_T("сборочная единица")) return _T("assembly");
		else if(st== APL_T("материал")) return _T("material");
		else if(st== APL_T("комплект")) return _T("kit");
		else if(st== APL_T("комплекс")) return _T("komplex");
		else if(st== APL_T("зона")) return _T("zone");
		else if(st== APL_T("программный модуль")) return _T("module");
		else if(st== APL_T("система")) return _T("system");
		else if(st== APL_T("прочее")) return _T("other");
		return _T("part");
	}

	static CaplStrStrMap map;

	if(0==map.GetSize())
	{
		// Такое извращение нужно чтобы скрестить перевод со сравнением без учёта регистра
		CString buf;
		buf=StrConvertPdfType2Rus(_T("assembly")); buf.MakeLower(); map.Add(buf,_T("assembly"));
		buf=StrConvertPdfType2Rus(_T("material")); buf.MakeLower(); map.Add(buf,_T("material"));
		buf=StrConvertPdfType2Rus(_T("kit"));      buf.MakeLower(); map.Add(buf,_T("kit"));
		buf=StrConvertPdfType2Rus(_T("komplex"));  buf.MakeLower(); map.Add(buf,_T("komplex"));
		buf=StrConvertPdfType2Rus(_T("zone"));     buf.MakeLower(); map.Add(buf,_T("zone"));
		buf=StrConvertPdfType2Rus(_T("module"));   buf.MakeLower(); map.Add(buf,_T("module"));
		buf=StrConvertPdfType2Rus(_T("system"));   buf.MakeLower(); map.Add(buf,_T("system"));
		buf=StrConvertPdfType2Rus(_T("part"));     buf.MakeLower(); map.Add(buf,_T("part"));
		buf=StrConvertPdfType2Rus(_T("other"));     buf.MakeLower(); map.Add(buf,_T("other"));
	}
	int i=map.FindByIn(st);
	if(i>=0) return LPCTSTR(map.GetAt(i)->val); // Если просто вернуть Get, то стррока будет убита при выходе из функции
	return _T("part");
}

//*************************************************************
const TCHAR *CaplProductManager::StrConvertMakeOrBuy2Rus(const TCHAR *src)
{
	if(src==0) return 0;
	CString buf=src;
	buf.MakeLower();
	if(buf==_T("made")) return  APL_T("Изготовляемое");
	else if(buf==_T("bought")) return  APL_T("Покупное");
	else if(buf==_T("coproduction")) return  APL_T("По кооперации");
	else if(buf==_T("assignment")) return  APL_T("Назначается");
	else return  APL_T("Не известно");
}

const TCHAR *CaplProductManager::StrConvertRus2MakeOrBuy(const TCHAR *src)
{
	if(src==0) return 0;
	CString buf=src;
	// с этим не работает первод buf.MakeLower();
	if(buf== APL_T("Изготовляемое")) return _T("made");
	else if(buf== APL_T("Покупное")) return _T("bought");
	else if(buf== APL_T("По кооперации")) return _T("coproduction");
	else if(buf== APL_T("Назначается")) return _T("assignment");
	else return _T("not_known");
}
//*************************************************************

CaplInstance *CaplProductManager::CreatePdfByDot(CaplInstance *item, aplExtent &res)
{
	if(bNoCreateAndChangePDF)
	{
		CaplSetResourceHandle setres(module_inst);

		if(m_api->m_ModeInteractive)AfxMessageBox(IDS_NO_CREATE_PDF,MB_OK|MB_ICONSTOP);

		return 0;
	}
	if(m_data==0) return NULL;
	if(m_api==0) return NULL;
	if(!m_data->IsDictLoad()) return NULL;
	
	CaplSetResourceHandle setres(module_inst);
	CDlg_pdf_dot Dlg;
	Dlg.m_folder = item;
	Dlg.m_api = m_api;
	Dlg.pResult = &res;
	Dlg.DoModal();
	CaplInstance *rez = Dlg.m_rez;
	return rez;
}

//*************************************************************
CaplInstance *CaplProductManager::CreateSubstitute(CaplInstance *pdr, CaplInstance *subst_pdf, CaplInstance *parent_pdf, const TCHAR *id, double count, CaplInstance *unit)
{
	if(!m_api->m_data.IsDictLoad()) return NULL;
	if(pdr==NULL) return NULL;
	if(pdr==(CaplInstance*)-1)
	{
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(subst_pdf==NULL) return NULL;
	if(subst_pdf==(CaplInstance*)-1)
	{
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(subst_pdf->GetType()==NULL) return NULL;

	CaplAttrValue tst_values[4];
	tst_values[0].value.Set(pdr);
	tst_values[0].attr=a_pdf_subst_pdr;
	tst_values[1].value.Set(subst_pdf);
	tst_values[1].attr=a_pdf_subst_pdf;
	tst_values[2].value.Set(parent_pdf);
	tst_values[2].attr=a_pdf_subst_parent_item;
	tst_values[3].value.Set(id);
	tst_values[3].attr=a_pdf_subst_id;
	if(!m_data->TestUniqueAttrValues(e_pdf_subst, NULL, 3, &tst_values[0]))
	{
		if(m_api->m_ModeInteractive)
			AfxMessageBox( APL_T("Связь данных изделий с такой позицией уже есть в базе !!!"),MB_OK|MB_ICONSTOP);
		return NULL;
	}	

	CaplInstance *subst=m_data->CreateInstance(e_pdf_subst);
	if(subst)
	{
		m_data->PutAttr(subst, a_pdf_subst_pdr, pdr);
		m_data->PutAttr(subst, a_pdf_subst_pdf, subst_pdf);
		m_data->PutAttr(subst, a_pdf_subst_id, id);
		m_data->PutAttr(subst, a_pdf_subst_value, count);
		m_data->PutAttr(subst, a_pdf_subst_unit, unit);
		m_data->PutAttr(subst, a_pdf_subst_parent_item, parent_pdf);
	}

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

CaplInstance *CaplProductManager::CreateSubstitute(CaplInstance *context_pdr,
		CaplInstance *subst_pdf,const TCHAR *id,const TCHAR *name,const TCHAR *descr, double count, CaplInstance *unit)
{
	if(m_data==0) return 0;
	if(context_pdr==0) return 0;
	if(context_pdr==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(context_pdr->GetType()==0) return 0;
	if(subst_pdf==0) return 0;
	if(subst_pdf==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(subst_pdf->GetType()==0) return 0;

	CaplAttrValue tst_values[3];
	tst_values[0].value.Set(context_pdr);
	tst_values[0].attr=a_pdf_subst_pdr;
	tst_values[1].value.Set(subst_pdf);
	tst_values[1].attr=a_pdf_subst_pdf;
	tst_values[2].value.Set(id);
	tst_values[2].attr=a_pdf_subst_id;
	if(!m_data->TestUniqueAttrValues(e_pdf_subst,0,3,&tst_values[0]))
	{
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Связь данных изделий с такой позицией уже есть в базе !!!"),MB_OK|MB_ICONSTOP);
		return 0;
	}	

	CaplInstance *subst=m_data->CreateInstance(e_pdf_subst);
	if(subst)
	{
		m_data->PutAttr(subst,a_pdf_subst_pdr,context_pdr);
		m_data->PutAttr(subst,a_pdf_subst_pdf,subst_pdf);
		m_data->PutAttr(subst,a_pdf_subst_id,id);
		m_data->PutAttr(subst,a_pdf_subst_name,name);
		m_data->PutAttr(subst,a_pdf_subst_description,descr);
		m_data->PutAttr(subst,a_pdf_subst_value,count);
		m_data->PutAttr(subst,a_pdf_subst_unit,unit);
	}

	if(m_AutoSave) m_data->NET_SaveChanges();
	return subst;
}

bool CaplProductManager::ShowProperties(CaplInstance* Inst, aplPrdDlgmode editMode, CaplInstance* rel, CaplInstance* subst)
{
	CaplSetResourceHandle setres(module_inst);
	CProductDlg dlg;
	dlg.m_mode = editMode;
	if(Inst==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(Inst!=0)
	{
		if(NULL == Inst->GetType()) 
		{
			if(m_api->m_ModeInteractive) AfxMessageBox( APL_T("Объект не существует."), MB_ICONINFORMATION);
			return false;
		}
		
		if(m_api->m_data.IsKindOf(Inst, e_pdf))
			dlg.m_pdf = Inst;
		else if(m_api->m_data.IsKindOf(Inst, e_prd))
			dlg.m_prd = Inst;
	}
	dlg.m_nauo = rel;
	dlg.m_subst = subst;
	dlg.m_api = m_api;
	bool bRes =	(dlg.DoModal()==IDOK);

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

CaplInstance* CaplProductManager::CreateProduct(CaplInstance* Inst, aplPrdDlgmode editMode)
{
	if(bNoCreateAndChangePDF)
	{
		CaplSetResourceHandle setres(module_inst);
		if(m_api->m_ModeInteractive)AfxMessageBox(IDS_NO_CREATE_PDF,MB_OK|MB_ICONSTOP);
		return 0;
	}

	CaplSetResourceHandle setres(module_inst);
	CProductDlg dlg;
	dlg.m_mode = editMode;
	if(Inst==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(Inst!=0)
	{
		if(m_api->m_data.IsKindOf(Inst, e_pdf))
			dlg.m_base_pdf = Inst;
		else if(m_api->m_data.IsKindOf(Inst, e_prd)){
			dlg.m_base_prd = Inst;
		}
		else if(m_api->m_data.IsKindOf(Inst, m_api->m_categ_mgr.e_categ))
		{
			m_api->m_data.GetAttr(Inst, m_api->m_categ_mgr.a_categ_id, dlg.m_prd_id);
			m_api->m_data.GetAttr(Inst, m_api->m_categ_mgr.a_categ_name, dlg.m_prd_name);
		}
	}
	dlg.m_api = m_api;
	bool bRes =	(dlg.DoModal()==IDOK);
	if(true==bRes)
	{
		if(m_AutoSave) 
			m_api->SaveChanges();

		if(true==m_AutoSave)
		{
			CString csAccPat;

			if(_T("")!=dlg.m_csAccessString)
				apidata.NET_SetAccessFromPattern(&dlg.m_aeCreatedInsts,dlg.m_csAccessString);
			else
			if(true==m_AutoUsurpire)
			{
				CaplEntity* et=NULL;

				if(aplModeCreateProduct==editMode)
					et=e_prd;
				if(aplModeCreateVersion==editMode)
					et=e_pdf;
				if(aplModeCreateSubProduct==editMode)
					et=e_pdf;
				if(aplModeCreateProductIfNew==editMode)
					et=0;
				

				if(NULL!=et)
					if(TRUE==m_api->m_options_mgr.GetDefPatern(et,csAccPat))
						apidata.NET_SetAccessFromPattern(&dlg.m_aeCreatedInsts,csAccPat);
			}
		}
	}

	if(editMode == aplModeCreateProduct)
		return dlg.m_prd;
	else if(editMode == aplModeCreateVersion)
		return dlg.m_pdf;
	else if(aplModeCreateProductIfNew==editMode){
		if(m_api->m_data.IsKindOf(Inst, e_pdf))
			return dlg.m_pdf;
		else if(m_api->m_data.IsKindOf(Inst, e_prd)){
			return dlg.m_prd;
		}
	}

	return NULL;
}

bool CaplProductManager::CreateSubProduct(CaplInstance* Parent, CaplInstance **BaseItem, CaplInstance** nuao)
{
	if(bNoCreateAndChangePDF)
	{
		CaplSetResourceHandle setres(module_inst);
		if(m_api->m_ModeInteractive)AfxMessageBox(IDS_NO_CREATE_PDF,MB_OK|MB_ICONSTOP);
		return false;
	}

	CaplSetResourceHandle setres(module_inst);
	CProductDlg dlg;
	dlg.m_mode = aplModeCreateSubProduct;
	if(BaseItem)
	{
		int iOption=0;
		m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Изделия\\Не наследовать атрибуты сборки при создании входящего"),iOption,0);
		if(0==iOption)
		{
			if(m_api->m_data.IsKindOf(*BaseItem, e_pdf))
				dlg.m_base_pdf = *BaseItem;
			else if(m_api->m_data.IsKindOf(*BaseItem, e_prd))
				dlg.m_base_prd = *BaseItem;
		}
	}
	dlg.m_parent_pdf = Parent;
	dlg.m_api = m_api;
	if(nuao)
		dlg.m_base_nauo = *nuao;
	bool bRes =	(dlg.DoModal()==IDOK);
	if(bRes)
	{
		if(nuao)
			*nuao = dlg.m_nauo;
		if(BaseItem)
			*BaseItem = dlg.m_pdf;

		if(dlg.m_pdf->GetAccessmode()==aplOWN)
			apidata.NET_SetAccessFromPattern(&dlg.m_aeCreatedInsts,dlg.m_csAccessString);
	}

	return dlg.m_add_mode&bRes;
}

bool CaplProductManager::CreateProductCopy(CaplInstance* Parent, CaplInstance **BaseItem, CaplInstance** nuao)
{
	if(bNoCreateAndChangePDF)
	{
		CaplSetResourceHandle setres(module_inst);
		if(m_api->m_ModeInteractive)AfxMessageBox(IDS_NO_CREATE_PDF,MB_OK|MB_ICONSTOP);
		return false;
	}

	CaplSetResourceHandle setres(module_inst);
	CProductDlg dlg;
	dlg.m_mode = aplModeCreateSubProduct;
	dlg.m_bIsCreatingCopy = true;
	if(BaseItem)
	{
		if(m_api->m_data.IsKindOf(*BaseItem, e_pdf))
		{
			dlg.m_base_pdf = *BaseItem;
		}
		else if(m_api->m_data.IsKindOf(*BaseItem, e_prd))
		{
			dlg.m_base_prd = *BaseItem;
			
		}
		// ЯАИ: Product должен быть всегда новый
		dlg.m_pdf = 0;
		dlg.m_prd = 0;
	}
	dlg.m_parent_pdf = Parent;

	if(Parent!=0)
	{
		if(NULL == Parent->GetType()) 
		{
			if(m_api->m_ModeInteractive) AfxMessageBox( APL_T("Объект не существует."), MB_ICONINFORMATION);
			return false;
		}
	}

	dlg.m_api = m_api;

	bool bRes =	(dlg.DoModal()==IDOK);
	if(bRes)
	{
		if(nuao)
			*nuao = dlg.m_nauo;
		if(BaseItem)
			*BaseItem = dlg.m_pdf;

		if(dlg.m_pdf->GetAccessmode()==aplOWN)
			apidata.NET_SetAccessFromPattern(&dlg.m_aeCreatedInsts,dlg.m_csAccessString);
	}

	return dlg.m_add_mode&bRes;
}

bool CaplProductManager::IsTechprocessContainsLockers(CaplInstance *techprocess)
{
	CaplFinder ff(DEF_SOURCE);
	int tpoCheckInedIndex = ff.CreateExt(m_api->m_prd_mgr.e_apl_tech_process_operation);
	ff.AddAttr(tpoCheckInedIndex, m_api->m_prd_mgr.a_tpo_check_in_date, _T(""), CaplFinder::cmpNotEqual);

	int tpoLockerIndex = ff.CreateExt(m_api->m_prd_mgr.e_apl_tech_process_operation, m_api->m_prd_mgr.a_tpo_process);
	ff.AddAttr(tpoLockerIndex, m_api->m_prd_mgr.a_tpo_locker, tpoCheckInedIndex);
	ff.AddToResult(tpoLockerIndex);
	ff.Find(m_api->m_data, true, false, false, true, false);

	return (ff.m_innerExtent.Find(techprocess) != -1);
}

CaplInstance* CaplProductManager::CreateLanguage(LPCTSTR lpszName)
{
	if(m_api==NULL) return NULL;
	if(!m_api->m_data.IsDictLoad()) return NULL;
	if(lpszName==NULL) return NULL;

	//проверка на уникальность
	aplExtent ext;
	CString buf;
	int i;
	m_api->m_data.GetEntityExtent(e_apl_language, ext);
	for(i=0; i<ext.GetSize(); i++)
	{
		if(ext[i]==NULL) continue;
		if(ext[i]->GetAccessmode()>aplRO) continue;
		m_api->m_data.GetAttr(ext[i], a_apl_language_name, buf);
		if(buf.CompareNoCase(lpszName)==0) return ext[i];
	}
	
	CaplInstance* nInst = m_api->m_data.CreateInstance(e_apl_language);
	ASSERT(nInst);
	m_api->m_data.PutAttr(nInst, a_apl_language_name, lpszName);

	if(m_AutoSave)
		m_api->SaveChanges();

	return nInst;
}

CaplInstance* CaplProductManager::CreateExportProduct(CaplInstance* Item, CaplInstance* language, LPCTSTR lpszId, LPCTSTR lpszName, LPCTSTR lpszCode,
													  LPCTSTR lpszPdfId, LPCTSTR lpszPdfCode, LPCTSTR lpszPdfCode1, LPCTSTR lpszPdfCode2, LPCTSTR lpszDescr)
{
	if(m_api==NULL) return NULL;
	if(!m_api->m_data.IsDictLoad()) return NULL;
	if(Item==NULL) return NULL;
	if(Item==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(Item->GetAccessmode()>aplRW) 
	{
		if(m_api->m_ModeInteractive)aplErrorMessage(S::NoAccessRight());
		return NULL;
	}

	if(language==NULL || lpszId==NULL)
	{
		CaplInstance* ReturnInst = NULL;
		CaplSetResourceHandle setres(module_inst);

		CExportProductAttrsDlg dlg(m_api);
		dlg.m_Inst = Item;
		if(dlg.DoModal()==IDOK)
			ReturnInst = dlg.m_CreatedInst;

		return ReturnInst;
	}

	//Проверка на уникальность
	aplExtent ext;
	CaplAttrValue tst_vals[3];
	tst_vals[0].attr = a_apl_export_product_ofproduct;
	tst_vals[0].value.Set(Item);
	tst_vals[1].attr = a_apl_export_product_language;
	tst_vals[1].value.Set(language);
	if(m_api->m_data.NET_FindInstancesWithAttrValues(e_apl_export_product, 2, &tst_vals[0], ext, false)>0)
	{
		if(m_api->m_ModeInteractive)
			AfxMessageBox( APL_T("Описание изделия на данном языке уже существует в БД!"), MB_OK|MB_ICONSTOP);
		return ext[0];
	}

	tst_vals[0].attr = a_apl_export_product_id;
	tst_vals[0].value.Set(lpszId);
	tst_vals[1].attr = a_apl_export_product_pdf_id;
	tst_vals[1].value.Set(lpszPdfId);
	tst_vals[2].attr = a_apl_export_product_language;
	tst_vals[2].value.Set(language);
	if(m_api->m_data.NET_FindInstancesWithAttrValues(e_apl_export_product, 3, &tst_vals[0], ext, false)>0)
	{
		if(m_api->m_ModeInteractive)
			AfxMessageBox( APL_T("Обозначение изделия и версии изделия на данном языке не уникальны!"), MB_OK|MB_ICONSTOP);
		return ext[0];
	}
	CaplInstance* nInst = m_api->m_data.CreateInstance(e_apl_export_product);
	ASSERT(nInst);
	m_api->m_data.PutAttr(nInst, a_apl_export_product_ofproduct, Item);
	m_api->m_data.PutAttr(nInst, a_apl_export_product_language, language);
	m_api->m_data.PutAttr(nInst, a_apl_export_product_id, lpszId);
	m_api->m_data.PutAttr(nInst, a_apl_export_product_name, lpszName);
	m_api->m_data.PutAttr(nInst, a_apl_export_product_code, lpszCode);
	m_api->m_data.PutAttr(nInst, a_apl_export_product_pdf_id, lpszPdfId);
	m_api->m_data.PutAttr(nInst, a_apl_export_product_pdf_code, lpszPdfCode);
	m_api->m_data.PutAttr(nInst, a_apl_export_product_pdf_code1, lpszPdfCode1);
	m_api->m_data.PutAttr(nInst, a_apl_export_product_pdf_code2, lpszPdfCode2);
	m_api->m_data.PutAttr(nInst, a_apl_export_product_descr, lpszDescr);

	if(m_AutoSave)
		m_api->SaveChanges();

	return nInst;
}

CaplInstance* CaplProductManager::CreateProductAttrsChange(CaplInstance* Item, LPCTSTR lpszId, LPCTSTR lpszName, LPCTSTR lpszCode,
														   LPCTSTR lpszPdfId, LPCTSTR lpszPdfCode, LPCTSTR lpszPdfCode1, LPCTSTR lpszPdfCode2)
{
	if(m_api==NULL) return NULL;
	if(!m_api->m_data.IsDictLoad()) return NULL;
	if(Item==NULL) return NULL;
	if(Item==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(Item->GetAccessmode()>aplRW) 
	{
		if(m_api->m_ModeInteractive)
			aplErrorMessage(S::NoAccessRight());
		return NULL;
	}
	if(!m_api->m_data.IsKindOf(Item, e_pdf) && !m_api->m_data.IsKindOf(Item, e_apl_export_product)) 
		return NULL;
	CaplInstance* person = m_api->m_appr_mgr.GetCurrentPerson();
	if(person==NULL)
	{
		if(m_api->m_ModeInteractive)
			AfxMessageBox( APL_T("Изменение атрибутов изделия доступно только пользователям, для которых указан сотрудник!"));
		return NULL;
	}

	CaplInstance *prd = NULL;
	if(m_api->m_data.IsKindOf(Item, e_prd))
		prd = Item;
	else if(m_api->m_data.IsKindOf(Item, e_pdf))
		m_api->m_data.GetAttr(Item, a_pdf_prd, prd);

	if(lpszId==NULL || lpszName==NULL)
	{
		bool bRes;
		CaplSetResourceHandle setres(module_inst);
		CChangeProductAttrsDlg dlg(m_api);
		dlg.m_Item = Item;
		bRes = dlg.DoModal()==IDOK;
		if(bRes)
			return dlg.m_CreatedInst;
		else return NULL;
	}

	CaplAttrValue tst_val[3];

	CString oldId, oldName, oldCode, buf, oldPdfId, oldPdfCode, oldPdfCode1, oldPdfCode2;
	CString newId(lpszId), newName(lpszName), newCode(lpszCode);
	CString newPdfId(lpszPdfId), newPdfCode(lpszPdfCode), newPdfCode1(lpszPdfCode1), newPdfCode2(lpszPdfCode2);

	COleDateTime time;
	if(m_api->m_data.IsConnected())
		m_api->m_data.NET_GetServerDateTime(time);
	else
		time = COleDateTime::GetCurrentTime();
	aplDate2String(time, buf);

	newId.TrimLeft(); newId.TrimRight();
	newName.TrimLeft(); newName.TrimRight();
	newCode.TrimLeft(); newCode.TrimRight();

	newPdfId.TrimLeft(); newPdfId.TrimRight();
	newPdfCode.TrimLeft(); newPdfCode.TrimRight();
	newPdfCode1.TrimLeft(); newPdfCode1.TrimRight();
	newPdfCode2.TrimLeft(); newPdfCode2.TrimRight();

	if(m_api->m_data.IsKindOf(Item, e_prd) || m_api->m_data.IsKindOf(Item, e_pdf))
	{
		m_api->m_data.GetAttr(prd, a_prd_id, oldId);
		m_api->m_data.GetAttr(prd, a_prd_name, oldName);
		m_api->m_data.GetAttr(prd, a_prd_code, oldCode);
		if(prd!=Item)
		{
			m_api->m_data.GetAttr(Item, a_pdf_id, oldPdfId);
			m_api->m_data.GetAttr(Item, a_pdf_code, oldPdfCode);
			m_api->m_data.GetAttr(Item, a_pdf_code1, oldPdfCode1);
			m_api->m_data.GetAttr(Item, a_pdf_code2, oldPdfCode2);
		}
	}
	else if(m_api->m_data.IsKindOf(Item, e_apl_export_product))
	{
		m_api->m_data.GetAttr(Item, a_apl_export_product_id, oldId);
		m_api->m_data.GetAttr(Item, a_apl_export_product_name, oldName);
		m_api->m_data.GetAttr(Item, a_apl_export_product_code, oldCode);
		m_api->m_data.GetAttr(Item, a_apl_export_product_pdf_id, oldPdfId);
		m_api->m_data.GetAttr(Item, a_apl_export_product_pdf_code, oldPdfCode);
		m_api->m_data.GetAttr(Item, a_apl_export_product_pdf_code1, oldPdfCode1);
		m_api->m_data.GetAttr(Item, a_apl_export_product_pdf_code2, oldPdfCode2);
	}

	if(oldId==newId && oldName==newName && oldCode==newCode &&
		oldPdfId==newPdfId && oldPdfCode==newPdfCode && oldPdfCode1==newPdfCode1 && oldPdfCode2==newPdfCode2)
	{
		if(m_api->m_ModeInteractive)
			AfxMessageBox( APL_T("Атрибуты не изменены!"), MB_OK|MB_ICONSTOP);
		return NULL;
	}

	//Проверка на уникальность
	if(m_api->m_data.IsKindOf(Item, m_api->m_prd_mgr.e_prd) || m_api->m_data.IsKindOf(Item, m_api->m_prd_mgr.e_pdf))
	{
		tst_val[0].value.Set(newId);
		tst_val[0].attr = m_api->m_prd_mgr.a_prd_id;
		if(!m_api->m_data.NET_TestUniqueAttrValues(e_prd, prd, 1, &tst_val[0], false))
		{
			if(m_api->m_ModeInteractive)
				AfxMessageBox( APL_T("Изделие с таким обозначением уже существует в БД!"), MB_OK|MB_ICONWARNING);
			return NULL;
		}
		if(prd!=Item) //Это версия изделия, проверяем уникальность версии
		{
			//Уникальность децимального номера по БД??
			if(newPdfCode!=oldPdfCode && !newPdfCode.IsEmpty())
			{
				tst_val[0].value.Set(newPdfCode);
				tst_val[0].attr = a_pdf_code;
				if(!m_api->m_data.NET_TestUniqueAttrValues(e_apl_pdf, Item, 1, &tst_val[0], false))
				{
					if(m_api->m_ModeInteractive)
						AfxMessageBox( APL_T("Версия изделия с таким кодом (децимальным номером) уже существует в БД!"), MB_OK|MB_ICONWARNING);
					return NULL;
				}
			}
			
			//Уникальность обозначения версии
			tst_val[0].value.Set(prd);
			tst_val[0].attr = a_pdf_prd;
			tst_val[1].value.Set(newPdfId);
			tst_val[1].attr = a_pdf_id;
			if(!m_api->m_data.NET_TestUniqueAttrValues(e_apl_pdf, Item, 2, &tst_val[0], false))
			{
				if(m_api->m_ModeInteractive)
					AfxMessageBox( APL_T("Версия изделия с таким обозначением уже существует в БД!"), MB_OK|MB_ICONWARNING);
				return NULL;
			}
		}
	}
	else if(m_api->m_data.IsKindOf(Item, e_apl_export_product))
	{
		CaplInstance *lang;
		m_api->m_data.GetAttr(Item, a_apl_export_product_language, lang);
		tst_val[0].value.Set(newId);
		tst_val[0].attr = a_apl_export_product_id;
		tst_val[1].value.Set(newPdfId);
		tst_val[1].attr = a_apl_export_product_pdf_id;
		tst_val[2].value.Set(lang);
		tst_val[2].attr = a_apl_export_product_language;
		if(!m_api->m_data.NET_TestUniqueAttrValues(e_apl_export_product, Item, 3, &tst_val[0], false))
		{
			if(m_api->m_ModeInteractive)
				AfxMessageBox( APL_T("Изделие с таким обозначением уже существует в БД!"), MB_OK|MB_ICONWARNING);
			return NULL;
		}
	}

	CaplInstance *nInst = m_api->m_data.CreateInstance(e_apl_product_attrs_change);
	ASSERT(nInst);

	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_code, oldCode);
	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_name, oldName);
	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_id, oldId);
	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_id, oldPdfId);
	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_id, oldPdfCode);
	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_id, oldPdfCode1);
	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_id, oldPdfCode2);
	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_person, person);
	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_item, Item);
	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_datetime, buf);
	m_api->m_data.PutAttr(nInst, a_apl_product_attrs_change_next, FindLastestAttrChange(Item, true));

	if(m_api->m_data.IsKindOf(Item, e_prd) || m_api->m_data.IsKindOf(Item, e_pdf))
	{
		m_api->m_data.PutAttr(prd, a_prd_id, newId);
		m_api->m_data.PutAttr(prd, a_prd_name, newName);
		m_api->m_data.PutAttr(prd, a_prd_code, newCode);
		if(prd!=Item)
		{
			m_api->m_data.PutAttr(Item, a_pdf_id, newPdfId);
			m_api->m_data.PutAttr(Item, a_pdf_code, newPdfCode);
			m_api->m_data.PutAttr(Item, a_pdf_code1, newPdfCode1);
			m_api->m_data.PutAttr(Item, a_pdf_code2, newPdfCode2);
		}
	}
	else if(m_api->m_data.IsKindOf(Item, e_apl_export_product))
	{
		m_api->m_data.PutAttr(Item, a_apl_export_product_id, newId);
		m_api->m_data.PutAttr(Item, a_apl_export_product_name, newName);
		m_api->m_data.PutAttr(Item, a_apl_export_product_code, newCode);
		m_api->m_data.PutAttr(Item, a_apl_export_product_pdf_id, newPdfId);
		m_api->m_data.PutAttr(Item, a_apl_export_product_pdf_code, newPdfCode);
		m_api->m_data.PutAttr(Item, a_apl_export_product_pdf_code1, newPdfCode1);
		m_api->m_data.PutAttr(Item, a_apl_export_product_pdf_code2, newPdfCode2);
	}

	ChangeWFState(nInst, _T("approved"));

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

bool CaplProductManager::LoadDictionary()
{
	if(m_api==NULL) return false;
	if(!m_api->m_data.IsDictLoad()) return false;

	if(m_api->m_data.IsConnected())
	{
		CaplLoadData ld(m_data,DEF_SOURCE);
		ld.AddQuery(_T('e'), 0, e_apl_language, 0, true, true);
		return ld.LoadEx();
	}

	return true;
}

bool CaplProductManager::ShowExportProduct(CaplInstance* Product, CaplInstance* Language)
{
	if(m_api==NULL) return false;
	if(!m_api->m_data.IsDictLoad()) return false;
	if(Product==NULL) return false;
	if(Product==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(Product->GetAccessmode()>aplRO) return false;

	bool bRes = false;
	CaplSetResourceHandle setres(module_inst);
	
	CExportProductAttrsDlg dlg(m_api);
	dlg.m_Inst = Product;
	dlg.m_DefLang = Language;
	dlg.m_bCreateMode = false;
	bRes = (dlg.DoModal()==IDOK);
	
	return bRes;
}

bool CaplProductManager::FindExportProducts(CaplInstance* Product, aplExtent &ExPrds, aplExtent *Langs)
{
	ExPrds.Clear();
	if(Langs)
		Langs->Clear();
	if(m_api==NULL) return false;
	if(!m_api->m_data.IsDictLoad()) return false;
	if(Product==NULL) return false;
	if(Product==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(Product->GetAccessmode()>aplRO) return false;

	if(m_api->m_data.IsConnected() && Product->GetId()!=0)
	{
		CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
		ld.AddQuery(_T('b'), Product->GetId(), e_apl_export_product, a_apl_export_product_ofproduct, true, true);
		ld.LoadEx();
	}

	int i;
	aplExtent ext, lgs;
	CaplInstance* inst;
	m_api->m_data.GetEntityExtent(e_apl_export_product, ext);
	for(i=0; i<ext.GetSize(); i++)
	{
		if(ext[i]==NULL) continue;
		if(ext[i]->GetAccessmode()>aplRO) continue;

		m_api->m_data.GetAttr(ext[i], a_apl_export_product_ofproduct, inst);
		if(inst==Product)
		{
			m_api->m_data.GetAttr(ext[i], a_apl_export_product_language, inst);
			lgs.Add(inst);
			ExPrds.Add(ext[i]);
		}
	}
	if(Langs)
		Langs->Append(lgs);

	return true;
}

CaplInstance* CaplProductManager::GetExportProduct(CaplInstance* Product, CaplInstance* Language, bool bFromBase)
{
	if(m_api==NULL) return NULL;
	if(!m_api->m_data.IsDictLoad()) return NULL;
	if(Product==NULL) return NULL;
	if(Product==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(Product->GetAccessmode()>aplRO) return NULL;
	if(Language==NULL) return NULL;
	if(Language==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(Language->GetAccessmode()>aplRO) return NULL;

	if(m_api->m_data.IsConnected() && Product->GetId()!=0 && bFromBase)
	{
		CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
		ld.AddQuery(_T('b'), Product->GetId(), e_apl_export_product, a_apl_export_product_ofproduct, true, true);
		ld.LoadEx();
	}
	
	int i;
	aplExtent ext, lgs;
	CaplInstance* inst;
	m_api->m_data.GetEntityExtent(e_apl_export_product, ext);
	for(i=0; i<ext.GetSize(); i++)
	{
		if(ext[i]==NULL) continue;
		if(ext[i]->GetAccessmode()>aplRO) continue;
		
		m_api->m_data.GetAttr(ext[i], a_apl_export_product_ofproduct, inst);
		if(inst==Product)
		{
			m_api->m_data.GetAttr(ext[i], a_apl_export_product_language, inst);
			if(inst==Language)
				return ext[i];
		}
	}

	return NULL;
}

CaplInstance* CaplProductManager::FindLastestAttrChange(CaplInstance* Item, bool bFromBase)
{
	if(m_api==NULL) return NULL;
	if(!m_api->m_data.IsDictLoad()) return NULL;
	if(Item==NULL) return NULL;
	if(Item==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return 0;
	}
	if(Item->GetAccessmode()>aplRO) return NULL;

	aplExtent ext;
	if(m_api->m_data.IsConnected() && bFromBase)
	{
		CaplAttrValue tst_vals[2];
		tst_vals[0].attr = a_apl_product_attrs_change_item;
		tst_vals[0].value.Set(Item);
		tst_vals[1].attr = a_apl_product_attrs_change_next;
		tst_vals[1].value.Set((CaplInstance*)NULL);
		if(m_api->m_data.NET_FindInstancesWithAttrValues(e_apl_product_attrs_change, 2, &tst_vals[0], ext, false)>0)
		{
			CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
			ld.AddQuery(0, ext[0], true);
			ld.LoadEx();
			return ext[0];
		}
		return NULL;
	}

	CaplInstance* inst;
	m_api->m_data.GetEntityExtent(e_apl_product_attrs_change, ext);
	for(int i=0; i<ext.GetSize(); i++)
	{
		if(ext[i]==NULL) continue;
		if(ext[i]->GetAccessmode()>aplRO) continue;
		m_api->m_data.GetAttr(ext[i], a_apl_product_attrs_change_item, inst);
		if(inst!=Item) continue;
		m_api->m_data.GetAttr(ext[i], a_apl_product_attrs_change_next, inst);
		if(inst==NULL)
			return ext[i];
	}

	return NULL;
}

bool CaplProductManager::FindAllPDFEffectiviti(CaplInstance* Pdr, aplExtent &ext, bool load_from_server)
{
	ext.Clear();
	if(Pdr==0) return false;
	if(Pdr==(CaplInstance*)-1) return false;
	if(Pdr->GetType()==0) return false;
	if(load_from_server){
		CaplAttrValue tst_vals[1];
		tst_vals[0].attr = a_pde_usage;
		tst_vals[0].value.Set(Pdr);
		m_api->m_data.NET_FindInstancesWithAttrValues(e_pd_eff, 1, &tst_vals[0], ext, false);
	}else{
		aplExtent ext2;
		CaplInstance* inst0;
		m_api->m_data.GetEntityExtent(e_pd_eff, ext2);
		for(int j=0;j<ext2.Size; j++)
		{
			m_api->m_data.GetAttr(ext2[j], a_pde_usage, inst0);
			if(inst0==Pdr)
			{
				ext.Add(ext2[j]);
			}
		}
	}
	return true;
}

bool CaplProductManager::FindallAttrsChanges(CaplInstance* Product, aplExtent &ext)
{
	ext.Clear();

	if(m_api==NULL) return false;
	if(!m_api->m_data.IsDictLoad()) return false;
	if(Product==NULL) return false;
	if(Product==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(Product->GetAccessmode()>aplRO) return false;

	if(m_api->m_data.IsConnected() && Product->GetId()!=0)
	{
		CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
		ld.AddQuery(_T('b'), Product->GetId(), e_apl_export_product, a_apl_product_attrs_change_item, true, true);
		ld.LoadEx();
	}
	aplExtent tmp;
	int i;
	CaplInstance* inst;
	for(i=0; i<tmp.GetSize(); i++)
	{
		if(tmp[i]==NULL) continue;
		if(tmp[i]->GetAccessmode()>aplRO) continue;
		m_api->m_data.GetAttr(tmp[i], a_apl_product_attrs_change_item, inst);
		if(inst==Product)
			ext.Add(tmp[i]);
	}
	
	return true;
}

bool CaplProductManager::ShowHistory(CaplInstance* Item)
{
	if(m_api==NULL) return false;
	if(!m_api->m_data.IsDictLoad()) return false;

	return true;
}

bool CaplProductManager::SelectLanguage(CaplInstance** SelectedLanguage)
{
	if(m_api==NULL) return false;
	if(!m_api->m_data.IsDictLoad()) return false;

	bool bRes = false;
	CaplSetResourceHandle setres(module_inst);
	CSelectLanguageDlg dlg(m_api);
	bRes = (dlg.DoModal()==IDOK);
	if(bRes && SelectedLanguage)
		*SelectedLanguage = dlg.m_inst;

	return bRes;
}

bool CaplProductManager::DeleteLanguage(CaplInstance* Language)
{
	if(m_api==NULL) return false;
	if(!m_api->m_data.IsDictLoad()) return false;
	if(Language==NULL) return false;
	if(Language==(CaplInstance*)-1) {
		if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка вызывающей программы! instance равен -1!"));
		return false;
	}
	if(Language->GetAccessmode()>aplOWN)
	{
		if(m_api->m_ModeInteractive)
			aplErrorMessage(S::NoAccessRight());
		return false;
	}
	
	//Ищем все объекты, зависящие от данного языка:
	// * apl_export_product
	// * apl_export_logbook
	// * apl_logbook_item;
	int i, j;
	const int count = 3;
	aplExtent ext, ext_to_del;
	CaplEntity *pEntities[count];
	CaplAttr *pAttrs[count];
	
	pEntities[0] = m_api->m_data.GetEntityBN(_T("apl_export_product"));
	if(pEntities[0])
		pAttrs[0] = m_api->m_data.GetAttrDefinition(pEntities[0], _T("language"));
	
	pEntities[1] = m_api->m_data.GetEntityBN(_T("apl_export_logbook"));
	if(pEntities[1])
		pAttrs[1] = m_api->m_data.GetAttrDefinition(pEntities[1], _T("language"));

	pEntities[2] = m_api->m_data.GetEntityBN(_T("apl_logbook_item"));
	if(pEntities[2])
		pAttrs[2] = m_api->m_data.GetAttrDefinition(pEntities[2], _T("language"));

	if(m_api->m_data.IsConnected() && Language->GetId()!=0) //Зачитываем в КЭШ информацию о наших языках
	{
		CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
		for(i=0; i<count; i++)
		{
			if(pEntities[i]==NULL) continue;
			ld.AddQuery(_T('b'), Language->GetId(), pEntities[i], pAttrs[i], true, false);
		}
		ld.LoadEx();
	}

	for(i=0; i<count; i++)
	{
		if(pEntities[i]==NULL) continue;
		m_api->m_data.GetEntityExtent(pEntities[i], ext);
		for(j=0; j<ext.GetSize(); j++)
		{
			if(ext[j]==NULL) continue;
			if(ext[j]->GetAccessmode()>aplRO)
			{
				if(m_api->m_ModeInteractive)
					aplErrorMessage(S::NoAccessRight());
				return false;
			}
		}
		ext_to_del.Append(ext);
	}
	ext_to_del.Add(Language);
	for(i=0; i<ext_to_del.GetSize(); i++)
	{
		if(ext_to_del[i]==NULL) continue;
		m_api->m_data.DeleteInstance(ext_to_del[i]);
	}

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

CaplInstance* CaplProductManager::GenerateComplectByPdf(CaplInstance *order, CaplInstance *pdf)
{
	CaplComplectMgr mgr(m_api);
	return mgr.GenerateComplectByPdf(order, pdf);
}

bool CaplProductManager::DeleteLimit(CaplInstance *nrm)
{
	CaplNrmmManager mgr(m_api);
	return mgr.DeleteLimit(nrm);	
}

bool CaplProductManager::GenerateLimitByPdf(CaplInstance *nrm, CaplInstance *pdf)
{	
	CaplNrmmManager mgr(m_api);
	return mgr.GenerateLimitByPdf(nrm, pdf);	
}

CaplInstance* CaplProductManager::FindPdfRelation(CaplInstance* PdfRelating, CaplInstance* PdfRelated)
{
	CaplAttrValue tst_val[2];
	aplExtent res;
	tst_val[0].attr = a_pdr_r_ted;
	tst_val[0].value.Set(PdfRelated);
	tst_val[1].attr = a_pdr_r_ting;
	tst_val[1].value.Set(PdfRelating);
	if(m_api->m_data.NET_FindInstancesWithAttrValues(e_pdr, 2, &tst_val[0], res, false)>0)
		return res[0];
	else 
		return NULL;
}

bool CaplProductManager::LoadSubstituteInfo(aplExtent &ext)
{
	if (!m_data)
		return false;
	if (!e_prd) 
		return false;

	if(!m_data->IsConnected()) 
		return true;

	if (!ext.Size)
		return true;

	// Чтение из базы
	CaplLoadData ld(m_data,DEF_SOURCE);

	for(int i=0; i<ext.Size; ++i)
	{
		ld.AddQuery(0, ext[i]);
	}
					ld.AddQuery(_T('d'), 0, 0, a_pdf_subst_id, true, true);
					ld.AddQuery(_T('d'), 0, 0, a_pdf_subst_name, true, true);
					ld.AddQuery(_T('d'), 0, 0, a_pdf_subst_description, true, true);
					ld.AddQuery(_T('d'), 0, 0, a_pdf_subst_value, true, true);
					ld.AddQuery(_T('d'), 0, 0, a_pdf_subst_unit, true, true);
	int pdr_id =	ld.AddQuery(_T('d'), 0, 0, a_pdf_subst_pdr, true, true);
					ld.AddQuery(_T('d'), pdr_id, 0, a_pdr_id, true, true);
					ld.AddQuery(_T('d'), pdr_id, 0, a_pdr_name, true, true);
					ld.AddQuery(_T('d'), pdr_id, 0, a_pdr_descr, true, true);
					ld.AddQuery(_T('d'), pdr_id, 0, a_pdr_r_ting, true, true);
					ld.AddQuery(_T('d'), pdr_id, 0, a_pdr_r_ted, true, true);
					ld.AddQuery(_T('d'), pdr_id, 0, a_apl_qacu_unit, true, true);
					ld.AddQuery(_T('d'), pdr_id, 0, a_apl_qacu_value, true, true);
					ld.AddQuery(_T('d'), pdr_id, 0, a_pdr_frames_of_reference, true, true);
					ld.AddQuery(_T('d'), pdr_id, 0, a_pdr_inner_id, true, true);
	int pdf_id =	ld.AddQuery(_T('d'), 0, 0, a_pdf_subst_pdf, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_pdf_id, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_pdf_prd, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_pdf_descr, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_pdf_code, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_pdf_code1, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_pdf_code2, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_pdfwss_source, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_apl_pdf_type, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_apl_pdf_standard, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_apl_pdf_state, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_apl_pdf_unit, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_apl_pdf_logbook, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_apl_pdf_first_usage, true, true);
					ld.AddQuery(_T('d'), pdf_id, 0, a_apl_pdf_additional_data, true, true);
	int parent_id = ld.AddQuery(_T('d'), 0, 0, a_pdf_subst_parent_item, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_pdf_id, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_pdf_prd, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_pdf_descr, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_pdf_code, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_pdf_code1, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_pdf_code2, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_pdfwss_source, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_apl_pdf_type, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_apl_pdf_standard, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_apl_pdf_state, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_apl_pdf_unit, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_apl_pdf_logbook, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_apl_pdf_first_usage, true, true);
					ld.AddQuery(_T('d'), parent_id, 0, a_apl_pdf_additional_data, true, true);
	if(!ld.LoadEx())
	{
		if(m_data->GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
			if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
		}
		return false;
	}

	return true;
}

bool CaplProductManager::FindPKIEx(CaplInstance **ciItem, CaplInstance **ciLot, bool bOnlyPrdIns, bool bDisableLot, bool bDisablePrdInst,LPCTSTR sSpravId)
{
	if(m_api==NULL) return false;
	if(!m_api->m_data.IsDictLoad()) return false;

	CaplSetResourceHandle setres(module_inst);

	bool bResult = false;
	CFindPKIDlgEx dlg(m_api,  APL_T("Поиск"));

	if(0!=sSpravId) dlg.m_sSpravId=sSpravId;
	dlg.m_bPrdInstOnly = bOnlyPrdIns;
	dlg.m_bDisableLot = bDisableLot;
	dlg.m_bDisablePrdInst = bDisablePrdInst;

	if(ciItem) dlg.m_ciItem = *ciItem;
	if(ciLot)  dlg.m_ciLot = *ciLot;				
	
	if(dlg.DoModal() == IDOK)
	{
		bResult = true;

		if(ciItem) *ciItem = dlg.m_ciItem;
		if(ciLot) *ciLot = dlg.m_ciLot;				
	}

	return bResult;
}
// Составляем список на экспорт
bool CreateEsi(CaplAPI *m_api, CaplInstance *pdf, aplExtent &ext4Out)
{
	ext4Out.Clear();
	CaplInstance *prd;
	m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_pdf_prd, prd);
	aplExtent ext_rel,ext_pdf; 
	ext4Out.Add(prd);
	ext4Out.Add(pdf);

	 m_api->m_prd_mgr.LoadAllSubProduct(0,0,pdf,ext_rel,ext_pdf);
	 m_api->m_prd_mgr.LoadPrdInfo(ext_pdf);
	int i;
	ext4Out.Unique=false;
	
	/*for(i=0;i<ext_pdf.GetSize();i++)
	{
		//CaplInstance *prd0,*pdf0=ext_pdf[i];
		//m_api->m_data.GetAttr(pdf0,a_pdf_prd,prd0);
		//ext4Out.Add(pdf0);
		//ext4Out.Add(prd0);
		LoadInstanceTree(ext_pdf[i],ext4Out);
	}
	ext4Out.Append(ext_rel);*/

	for(i=0;i<ext_rel.GetSize();i++) LoadInstanceTree(ext_rel[i],ext4Out);


	aplExtent ext_eff;
	m_api->m_data.GetEntityExtent(m_api->m_prd_mgr.e_pd_eff, ext_eff);
	for(i=0;i<ext_eff.Size; i++)
	{
		CaplInstance *eff=ext_eff[i],*pdr,*pdf1;
		m_api->m_data.GetAttr(eff, m_api->m_prd_mgr.a_pde_usage, pdr);
		if(0==pdr) continue;
		else m_api->m_data.GetAttr(pdr, m_api->m_prd_mgr.a_pdr_r_ting, pdf1);
		if(pdf1!=pdf) continue;
		ext4Out.Add(eff);
	}

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

bool CaplProductManager::GenerateESI4Ext(aplExtent &ext,  bool bShowResultMessage)
{
	CString sLog,buf;
	int i,n=0;
	long wait_dlg=aplStartWaitDlg(APL_T("Генерация ЭСИ"),APL_T("Генерация ЭСИ"));
	for(i=0;i<ext.GetSize();i++)
	{
		buf.Format(APL_T("%i из %i"),i,ext.GetSize());
		aplSetTextWaitDlg(wait_dlg,buf);
		CaplInstance *pdf=ext[i];
		if(0==pdf) continue;
		if(pdf->GetAccessmode()>aplRW)  continue;
		if(!m_api->m_data.IsKindOf(pdf,e_pdf)) continue;

		CaplInstance *doc=GenerateESI(pdf,_T(""),false,&sLog);
		if(0!=doc) n++;

	}
	aplEndWaitDlg(wait_dlg);

	buf.Format(APL_T("\n\nВсего создано %i документов."),n);
	sLog+=buf;

	aplShowBigMsg(sLog,APL_T("Генерация ЭСИ"));
	return true;
}


//***********************************************************************
CaplInstance *CaplProductManager::GenerateESI(CaplInstance *pdf, LPCTSTR num_change, bool bShowResultMessage, CString *sLog)
{
	if(0==m_api || 0==pdf) return 0;
	if(pdf->GetAccessmode()>aplRW) {AfxMessageBox(APL_T("Генерация ЭСИ: Недостаточно прав доступа!"),MB_ICONSTOP|MB_OK); return 0;}
	if(!m_api->m_data.IsKindOf(pdf,e_pdf)) {AfxMessageBox(APL_T("Генерация ЭСИ: Объект не является версией изделия!"),MB_ICONSTOP|MB_OK); return 0;}

	LoadPrdInfo(pdf);

	CString buf;
	if(0!=sLog)
	{
		(*sLog)+=APL_T("\nИзделие:");
		GetItemName(pdf,buf);
		(*sLog)+=buf;
		(*sLog)+=_T("   ");
	}

	m_api->m_data.GetAttr(pdf,a_apl_pdf_type,buf);
	if((buf!=_T("assembly"))&&(buf!=_T("kit"))&&(buf!=_T("komplex")))
	{
		if(0==sLog) AfxMessageBox(APL_T("Генерация ЭСИ: ЭСИ создается только для сборок комплектов или комплексов !"),MB_ICONSTOP|MB_OK); 
		else  (*sLog)+=APL_T("ЭСИ не создана. ЭСИ создается только для сборок комплектов или комплексов !");
		return 0;
	}

	CaplInstance *dt_esi=m_api->m_doc_mgr.GetDocumentTypeBN(APL_T("Электронная структура изделия"));
	if(0==dt_esi)//{AfxMessageBox(APL_T("В БД не настроен вид документа \"Электронная структура изделия\"!"),MB_ICONSTOP|MB_OK); return false;}
	{
		dt_esi = m_api->m_data.CreateInstance(m_api->m_doc_mgr.e_dt);
		m_api->m_data.PutAttr(dt_esi, m_api->m_doc_mgr.a_dt_pdt, APL_T("Электронная структура изделия"));
		m_api->SaveChanges();
	}


	//Формируем обозначение
	CaplInstance *prd, *esi_doc=0, *esi_rel=0;
	CString sDocId, sPdfId, sFileName;
	m_api->m_data.GetAttr(pdf,a_pdf_id,sPdfId);
	m_api->m_data.GetAttr(pdf,a_pdf_prd,prd);
	m_api->m_data.GetAttr(prd,a_prd_id,sDocId);
	if(sPdfId!=_T("")){sDocId+=_T("-"); sDocId+=sPdfId;}

	// Готовим обозначение файла
	buf= sDocId.Left(20);
	buf.Replace(_T(' '),_T('_'));
	buf.Replace(_T('?'),_T('_'));
	buf.Replace(_T('*'),_T('_'));
	buf.Replace(_T('/'),_T('_'));
	buf.Replace(_T('\\'),_T('_'));
	sFileName = _T("esi_") + buf + _T(".std");

	CString sPathRep;  aplGetTempPath(sPathRep);
	sPathRep+=sFileName;
	SetFileAttributes(sPathRep,FILE_ATTRIBUTE_NORMAL);
	DeleteFile(sPathRep);

	// Составляем список на экспорт
	aplExtent ext4Out;
	CreateEsi(m_api,pdf,ext4Out);


	// Экспортируем данные
	/*CaplMap inst_map;
	CaplStepData file_data;
	CString FullDictName;
	m_api->m_data.GetFullDictName(FullDictName);
	file_data.LoadDictionaryFromFile(FullDictName);
	CaplExchangeManager exch_mgr; exch_mgr.Attach(api);
	exch_mgr.CopyData(ext4Out, inst_map, &file_data);
	aplP21Header header;
	if(!file_data.SaveP21(sPathRep,header)) {AfxMessageBox(APL_T("Ошибка сохранения файла!"),MB_ICONSTOP|MB_OK); return true;}*/

	CaplFictiveStepData fictive_data;
	fictive_data.Initialize(&(m_api->m_data),&ext4Out);
	//aplP21Header header;
	//if(!fictive_data.SaveP21(sPathRep,header,aplWIN,true)){AfxMessageBox(APL_T("Ошибка сохранения файла!"),MB_ICONSTOP|MB_OK); return true;}
	
	CSortClass::SortInstById(fictive_data.instances); //чтобы при отсутствии изменений файды совпадали
	if(!fictive_data.SaveToFile(sPathRep,false))
	{
		if(0==sLog) AfxMessageBox(APL_T("Генерация ЭСИ: Ошибка сохранения файла!"),MB_ICONSTOP|MB_OK); 
		else (*sLog)+=APL_T("Ошибка сохранения файла!");
		return 0;
	}


	// Ищем документ ЭСИ
	CaplAttrValue tst_values[2];
	aplExtent ext;
	
	tst_values[0].value.Set(pdf);
	tst_values[0].attr= m_api->m_doc_mgr.a_doc_src_item;
	tst_values[1].value.Set(dt_esi);
	tst_values[1].attr= m_api->m_doc_mgr.a_doc_kind;
	m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_doc_mgr.e_apl_doc,2,&tst_values[0],ext,true);

	if(ext.GetSize()>0) esi_doc=ext[0];  //других таких не предвидится

	//sPathRep=_T("c:\\temp\\0.txt");

	bool bNewDoc=false;

	if(0!=esi_doc)
	{
		m_api->m_doc_mgr.LoadDocInfo(esi_doc);
		if(0==m_api->m_doc_mgr.CompareRevisionWithFile(esi_doc,sPathRep))
		{
			if(0==sLog)	AfxMessageBox(APL_T("Генерация ЭСИ: Данные не изменились, новая версия не создается! Активная версия актуальна."),MB_ICONSTOP|MB_OK); 
			else (*sLog)+=APL_T("Данные не изменились, новая версия не создается!");
			return 0;
		}
		/* ЯАИ: Это на будущее пока не надо.
		else 
		{
			// Проверяем последнюю
			CaplInstance *act_rev,*last_rev;
			last_rev=m_api->m_doc_mgr.GetLastDocumenrRevision(esi_doc);
			m_api->m_data.GetAttr(esi_doc,m_api->m_doc_mgr.a_apl_doc_active,act_rev);
			if(act_rev!=last_rev  && 0!=last_rev)
			{
				m_api->m_doc_mgr.LoadDocInfo(last_rev);
				if(0==m_api->m_doc_mgr.CompareRevisionWithFile(last_rev,sPathRep))
				{
					if(0==sLog)	AfxMessageBox(APL_T("Генерация ЭСИ: Данные не изменились, новая версия не создается! Внимание! Активная версия не актуальна!."),MB_ICONSTOP|MB_OK); 
					else (*sLog)+=APL_T("Данные не изменились, новая версия не создается! Внимание! Активная версия не актуальна!.");
					return 0;
				}
			}
		}*/
		esi_rel=m_api->m_doc_mgr.FindAssociation(pdf,esi_doc); // проверяем связку
	}
	else 
	{
		//Создаем новый документ
		bNewDoc=true;
		
		esi_doc=m_api->m_data.CreateInstance(m_api->m_doc_mgr.e_apl_doc);
		m_api->m_data.PutAttr(esi_doc,m_api->m_doc_mgr.a_doc_id,sDocId);
		m_api->m_data.PutAttr(esi_doc,m_api->m_doc_mgr.a_doc_src_item,pdf);
		m_api->m_data.PutAttr(esi_doc,m_api->m_doc_mgr.a_doc_kind,dt_esi);
		m_api->m_data.PutAttr(esi_doc,m_api->m_doc_mgr.a_doc_add_dt_code,APL_T("ЭC"));

		m_api->m_data.GetAttr(prd,a_prd_name,buf);
		m_api->m_data.PutAttr(esi_doc,m_api->m_doc_mgr.a_doc_name,buf);

		m_api->m_data.PutAttr(esi_doc, m_api->m_doc_mgr.a_apl_doc_system,_T("GenerateESI") );

	}
	
	if(0==esi_rel) esi_rel=m_api->m_doc_mgr.CreateAssociation(pdf,esi_doc,0,0,APL_DOCUMENT_RELATION,false);
	
	CString sOldState;
	m_api->m_data.GetAttr(esi_doc,m_api->m_doc_mgr.a_apl_doc_wf_state,sOldState);

	CaplAdminModeProvider adminmode(&(m_api->m_data),-1, -1,DEF_SOURCE);
	m_api->m_data.PutAttr(esi_doc,m_api->m_doc_mgr.a_apl_doc_wf_state,_T("")); // Обманываем проверку состояния
	CaplInstance *doc_rev = m_api->m_doc_mgr.CreateDocumentRevision(esi_doc, sPathRep,true,true);
	m_api->m_data.PutAttr(esi_doc,m_api->m_doc_mgr.a_apl_doc_wf_state,sOldState);
	if(0!=num_change) m_api->m_data.PutAttr(doc_rev,m_api->m_doc_mgr.a_apl_doc_rev_label,num_change);
	SetFileAttributes(sPathRep,FILE_ATTRIBUTE_NORMAL);
	DeleteFile(sPathRep);

	if(0==doc_rev) 
	{
		if(0==sLog)	AfxMessageBox(APL_T("Генерация ЭСИ: Ошибка при создании версии документа!"),MB_ICONSTOP|MB_OK); 
		else (*sLog)+=APL_T("Ошибка при создании версии документа!");
		return 0;
	}

	aplExtent ext4Access; ext4Access.Add(doc_rev); ext4Access.Add(esi_doc); 
	m_api->m_data.NET_SetInstancesAccess(&ext4Access,(CaplInstance*)-1,aplRO);
	adminmode.ExitAdminMode();

	/*if(bNewDoc) buf=APL_T("Документ создан!  Открыть для просмотра ?");
	else  buf=APL_T("Cоздана новая версия документа!  Открыть для просмотра ?");

	if(IDYES==AfxMessageBox(buf,MB_ICONINFORMATION|MB_YESNO))
	{
		m_api->m_doc_mgr.ViewWithMarkView(doc_rev);
	}*/

	if(bNewDoc)buf=APL_T("Создан новый документ!");
	else buf=APL_T("Создана новая версия документа!");

	if(0!=sLog)	(*sLog)+=buf;

	if(bShowResultMessage)AfxMessageBox(buf);

	return doc_rev;
}


bool CompareInstance(CaplInstance *inst1, CaplInstance *inst2, CString &sLog)
{
	if(0==inst1 || 0==inst2) {sLog+=APL_T("\nНеверные данные сравнения объектов"); return false;}

	CString buf;
	if(inst1->GetType()->name!=inst2->GetType()->name)
	{
		buf.Format(APL_T("\nНе cовпадают типы объектов #%i и #%i. Сравнение невозможно"),inst1->GetId(),inst2->GetId());
		sLog+=buf;  return false;
	}
	int i, attr_count=inst1->GetType()->all_attrs.GetSize();
	bool bResult=true;
	for(i=0;i<attr_count;i++)
	{
		CaplValue *val1=&(inst1->attrs[i].value);
		CaplValue *val2=&(inst2->attrs[i].value);

		if(val1->type!=val2->type)
		{
			if(val2->type==aplNOTYPE || val1->type==aplNOTYPE)
			{
				bResult=false;
				buf.Format(APL_T("\nОбъект #%i (%s) изменен атрибут '%s'"),inst1->GetId(),LPCTSTR(inst1->GetType()->name),LPCTSTR(inst1->GetType()->all_attrs[i]->name));
				sLog+=buf;  continue;

			}
		}
		bool bEgu=true;
		if(val1->type==aplSTRING||val1->type==aplENUMERATION) {	buf=val1->sval; if(buf!=val2->sval) bEgu=false;	}
		else if(val1->type==aplINTEGER) {	if(val1->ival!=val2->ival) bEgu=false;	}
		else if(val1->type==aplREAL) {	if(val1->rval!=val2->rval) bEgu=false;}
		else if(val1->type==aplINSTANCE) {	if(val1->instval->GetId()!=val2->instval->GetId()) bEgu=false;}

		if(!bEgu)
		{
			//CaplEntity *ent=inst1->GetType();
			//CaplAttr *attr=ent->all_attrs[i];
			bResult=false;
			buf.Format(APL_T("\nОбъект #%i (%s) изменен атрибут '%s'"),inst1->GetId(),LPCTSTR(inst1->GetType()->name),LPCTSTR(inst1->GetType()->all_attrs[i]->name));
			sLog+=buf;  continue;
		}
	}
	return bResult;
}


bool CaplProductManager::CompareDocWintESI(CaplInstance *doc_or_revision)
{
	if(0==m_api || 0==doc_or_revision) return false;
	if(doc_or_revision->GetAccessmode()>aplRO) {AfxMessageBox(APL_T("Недостаточно прав доступа!"),MB_ICONSTOP|MB_OK); return false;}
	
	m_api->m_doc_mgr.LoadDocInfo(doc_or_revision);

	CaplInstance *rev=0;
	if(m_api->m_data.IsKindOf(doc_or_revision,m_api->m_doc_mgr.e_apl_doc_rev)) rev=doc_or_revision;
	else if(m_api->m_data.IsKindOf(doc_or_revision,m_api->m_doc_mgr.e_doc)) m_api->m_data.GetAttr(doc_or_revision,m_api->m_doc_mgr.a_apl_doc_active,rev);
	else return false;
	if(0==rev) {AfxMessageBox(APL_T("Не найдена версия документа!"),MB_ICONSTOP|MB_OK); return false;}

	// читаем данные из документа	
	long rev_size;// размер файла версии
	CaplInstance *ciSource;
	m_api->m_data.GetAttr(rev, m_api->m_doc_mgr.a_apl_doc_rev_access_form, ciSource);
	if(!m_api->m_data.NET_GetBlobSize(ciSource, m_api->m_doc_mgr.a_apl_stored_document_source, rev_size))return false;

	char *mem_rev=new char[rev_size];
	m_api->m_data.NET_LoadBlob2Memory(ciSource, m_api->m_doc_mgr.a_apl_stored_document_source, (BYTE*)mem_rev,rev_size);

	CaplStepData doc_data;
	CaplDataBuf doc_data_buf;
	doc_data_buf.SetExternalData(mem_rev,rev_size);

	doc_data.ApploadFromDataBuf(doc_data_buf);
	delete mem_rev;


	// Определяем версию сборки.  
	CaplInstance *top_pdf=0;
	aplExtent ext_rel;
	doc_data.GetEntityExtentBN(S::nauo,ext_rel);
	if(ext_rel.GetSize()>0)doc_data.GetAttrBN(ext_rel[0],S::relating_pd,top_pdf); //Считаем что сборка одна

	if(0==top_pdf) // например, пустая сборка
	{
		aplExtent ext_pdf;
		doc_data.GetEntityExtentBN(S::pdf,ext_pdf);
		if(ext_pdf.GetSize()>0) top_pdf=ext_pdf[0];
	}

	if(0==top_pdf) {AfxMessageBox(APL_T("Не удалось найти сборку в документе!"),MB_ICONSTOP|MB_OK); return false;}
	top_pdf=m_api->m_data.GetInstById(top_pdf->GetId());
	if(0==top_pdf) {AfxMessageBox(APL_T("Не удалось найти эквивалентную сборку в БД!"),MB_ICONSTOP|MB_OK); return false;}

	m_api->m_prd_mgr.LoadPrdInfo(top_pdf);
	aplExtent ext4Out;
	CreateEsi(m_api,top_pdf,ext4Out);
	//CaplFictiveStepData fictive_data;
	//fictive_data.Initialize(&(m_api->m_data),&ext4Out);

	int i;
	CaplMap map_db_id_inst, map_file_id_inst;
	for(i=0;i<ext4Out.GetSize();i++ )map_db_id_inst.Add(ext4Out[i]->GetId(),(long)(ext4Out[i]));
	for(i=0;i<doc_data.instances.GetSize();i++ )map_file_id_inst.Add(doc_data.instances[i]->GetId(),(long)(doc_data.instances[i]));

	

	//CSortClass::SortInstById(doc_data.instances);

	/*aplExtent ext_pdf_db, ext_pdf_file;

	//fictive_data.GetEntityExtentBN(_T("S::pdf"),ext_pdf_db);
	//doc_data.GetEntityExtentBN(S::pdf,ext_pdf_file);
	
	CaplMap map_pdf_id_inst;
	for(i=0;i<ext_pdf_db.GetSize();i++ )map_pdf_id_inst.Add(ext_pdf_db[i]->GetId(),ext_pdf_db[i]);

	CString dLog;

	int i;
	for(i=0;i<ext_pdf_file.GetSize();i++)
	{
		CaplInstance *pdf_file=ext_pdf_file[i];
		CaplInstance *pdf_db=map_pdf_id_inst.QGetByIn(pdf_file->GetId());

		if(pdf_db)
		


	}*/


	// Сравниваем 2 extent-a

	CString buf,sLog;
	bool bEqu=true; // данные идентичны
	bool bOnlyNew=true; // Изменения могли быть получениы проведение изменения


	//CSortClass::SortInstById(doc_data.instances);
	//CSortClass::SortInstById(fictive_data.instances);
	for(i=0;i<doc_data.instances.GetSize();i++)
	{
		CaplInstance *inst1=doc_data.instances[i];
		CaplInstance *inst2=(CaplInstance *)map_db_id_inst.QGetPointerByIn(inst1->GetId());
		if(0==inst2)
		{
			bEqu=false; bOnlyNew=false;
			buf.Format(APL_T("\nИз БД удален #%i (%s)"),inst1->GetId(),LPCTSTR(inst1->GetType()->name));
			sLog+=buf;
		}
		else if(!CompareInstance(inst1,inst2,sLog))
		{
			if(inst1->GetType()->name.Find(_T("effectivity"))<0) bOnlyNew=false; // кроме применяемости ничего изменяться не может
			bEqu=false;
		};
	}

	// Ищем новые объекты
	for(i=0;i<ext4Out.GetSize();i++)
	{
		CaplInstance *inst1=ext4Out[i];
		CaplInstance *inst2=(CaplInstance *)map_file_id_inst.QGetPointerByIn(inst1->GetId());
		if(0==inst2)
		{
			bEqu=false;
			buf.Format(APL_T("\nВ БД добавлен #%i (%s)"),inst1->GetId(),LPCTSTR(inst1->GetType()->name));
			sLog+=buf;  continue;
		}
	}



	if(bEqu) AfxMessageBox(APL_T("Изменения отсутствуют!"), MB_ICONINFORMATION|MB_OK);
	else
	{
		if(bOnlyNew) buf=APL_T("Данные были дополнены!");
		else buf=APL_T("Данные изменились!");
		buf+=APL_T(" Просмотреть изменения ?");
		if(IDYES==AfxMessageBox(buf, MB_ICONSTOP|MB_YESNO)) aplShowBigMsg(sLog,APL_T("Протокол сравнения"));
	}
	return true;
}