// aplExchangeManager.cpp: implementation of the CaplExchangeManager class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include <apl_gui.h>
#include "apl_api.h"
#include "SelectName.h"
#include "dictionary.h"
#include "ExportInstanceDialog.h"
#include "ImportDialog.h"
#include "aplMgrPrgsDlg.h"  
#include <aplPacket.h>

#define MAX_RANGE 100
int delta=1;
void TestRange(int &m_recurs_level,CaplMgrPrgsDlg* m_prgs_dlg)
{
	if(m_prgs_dlg){ 
		m_recurs_level+=delta;
		if(m_recurs_level>0){
			if( m_recurs_level>=MAX_RANGE){delta=-1;}
			else{m_prgs_dlg->SetPos(m_recurs_level);}
		}
		if(m_recurs_level<0){
			delta=1;
		}
	}
}

#define INC_PRGS_POS(pos,count) prgs_count++; if(prgs_count>=count){prgs_count=0; prgs_dlg.SetPos(pos);}
#define INC_PRGS_POS_P(pos,count) prgs_count++; if(prgs_count>=count){prgs_count=0; if(m_prgs_dlg) m_prgs_dlg->SetPos(pos);}
//#define INC_EXP_POS {m_recurs_level++;if(m_prgs_dlg){ m_prgs_dlg->SetPos(m_recurs_level);}}
#define INC_EXP_POS TestRange(m_recurs_level,m_prgs_dlg);
//#define DEC_EXP_POS {m_recurs_level--;if(m_prgs_dlg){ m_prgs_dlg->SetPos(m_recurs_level);}}
#define DEC_EXP_POS 
//#define INC_PRGS_POS(pos,count) m_prgs_dlg.SetPos(pos);

// Настройки экспорта
BOOL CaplExchangeManager::m_ExportSubCategory=TRUE;
BOOL CaplExchangeManager::m_ExportClassifiers=TRUE;
BOOL CaplExchangeManager::m_ExportProductInstance= TRUE;;
BOOL CaplExchangeManager::m_ExportSubProduct=TRUE;
BOOL CaplExchangeManager::m_ExportProductMaterial=TRUE;
BOOL CaplExchangeManager::m_ExportProductCharacteristics=TRUE;
BOOL CaplExchangeManager::m_ExportRequirments=TRUE;
BOOL CaplExchangeManager::m_ExportAssDocuments=TRUE;
BOOL CaplExchangeManager::m_ExportApproval=TRUE;
BOOL CaplExchangeManager::m_ExportPrj=TRUE;
BOOL CaplExchangeManager::m_ExportPrjVer=FALSE;
BOOL CaplExchangeManager::m_ExportFolders=TRUE;
BOOL CaplExchangeManager::m_ExportBP=TRUE;
BOOL CaplExchangeManager::m_ExportBPRes=TRUE;
BOOL CaplExchangeManager::m_ExportNotes = TRUE;
BOOL CaplExchangeManager::m_IgnoreAddDict = TRUE;

BOOL CaplExchangeManager::m_ExportDocWithOriginalNames=TRUE;
BOOL CaplExchangeManager::m_ExportDocReqvToExtFile=FALSE;

CString m_OutPath;
CString m_OutFile;

// Настройки Импорта
BOOL CaplExchangeManager::m_ImportCategory=true;
BOOL CaplExchangeManager::m_ImportClassifiers=true;
BOOL CaplExchangeManager::m_ImportProductStruct=true;
BOOL CaplExchangeManager::m_ImportProductInst=true;
BOOL CaplExchangeManager::m_ImportProductMaterial=true;
BOOL CaplExchangeManager::m_ImportProductCharacteristics=true;
BOOL CaplExchangeManager::m_ImportAssDocuments=true;
BOOL CaplExchangeManager::m_ImportApproval=true;
BOOL CaplExchangeManager::m_ImportFolders=true;
BOOL CaplExchangeManager::m_ImportProject=true;
BOOL CaplExchangeManager::m_ImportBP=true;
BOOL CaplExchangeManager::m_ImportBPRes=true;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//**********************************************************************
void RemapAggrToNewDB(CaplAggr &aggr, CaplMap &map)
{
	int i;
	int Range = aggr.GetSize();	

	// Массив вложенный
	CaplValue *val;
	for ( i=0; i < Range; i++ )
	{
		val=aggr.GetByIndex(i);
		if(val==0) continue;
		if ( val->type == aplAGGR ) RemapAggrToNewDB(*(val->aggrval),map);
		else if ( val->type == aplINSTANCE )
		{
			long k=map.QGetByIn((long)val->instval);
			if(k==-1)k=0;
			if(k==0) {aggr.Remove(i); i--;}
			else val->instval = (CaplInstance*)k;
		}	
	}
};
//*************************************************************
bool AFX_EXT_API LoadInstanceTree(CaplInstance *inst, aplExtent &m_array,CaplExchangeManager* exch_mgr)
{
	if(inst==0)	return false;
	if(inst->GetType()==0) return false;
	if(inst->GetAccessmode()>aplRO) return false;
	CaplInstance * inst2=0;
	int i=0;

	for(i=0; i<m_array.GetSize();i++)
	{
		if(inst==m_array[i]) return false;
	}

	m_array.Add(inst);
	for(int j=0;j<inst->GetType()->all_attrs.GetSize();j++)
	{	
		if(inst->attrs==0) continue;
		switch(inst->attrs[j].value.type)
		{
			case aplINSTANCE:
				{
					inst->attrs[j].value.Get(inst2);
					if(inst2!=0){ 
						// 2026.03.23 ЯАИ обработка перенесена в конец функции
						/*
						if(exch_mgr!=0){
							if(exch_mgr->m_api->m_data.IsKindOf(inst2,exch_mgr->m_api->m_classifier_mgr.e_apl_classifier_level) ||
								exch_mgr->m_api->m_data.IsKindOf(inst2,exch_mgr->m_api->m_classifier_mgr.e_apl_classifier_system) ||
								exch_mgr->m_api->m_data.IsKindOf(inst2,exch_mgr->m_api->m_categ_mgr.e_categ))
							{
								exch_mgr->ExportInstance(inst2,_T(""),true);
							}
						}*/
						LoadInstanceTree(inst2, m_array, exch_mgr);
					}
					break;
				}
			case aplAGGR:
				{
					CaplValue value;
					CaplAggr aggr;
					inst->attrs[j].value.Get(aggr);
					for(int i=0;i<aggr.GetSize();i++)
					{
						aggr.GetByIndex(i,value);
						if(value.type==aplINSTANCE)
						{
							value.Get(inst2);
							if(inst2!=0){ 
								// 2026.03.23 ЯАИ обработка перенесена в конец функции
								/*if(exch_mgr!=0){
									if(exch_mgr->m_api->m_data.IsKindOf(inst2,exch_mgr->m_api->m_classifier_mgr.e_apl_classifier_level) ||
										exch_mgr->m_api->m_data.IsKindOf(inst2,exch_mgr->m_api->m_classifier_mgr.e_apl_classifier_system) ||
										exch_mgr->m_api->m_data.IsKindOf(inst2,exch_mgr->m_api->m_categ_mgr.e_categ))
									{
										exch_mgr->ExportInstance(inst2,_T(""),true);
									}
								}*/
								LoadInstanceTree(inst2, m_array, exch_mgr);
							}
						}
					}
					break;
				}
			default:break;
		}
	}

	// 2026.03.23 ЯАИ: затычка на случай, если не зачитаны справочники
	if(0!=exch_mgr)
	{
		if(exch_mgr->m_api->m_data.IsKindOf(inst, exch_mgr->m_api->m_classifier_mgr.e_apl_classifier_level))
		{
			CaplInstance *system=0;
			exch_mgr->m_api->m_data.GetAttr(inst, exch_mgr->m_api->m_classifier_mgr.a_apl_classifier_level_system,system);
			if(0!=system && 0==system->attrs) 
				exch_mgr->m_api->m_classifier_mgr.LoadClassifierInfo(system);

			m_array.Add(system);

			// Заносим родителей уровня, а то при импорте получается криво
			CaplInstance *parent=inst;
			while(0!=parent)
			{
				exch_mgr->m_api->m_data.GetAttr(parent, exch_mgr->m_api->m_classifier_mgr.a_apl_classifier_level_parent,parent);
				if(0!=parent && 0==parent->attrs) exch_mgr->m_api->m_classifier_mgr.LoadClassifierInfo(parent);
				m_array.Add(parent);
			}
		}
	}
	return true;
}

//********************************************************************************
//********************************************************************************
//********************************************************************************
CaplExchangeManager::CaplExchangeManager()
{
	m_fileApi=0;
	m_FileData=0;
	m_prgs_dlg=0;
	m_recurs_level=1;
}

void CaplExchangeManager::Detach()
{
	CaplStepManager::Detach();
}

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

	/* убрал ayatsk т.к это и так читается в PSM. а LoadOrgStruct - очень длинная операция для ГРПЗ
	
	m_api->m_charact_mgr.LoadDictionary();
	m_api->m_appr_mgr.LoadOrgStruct();
	m_api->m_prd_mgr.LoadAssortment();*/

	return  true;
}
//********************************************************************************
bool CaplExchangeManager::ExportBP(CaplInstance *inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0)  return false;
	if(inInst->GetAccessmode()>aplRO) return false;

	int i;
	INC_EXP_POS;
	CaplInstance *obj,*inst=0,*type=0;
	if(m_ExportNotes) ExportNotes(inInst);
	if(m_data->IsKindOf(inInst,m_api->m_bp_mgr.e_apl_bp_inst))
	{
		if(m_ExportProductInstance)
		{
			m_api->m_bp_mgr.LoadBPInstInfo(inInst);
			LoadInstanceTree(inInst, m_array, this);
			
			if(m_ExportBPRes)
			{
				aplExtent extRes1;
				m_api->m_data.GetAttr(inInst, m_api->m_bp_mgr.a_bp_inst_res, extRes1);
				for(i=0;i<extRes1.Size;i++)
				{
					inst=extRes1[i];
					if(inst==0) continue;
					LoadInstanceTree(inst, m_array, this);

					m_data->GetAttr(inst,m_api->m_bp_mgr.a_bp_res_object, obj);
					if(obj!=0) ExportInstance(obj, 0, true);

					if(m_ExportProductCharacteristics) ExportCharacteristic(inst);
					if(m_ExportAssDocuments)ExportDocument(inst, m_OutPath);
					if(m_ExportApproval) m_exported_items_4_approval.Add(inst);
				}
			}

			if(m_ExportProductCharacteristics)ExportCharacteristic(inInst);
			if(m_ExportAssDocuments)ExportDocument(inInst,m_OutPath);
			if(m_ExportApproval) m_exported_items_4_approval.Add(inInst);

			if(m_ExportBP)
			{
				CaplInstance* bp_proc= NULL;
				
				m_api->m_data.GetAttr(inInst, m_api->m_bp_mgr.a_bp_inst_process, bp_proc);
				if(bp_proc) ExportBP(bp_proc);

				CaplAggr aggr0;
				m_data->GetAttr(inInst,m_api->m_bp_mgr.a_bp_inst_elements, aggr0);
				for(i=0;i<aggr0.GetSize();i++)
				{
					aggr0.GetByIndex(i,bp_proc);
					ExportBP(bp_proc);
				}
			}
		}
	}
	else if(!m_data->IsKindOf(inInst,m_api->m_bp_mgr.e_bp))
	{
		aplExtent ext,ext_rel;
		m_api->m_bp_mgr.FindAssociatedBP(inInst,ext,ext_rel);
		for(i=0;i<ext_rel.Size;i++)
		{
			inst=ext_rel[i];
			m_array.Add(inst);
			aplExtent bp_context;
			m_data->GetAttr(inst, m_api->m_bp_mgr.a_bp_ref_frames_of_reference, bp_context);
			m_array.Append(bp_context);
			
			m_data->GetAttr(inst,m_api->m_bp_mgr.a_bp_ref_process,obj);
			ExportBP(obj);
		}
		if(m_ExportProductInstance)
		{
			m_api->m_bp_mgr.FindAssociatedBPInst(inInst,ext,ext_rel);
			for(i=0;i<ext_rel.Size;i++)
			{
				inst=ext_rel[i];
				m_array.Add(inst);
				aplExtent bp_context;
				m_data->GetAttr(inst, m_api->m_bp_mgr.a_bp_inst_ref_frames_of_reference, bp_context);
				m_array.Append(bp_context);
				
				m_data->GetAttr(inst,m_api->m_bp_mgr.a_bp_inst_ref_process,obj);
				ExportBP(obj);
			}
		}
		DEC_EXP_POS;

		return true;
	}
	else
	{
		m_data->GetAttr(inInst, m_api->m_bp_mgr.a_bp_type, type);
		if(type)
			m_array.Add(type);
	}
	
	if(-1!=m_exported_bp.Find(inInst)){
		DEC_EXP_POS;
		return true;
	}
	
	m_api->m_bp_mgr.LoadBPInfo(inInst);
	m_exported_bp.Add(inInst);

	LoadInstanceTree(inInst, m_array, this);
	
	if(m_ExportBPRes)
	{
		aplExtent extRes;
		m_api->m_bp_mgr.LoadAllBPResources(inInst,extRes);
		for(i=0;i<extRes.Size;i++)
		{
			inst=extRes[i];
			LoadInstanceTree(inst, m_array,this);

			m_data->GetAttr(inst,m_api->m_bp_mgr.a_bp_res_object,obj);
			if(obj!=0) ExportInstance(obj, 0, true);

			if(m_ExportProductCharacteristics) ExportCharacteristic(inst);
			if(m_ExportAssDocuments)ExportDocument(inst,m_OutPath);
			if(m_ExportApproval) m_exported_items_4_approval.Add(inst);
		}
	}
	if(m_ExportProductCharacteristics) ExportCharacteristic(inInst);
	if(m_ExportAssDocuments)ExportDocument(inInst,m_OutPath);
	if(m_ExportApproval) m_exported_items_4_approval.Add(inInst);
	if(m_ExportProductInstance)
	{
		CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
		int i=ld.AddQuery(_T('b'), inInst->GetId(), m_api->m_bp_mgr.e_apl_bp_inst, m_api->m_bp_mgr.a_bp_inst_process, true);
			  ld.AddQuery(_T('d'), i, 0, m_api->m_bp_mgr.a_bp_inst_process, true);
		ld.LoadEx();
			
		aplExtent out_ext,ext_bp_inst;
		m_api->m_data.GetEntityExtent(m_api->m_bp_mgr.e_apl_bp_inst,out_ext);
		for(i=0;i<out_ext.Size;i++)
		{
			m_api->m_data.GetAttr(out_ext[i], m_api->m_bp_mgr.a_bp_inst_process,inst);
			if(inst==inInst)
				ExportBP(out_ext[i]);
		}
	}

	if(m_ExportBP)
	{
		CaplAggr aggr0;
		m_data->GetAttr(inInst,m_api->m_bp_mgr.a_bp_elements,aggr0);
		for(i=0;i<aggr0.GetSize();i++)
		{
			aggr0.GetByIndex(i,inst);
			ExportBP(inst);
		}
	}
	if(m_ExportNotes) ExportNotes(inInst);
	DEC_EXP_POS;
	return true;
}
//********************************************************************************

bool CaplExchangeManager::ExportProductInst(CaplInstance *inInst)
{
	if(inInst==0)  return false;
	if(inInst->GetType()==0)  return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	
	INC_EXP_POS;
	m_array.Add(inInst);
	if(m_ExportNotes) ExportNotes(inInst);

	aplExtent rels, ext;


	if(m_api->m_data.IsKindOf(inInst, m_api->m_prd_inst_mgr.e_prd_inst))
	{
		m_api->m_prd_inst_mgr.LoadInsertedInstances(inInst, rels, ext);
		CaplInstance* pdf= NULL;
		m_api->m_data.GetAttr(inInst, m_api->m_prd_inst_mgr.a_prd_inst_pdf, pdf);
		if(m_exported_pdf.Find(pdf)==-1)
		{
			m_api->m_prd_mgr.LoadPrdInfo(pdf);
			ExportInstance(pdf, 0, true);
		}
		for(int i= 0; i<ext.GetSize(); i++)
			ExportInstance(ext[i], 0, true);			
		m_array.Append(rels);

		if(m_ExportBP)ExportBP(inInst);
		if(m_ExportProductCharacteristics) ExportCharacteristic(inInst);
		if(m_ExportAssDocuments)ExportDocument(inInst,m_OutPath);
		if(m_ExportApproval) m_exported_items_4_approval.Add(inInst);	
	}
	else if(m_api->m_data.IsKindOf(inInst, m_api->m_prd_inst_mgr.e_lot))
	{
		m_api->m_prd_inst_mgr.LoadIncomingLots(inInst, ext);
		for(int i= 0; i<ext.GetSize(); i++)
		{
			CaplInstance* pdf= NULL;
			m_api->m_data.GetAttr(ext[i], m_api->m_prd_inst_mgr.a_lot_pdf, pdf);
			if(m_exported_pdf.Find(pdf)==-1)
			{
				m_api->m_prd_mgr.LoadPrdInfo(pdf);
				ExportInstance(pdf, 0, true);
			}
			ExportInstance(ext[i], 0, true);
		}
		
		if(m_ExportBP)ExportBP(inInst);
		if(m_ExportProductCharacteristics) ExportCharacteristic(inInst);
		if(m_ExportAssDocuments)ExportDocument(inInst,m_OutPath);
		if(m_ExportApproval) m_exported_items_4_approval.Add(inInst);	
	}

	DEC_EXP_POS;
	return true;
}

bool CaplExchangeManager::ExportProduct(CaplInstance *inInst)
{
	if(inInst==0)  return false;
	if(inInst->GetType()==0)  return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	
	INC_EXP_POS;

	if(m_ExportNotes) ExportNotes(inInst);
	int i,j;
	aplExtent ext0, a_pd, a_next, ext_eff;
	CaplInstance * inst0=0, * inst1=0, * pdf=0;
	CaplInstance * pdfor=0, * pd=0, * prd=0;

	if(m_data->IsKindOf(inInst,m_api->m_prd_mgr.e_prd)) 
	{
		if(m_exported_prd.Find(inInst)==-1)
		{
			m_exported_prd.Add(inInst);
			
			m_api->m_prd_mgr.LoadPrdInfo(inInst);
			m_array.Add(inInst);
			m_api->m_prd_mgr.GetAllProductVersion(inInst, ext0);
			for(i=0;i<ext0.GetSize();i++)
				ExportProduct(ext0[i]);
			ext0.Clear();
			if(m_ExportProductCharacteristics) ExportCharacteristic(inInst);
			if(m_ExportAssDocuments)ExportDocument(inInst,m_OutPath);
			if(m_ExportApproval) m_exported_items_4_approval.Add(inInst);
			if(m_ExportBP) ExportBP(inInst);
		}
		DEC_EXP_POS;
		return true;
	}
	else if(m_data->IsKindOf(inInst,m_api->m_prd_mgr.e_pdf)) 
	{
		if(m_exported_pdf.Find(inInst)==-1)
		{
			m_exported_pdf.Add(inInst);
			m_array.Add(inInst);
			m_data->GetAttr(inInst,m_api->m_prd_mgr.a_pdf_prd,prd);
			if(prd==0) {
				DEC_EXP_POS;
				return false;
			}
			m_array.Add(prd);

			if(m_ExportSubProduct)
			{
				m_api->m_prd_mgr.LoadAllSubProduct(0,0,inInst,a_next,a_pd);
				for(i=0; i<a_next.GetSize();i++)
				{
					LoadInstanceTree(a_next[i], m_array, this);
					m_api->m_prd_mgr.FindAllPDFEffectiviti(a_next[i],ext_eff,true);
					for(j=0;j<ext_eff.GetSize();j++){
						LoadInstanceTree(ext_eff[j],m_array, this);
					}
					
					aplExtent pd_context;
					m_data->GetAttr(a_next[i],m_api->m_prd_mgr.a_pdr_frames_of_reference, pd_context);
					m_array.Append(pd_context);

					m_data->GetAttr(a_next[i],m_api->m_prd_mgr.a_pdr_r_ted,inst0);
					ExportProduct(inst0);
				}
			}
			if(m_ExportProductMaterial)
			{
				m_api->m_prd_mgr.LoadAllZagotov(inInst,a_next,a_pd,true,true);
				for(i=0; i<a_next.GetSize();i++)
				{
					LoadInstanceTree(a_next[i], m_array, this);
					m_data->GetAttr(a_next[i],m_api->m_prd_mgr.a_pdr_r_ted,inst0);
					ExportProduct(inst0);
				}
			}
			if(m_ExportProductCharacteristics) ExportCharacteristic(inInst);
			if(m_ExportAssDocuments)ExportDocument(inInst,m_OutPath);
			if(m_ExportApproval) m_exported_items_4_approval.Add(inInst);
			if(m_ExportProductInstance)
			{
				aplExtent prd_insts;
				m_api->m_prd_inst_mgr.FindAllPdfInstances(inInst, prd_insts);
				for(i= 0; i<prd_insts.GetSize(); i++)
					ExportProductInst(prd_insts[i]);
				m_api->m_prd_inst_mgr.FindAllPdfLoot(inInst, prd_insts);
				for(i= 0; i<prd_insts.GetSize(); i++)
					ExportProductInst(prd_insts[i]);		
			}

			if(m_ExportBP) ExportBP(inInst);
		}
		DEC_EXP_POS;
		return true;
	}
	DEC_EXP_POS;
	return false;
}
//********************************************************************************

bool CaplExchangeManager::ExportCategory(CaplInstance *category)
{
	if(category==0) return false;
	if(category->GetType()==0) return false;
	if(category->GetAccessmode()>aplRO) return false;

	CaplInstance * inst=0, * sub_inst=0, * prd=0;
	aplExtent ext, ext1, aggr;
	int i, k;

	if(m_ExportNotes) ExportNotes(category);
	if(!m_data->IsKindOf(category,m_api->m_categ_mgr.e_categ))return false;
	m_array.Add(category);

	INC_EXP_POS;

	if(m_ExportAssDocuments) ExportDocument(category,m_OutPath);

//	if(include_contents==true)
	{
		m_api->m_categ_mgr.GetCategoryContents(category, aggr);
		for(k=0;k<aggr.GetSize();k++) ExportProduct(aggr[k]);
	}
	
/*	m_api->m_data.GetAttr(category, m_api->m_categ_mgr.a_categ_act, actVer);
	if(0==actVer->attrs.GetSize()) m_api->m_categ_mgr.LoadCategoryInfo(actVer);
	m_array.Add(actVer);*/
	
	if(m_ExportProductCharacteristics) ExportCharacteristic(category);
	if(m_ExportAssDocuments)ExportDocument(category,m_OutPath);

	if(m_ExportSubCategory)
	{
		//а то подкатегории не читаются.
		aplExtent rels;
		m_api->m_categ_mgr.GetAllSubCategory2(category, ext, rels);	
		m_data->GetEntityExtentBN(_T("product_category_relationship"),ext);
		
		for(i=0; i<ext.GetSize(); i++)
		{
			m_data->GetAttrBN(ext[i],_T("category"),inst);
			if(inst!=category) continue;
			
			m_data->GetAttrBN(ext[i], _T("sub_category"), sub_inst);
			if(sub_inst==0) continue;
			
			m_array.Add(ext[i]);
			ExportCategory(sub_inst);
		}
	}
	DEC_EXP_POS;
	return true;
}
//********************************************************************************

bool CaplExchangeManager::ExportAppearance(CaplInstance* inInst)
{
	if (!inInst)
		return false;

	if (!m_data->IsKindOfBN(inInst, _T("apl_product_appearance")))
		return false;

	CaplInstance *pProductPDF = NULL;

	m_api->m_data.GetAttrBN(inInst, _T("product"), pProductPDF);
	m_api->LoadItemInfo(pProductPDF);
	m_array.Add(inInst);
	m_array.Add(pProductPDF);

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

bool CaplExchangeManager::ExportAppLimitRel(CaplInstance* inInst)
{
	if (!inInst)
		return false;

	if (!m_data->IsKindOfBN(inInst, _T("apl_appearance_requirement_limit_relationship")))
		return false;

	CaplInstance *pAppearance = NULL;
	CaplInstance *pLimit = NULL;

	m_api->m_data.GetAttrBN(inInst, _T("appearance"), pAppearance);
	m_api->m_data.GetAttrBN(inInst, _T("limit"), pLimit);
	m_array.Add(inInst);
	m_array.Add(pAppearance);
	m_array.Add(pLimit);

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

bool CaplExchangeManager::ExportAppLimit(CaplInstance* inInst)
{
	if (!inInst)
		return false;

	if (!m_data->IsKindOfBN(inInst, _T("apl_appearance_requirement_limit")))
		return false;

	m_array.Add(inInst);

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

bool CaplExchangeManager::ExportAppOptionRel(CaplInstance* inInst)
{
	if (!inInst)
		return false;

	if (!m_data->IsKindOfBN(inInst, _T("apl_appearance_requirement_relationship")))
		return false;

	CaplInstance *pAppearance = NULL;
	CaplInstance *pOption = NULL;

	m_api->m_data.GetAttrBN(inInst, _T("appearance"), pAppearance);
	m_api->m_data.GetAttrBN(inInst, _T("option"), pOption);
	m_array.Add(inInst);
	m_array.Add(pAppearance);
	m_array.Add(pOption);

	ExportConfigartionOptions(pOption);

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

bool CaplExchangeManager::ExportOptionValue(CaplInstance* inInst)
{
	if (!inInst)
		return false;

	if (!m_data->IsKindOfBN(inInst, _T("apl_composition_requirement_enumeration_item")))
		return false;

	m_array.Add(inInst);

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

bool CaplExchangeManager::ExportComplectation(CaplInstance* inInst)
{
	if (!inInst)
		return false;

	if (!m_data->IsKindOfBN(inInst, _T("apl_appearence_composition")))
		return false;

	aplExtent extReqDefs;

	m_api->m_data.GetAttrBN(inInst, _T("requirement_definitions"), extReqDefs);
	m_api->LoadExtentInfo(extReqDefs);
	m_array.Add(inInst);
	m_array.Append(extReqDefs);

	for (int iIndex = 0; iIndex < extReqDefs.GetSize(); iIndex++)
	{
		CaplInstance *pReqDef = extReqDefs[iIndex];
		CaplInstance *pOption = NULL;
		CaplInstance *pOptionValue = NULL;

		m_api->m_data.GetAttrBN(pReqDef, _T("requirement"), pOption);
		m_api->m_data.GetAttrBN(pReqDef, _T("value"), pOptionValue);

		m_array.Add(pOption);
		m_array.Add(pOptionValue);
	}

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

bool CaplExchangeManager::ExportClassifierAssociation(CaplInstance* inInst)
{
	if (!inInst)
		return false;

	if (!m_data->IsKindOfBN(inInst, _T("apl_classifier_association")))
		return false;

	m_array.Add(inInst);

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

bool CaplExchangeManager::ExportConfigartionOptions(CaplInstance* inInst)
{
	aplExtent aeItems;
	if (!inInst)
		return false;
	if (!m_data->IsKindOfBN(inInst,_T("apl_composition_requirement_enumeration")))
		return false;
	CaplInstance* ciDefVal = NULL;
	m_api->m_data.GetAttrBN(inInst,_T("values"),aeItems);
	m_api->LoadExtentInfo(aeItems);
	m_array.Add(inInst);
	m_array.Append(aeItems);
	return true;
}
//********************************************************************************

bool CaplExchangeManager::ExportClassifier(CaplInstance *classifier)
{
	if(classifier==0) return false;
	if(classifier->GetType()==0) return false;
	if(classifier->GetAccessmode()>aplRO) return false;

	CaplInstance * charact=0, *type=0,*system=0;
	aplExtent ext, ext1, aggr;
	int i;

	if(!m_data->IsKindOf(classifier,m_api->m_classifier_mgr.e_apl_classifier_level) && 
		!m_data->IsKindOf(classifier,m_api->m_classifier_mgr.e_apl_classifier_system))
	{
		return false;
	}
	// справочники могут зацикливаться - их надо проверять на уникальность
	for(i=0;i<m_array.GetSize();i++){
		if(m_array[i]==classifier){return true;}
	}

	if(m_ExportNotes) ExportNotes(classifier);

	m_api->m_classifier_mgr.LoadClassifierInfo(classifier);
	m_array.Add(classifier);


	INC_EXP_POS;
	
	// содержимое, система уровня
	if(m_data->IsKindOf(classifier,m_api->m_classifier_mgr.e_apl_classifier_level)){
		m_api->m_classifier_mgr.GetSubItems(classifier,ext,&ext1);
		for(int i=0;i<ext.Size;i++){
			ExportInstance(ext[i],0,true);
		}
		m_array.Append(ext1);
		m_data->GetAttr(classifier,m_api->m_classifier_mgr.a_apl_classifier_level_system, system);
		ExportClassifier(system);
	}
	// входящие справочники/справочники нижнего уровня
	if(m_ExportClassifiers)
	{
		if(m_data->IsKindOf(classifier,m_api->m_classifier_mgr.e_apl_classifier_system)){
			m_api->m_classifier_mgr.LoadSubClassifierSystems(classifier, ext);
			for(int i=0;i<ext.Size;i++) ExportClassifier(ext[i]);
		}
	}
	m_api->m_classifier_mgr.LoadSubClassifierLevels(classifier, ext);
	for(i=0;i<ext.Size;i++) ExportClassifier(ext[i]);

	// Характеристики & type
	m_api->m_classifier_mgr.GetClassifierCharacteristic(classifier,ext);
	for(i=0;i<ext.Size;i++){
		m_array.Add(ext[i]);
		m_data->GetAttr(ext[i],m_api->m_charact_mgr.a_apl_characteristic_and_type_characteristic,charact);
		ExportCharacteristic(charact);
		m_data->GetAttr(ext[i],m_api->m_charact_mgr.a_apl_characteristic_and_type_type,type);
		m_array.Add(type);
	}

	// эскиз
	CaplValue *value;
	CString name_temp_file,name_stored_file,temp;
	
	if(m_data->IsKindOf(classifier,m_api->m_classifier_mgr.e_apl_classifier_level))
	{
		m_data->GetAttr(classifier,m_api->m_classifier_mgr.a_apl_classifier_level_esquisse_name, &value);
	}else
	{
		m_data->GetAttr(classifier,m_api->m_classifier_mgr.a_apl_classifier_system_esquisse_name, &value);
	}
	if(value!=0 && value->type!=aplNOTYPE)
	{
		m_changed_values.Add(value);
		CString buf; value->Get(buf);
		m_changed_values_old.Add(buf);

		m_api->m_classifier_mgr.GetClassifierEsquisse(classifier,name_temp_file);
		buf=GetOnlyFileName(name_temp_file);
		name_stored_file=m_OutPath+buf;
		CopyFile(name_temp_file,name_stored_file,FALSE);
		m_changed_values_new.Add(buf);
	}
	
	
	// формы - пока неясно
//	m_data->GetAttr(inInst,


	DEC_EXP_POS;
	return true;
}
//********************************************************************************
bool CaplExchangeManager::ExportFolder(CaplInstance * inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	aplExtent ext,out_ext,out_rel;
	int i;
	INC_EXP_POS;
	// папки могут зацикливаться - их надо проверять на уникальность
	for(i=0;i<m_array.GetSize();i++){
		if(m_array[i]==inInst){return true;}
	}
	
	m_array.Add(inInst);
	m_api->m_folder_mgr.GetFolderContents(inInst,ext);
	m_api->m_doc_mgr.FindAssociatedDocuments(inInst,out_ext,out_rel);
	ext.Append(out_ext);

	for(i=0;i<ext.Size;i++) ExportInstance(ext[i],0,true);

	if(m_ExportFolders)
	{
		m_api->m_folder_mgr.GetAllSubFolder(inInst,ext);
		for(int i=0;i<ext.Size;i++) ExportFolder(ext[i]);
	}
	DEC_EXP_POS;
	return true;
}
//********************************************************************************
bool CaplExchangeManager::ExportProject(CaplInstance * inInst)
{
	if(!m_ExportPrj) return true;
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	aplExtent ext;
	int i;
	INC_EXP_POS;

	if(!m_data->IsKindOf(inInst,m_api->m_project_mgr->e_project))
	{
		return false;
	}

	//m_array.Add(inInst);
	/*m_data->GetAttr(inInst,m_api->m_project_mgr->a_project_content,ext);
	for(i=0;i<ext.Size;i++) ExportProject(ext[i]);
	CaplAttrValue tst_values [5];
	tst_values[0].value.Set(inInst);
	tst_values[0].attr=m_api->m_project_mgr->a_project_adm_ver_project;
	m_data->NET_FindInstancesWithAttrValues(m_api->m_project_mgr->e_project_adm_ver,1,&tst_values[0],ext,false);
	for(i=0;i<ext.Size;i++) m_array.Add(ext[i]);*/

	aplExtent ext_1,ext_2,ext_po_all;
	ext_1.Add(inInst);
	m_api->m_project_mgr->GetAllSubProject(ext_1,ext_2,true,true,true);
	ext_2.Add(inInst);
	m_api->m_project_mgr->LoadProjectInfo(ext_2);

	for(i=0;i<ext_2.Size;i++)
	{
		CaplInstance *prj=ext_2[i];
		LoadInstanceTree(prj,m_array, this);
		// Выгружаем характеристики для исполнителей, кураторови заказчиков
		//if(m_ExportProductCharacteristics)
		{
			CaplInstance *po;
			aplExtent ext_po;
			m_data->GetAttr(prj,m_api->m_project_mgr->a_project_co_executors,ext_po);
			ext_po_all.Append(ext_po);
			m_data->GetAttr(prj,m_api->m_project_mgr->a_project_executors,ext_po);
			ext_po_all.Append(ext_po);
			m_data->GetAttr(prj,m_api->m_project_mgr->a_project_kurator,po);
			if(po) ext_po_all.Add(po);
			m_data->GetAttr(prj,m_api->m_project_mgr->a_project_customer,po);
			if(po) ext_po_all.Add(po);
		}
		//CaplInstance *ver;
		//m_data->GetAttr(prj,m_api->m_project_mgr->a_project_act_adm_version,ver);
		//if (ver!=0) m_array.Add(ver);
	}

	aplExtent ext_rel;
	m_api->m_project_mgr->LoadProjectsSequenceRelations(ext_2,ext_rel,false);
	m_array.Append(ext_rel);

	if(m_ExportPrjVer)
	{
		CaplLoadData ld_projects(m_data,DEF_SOURCE);
		for(i=0;i<ext_2.Size;i++)
		{
			ld_projects.AddQuery(0,ext_2[i],true);
		}
				
		ld_projects.AddQuery(_T('r'),0,m_api->m_project_mgr->e_project_adm_ver,m_api->m_project_mgr->a_project_adm_ver_project,true,true);
		aplExtent ext_ver;
		ld_projects.LoadEx(true, &ext_ver);
		for(i=0;i<ext_ver.Size;i++)
		{
			if(m_api->m_data.IsKindOf(ext_ver[i],m_api->m_project_mgr->e_project_adm_ver))
				LoadInstanceTree(ext_ver[i],m_array, this);
		}
	}
	

	if(m_ExportProductCharacteristics)
	{
		ExportCharacteristic(ext_po_all);
		ExportCharacteristic(ext_2);
	}

	if(m_ExportFolders)
	{
		m_api->m_folder_mgr.GetAllSubFolder(inInst,ext);
		for(int i=0;i<ext.Size;i++) ExportFolder(ext[i]);
	}

	if(m_ExportAssDocuments)
	{
		for(i=0;i<ext_2.Size;i++)
		{ 
			ExportDocument(ext_2[i],m_OutPath);
		}
	}
	if(m_ExportApproval) m_exported_items_4_approval.Append(ext_2);
	DEC_EXP_POS;
	return true;
}
//********************************************************************************
bool ExportItemApproval(CaplInstance * item)
{
	if(item==0) return false;
	if(item->GetType()==0) return false;


	return true;
}

//********************************************************************************
bool CaplExchangeManager::ExportDocument(CaplInstance *inInst, const TCHAR* path)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;

	CaplInstance * inst=0, * instAss=0, * instAct=0;
	CaplInstance *stor_doc= NULL,*dt= NULL;
	
	aplExtent extDoc, extRel;
	int i;
	
	CString fileName,s_id,s_name, path1=path;
	CaplValue *value=0;
	
	INC_EXP_POS;

	if(m_ExportNotes) ExportNotes(inInst);
	if(m_data->IsKindOf(inInst,m_api->m_doc_mgr.e_doc))
	{
		if(m_exported_doc.Find(inInst)==-1)
		{

			m_exported_doc.Add(inInst);
		
			m_api->m_doc_mgr.LoadDocInfo(inInst);
			m_data->GetAttr(inInst,m_api->m_doc_mgr.a_apl_doc_active, instAct);
//			m_data->GetAttr(inInst,m_api->m_doc_mgr.a_doc_id, s_id);
		}

		// экспортируем реквизиты всех версий документа
		CaplInstance *ciEntry  =0;
		aplExtent aeRev, aeEntriesVal, aeEntries;
		m_api->m_doc_mgr.LoadAllDocumentRevision(inInst, aeRev);

		for(int i=0; i<aeRev.Size; ++i)
		{
			m_api->m_data.GetAttr(aeRev[i], m_api->m_doc_mgr.a_apl_doc_rev_entries, aeEntriesVal);

			m_api->LoadExtentInfo(aeEntriesVal);
			for(int j=0; j<aeEntriesVal.Size; j++)
			{
				m_api->m_data.GetAttr(aeEntriesVal[j], m_api->m_doc_mgr.a_doc_entry_val_entry, ciEntry);
				aeEntries.Add(ciEntry);
			}

			m_api->LoadExtentInfo(aeEntries);
			m_array.Append(aeEntries);
			m_array.Append(aeEntriesVal);
		}
	}
	else if(m_api->m_data.IsKindOf(inInst, m_api->m_doc_mgr.e_apl_doc_rev))
	{
		instAct= inInst;

		// экспортируем реквизиты версии
		CaplInstance *ciEntry  =0;
		aplExtent aeRev, aeEntriesVal, aeEntries;
		m_api->m_data.GetAttr(inInst, m_api->m_doc_mgr.a_apl_doc_rev_entries, aeEntriesVal);

		m_api->LoadExtentInfo(aeEntriesVal);
		for(int j=0; j<aeEntriesVal.Size; j++)
		{
			m_api->m_data.GetAttr(aeEntriesVal[j], m_api->m_doc_mgr.a_doc_entry_val_entry, ciEntry);
			aeEntries.Add(ciEntry);
		}

		m_api->LoadExtentInfo(aeEntries);
		m_array.Append(aeEntries);
		m_array.Append(aeEntriesVal);
	}

	if(instAct)
	{
		m_api->m_doc_mgr.GetFileName(instAct, fileName);

		m_data->GetAttr(inInst,m_api->m_doc_mgr.a_doc_kind, dt);
		if(dt!=0 && m_array.Find(dt)==-1) m_array.Add(dt);
		
		m_data->GetAttr(instAct,m_api->m_doc_mgr.a_apl_doc_rev_access_form, stor_doc);
		if(stor_doc)
		{
			m_array.Add(stor_doc);
			/*s_name=s_id;s_name+=_T("_");*/ //кривое наименование получается
			s_name+=fileName;
			
			// Преобразование вредных символов
			for(i=0;i<s_name.GetLength();i++)
			{
				if(s_name[i]==_T('"'))
					s_name.SetAt(i,_T('\''));
				else if(s_name[i]==_T('/') )
					s_name.SetAt(i,_T(' '));
			}

			if(m_data->IsKindOf(stor_doc,m_api->m_doc_mgr.e_apl_stored_document))
				m_data->GetAttr(stor_doc,m_api->m_doc_mgr.a_apl_stored_document_file_name, &value);
			else if(m_data->IsKindOf(stor_doc,m_api->m_doc_mgr.e_apl_assigned_document))
				m_data->GetAttr(stor_doc,m_api->m_doc_mgr.a_apl_assigned_document_location_path, &value);
		}

		if(value!=0)
		{
/*
			m_changed_values.Add(value);
			CString buf; value->Get(buf);
			m_changed_values_new.Add(s_name);
			m_changed_values_old.Add(buf);
			path1+=s_name;
			m_api->m_doc_mgr.LoadRevision(instAct,path1);
*/
			m_api->m_doc_mgr.LogDocAccess(inInst,_T("CaplExchangeManager"),_T(""));
			LoadInstanceTree(inInst, m_array, this);
			if(m_ExportApproval) m_exported_items_4_approval.Add(instAct);
			if(inInst!=instAct)	ExportDocument(instAct,path); // экспортим связанные документы активной версии
			if(m_ExportProductCharacteristics)
				if(inInst!=instAct)	ExportCharacteristic(instAct);
		}
		
		//Экспорт эскизов
		aplExtent pics;
		m_api->m_data.GetAttr(instAct, m_api->m_doc_mgr.a_apl_doc_rev_pictures, pics);
		m_array.Append(pics);
	}

	if(m_ExportProductCharacteristics) ExportCharacteristic(inInst);

	if(m_ExportAssDocuments)
	{
		aplExtent items;
		items.Add(inInst);
		CaplInstance *prd;
		if(m_api->m_data.IsKindOf(inInst, m_api->m_prd_mgr.e_pdf))
		{
			m_api->m_data.GetAttr(inInst, m_api->m_prd_mgr.a_pdf_prd, prd);
			items.Add(prd);
		}
		m_api->m_doc_mgr.FindAssociatedDocuments(items, extDoc, extRel);
		for(i=0;i<extRel.GetSize();i++)
		{
			CaplInstance *rel=extRel[i];

			CaplInstance *inst1, *inst2;
			m_data->GetAttr(rel, m_api->m_doc_mgr.a_apl_doc_ref_item, inst1);
			m_data->GetAttr(rel, m_api->m_doc_mgr.a_apl_doc_ref_doc, inst2);
			if(inst1==inst2)  
				continue; // Игнорируем вхождение самого в себя (как у Созвездия)

			m_array.Add(rel);
			aplExtent doc_cont;
			m_data->GetAttr(extRel[i], m_api->m_doc_mgr.a_doc_rel_frames_of_reference, doc_cont);
			m_array.Append(doc_cont);
			
			m_data->GetAttrBN(extRel[i],_T("assigned_document"), instAss);
			ExportDocument(instAss,path);
		}
	}
	
	DEC_EXP_POS;
	return true;
}




bool CaplExchangeManager::ExportCharacteristic(aplExtent &ext)
{
	if(ext.GetSize()<1) return false;

	aplExtent extChar,ext_out_group;

	m_api->m_charact_mgr.FindAssociatedCharacteristic(ext, extChar,ext_out_group,true,false,false,true,true);

	INC_EXP_POS;
	//if(m_ExportNotes) ExportNotes(inInst);
	int i;
	for(i=0; i<extChar.GetSize();i++)
	{
		LoadInstanceTree(extChar[i], m_array,this);
		//if(m_ExportAssDocuments)ExportDocument(extChar[i],m_OutPath);
		//if(m_ExportProductCharacteristics) ExportCharacteristic(extChar[i]);
		if(m_ExportApproval) m_exported_items_4_approval.Add(extChar[i]);

		/*if(m_ExportApproval)
		{
			CaplInstance *act_rev;
			m_data->GetAttr(extChar[i],m_api->m_charact_mgr.a_apl_charact_val_act_ver,act_rev);
			if(act_rev!=0) m_exported_items_4_approval.Add(act_rev);
		}*/
	}
	DEC_EXP_POS;
	return true;
}

bool CaplExchangeManager::ExportCharacteristic(CaplInstance *inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;

	aplExtent extChar, extRel,extGroup;
	int i;

	INC_EXP_POS;
	if(m_ExportNotes) ExportNotes(inInst);
	m_api->m_charact_mgr.FindAssociatedCharacteristic(inInst,extChar,extGroup);

	for(i=0; i<extChar.GetSize();i++)
	{
		// 2026.03.23 ЯАИ: затычка на случай, если не зачитаны справочники
		if(m_api->m_data.IsKindOf(extChar[i],m_api->m_charact_mgr.e_apl_reference_value))
		{
			CaplInstance *val=0;
			m_data->GetAttr(extChar[i], m_api->m_charact_mgr.a_apl_reference_val, val);
			m_api->LoadItemInfo(val);
		}

		LoadInstanceTree(extChar[i], m_array,this);
		if(m_ExportAssDocuments)ExportDocument(extChar[i],m_OutPath);
		if(m_ExportProductCharacteristics) ExportCharacteristic(extChar[i]);

		if(m_ExportApproval)
		{
			CaplInstance *act_rev;
			m_data->GetAttr(extChar[i],m_api->m_charact_mgr.a_apl_charact_val_act_ver,act_rev);
			if(act_rev!=0) m_exported_items_4_approval.Add(act_rev);
		}
	}
	DEC_EXP_POS;
	return true;
}

bool CaplExchangeManager::ExportInstance(CaplInstance *inst, 
										 const TCHAR *filename,bool bRecursive,SParamExchangeManager* params,CString *err_mess)
{
	CString name;

	bool bEmptyFileName=false;
	
	if(0==filename)bEmptyFileName=true;
	else if(_T('\0')==filename[0])bEmptyFileName=true;
	
	if(bEmptyFileName)
	{
		if(m_api->m_data.IsKindOf(inst,m_api->m_prd_mgr.e_pdf)) name=m_api->m_prd_mgr.GetProductId(inst);
		else name=m_api->GetItemName(inst);

		name.Replace(_T('\\'),_T('_'));
		name.Replace(_T('/'),_T('_'));
		name.Replace(_T('*'),_T('_'));
		name.Replace(_T('?'),_T('_'));
		name.Replace(_T(':'),_T('_'));
		name.Replace(_T(".."),_T("_"));
		
		filename=LPCTSTR(name);
	}


	aplExtent ext;
	ext.Add(inst);
	return ExportExtent(ext,filename,bRecursive,params,err_mess);
}

bool CaplExchangeManager::ExportExtent(aplExtent &ext, 
										 const TCHAR *filename,bool bRecursive,SParamExchangeManager* params,CString *err_mess)
{
	if(m_data==0) return false;
	if(ext.GetSize()==0) return false;
	CaplInstance *inst=0;
	int i;

	bool bSaveFile=false;
	bool bFormateETDPacket = false;
	bool bDeleteTempraryFiles = false;

	if(bRecursive!=true)
	{
		m_array.Clear();
		m_exported_prd.Clear();
		m_exported_pdf.Clear();
		m_exported_doc.Clear();
		m_exported_bp.Clear();
		m_exported_bp_res.Clear();
		m_exported_obj_inst.Clear();

		m_exported_items_4_approval.Clear();
		
		if(params!=0)
		{
			m_ExportSubCategory=params->m_ExportSubCategory;
			m_ExportClassifiers=params->m_ExportClassifiers;
			m_ExportAssDocuments=params->m_ExportAssDocuments;
			m_ExportProductCharacteristics=params->m_ExportProductCharacteristics;
			m_ExportRequirments=params->m_ExportRequirments;
			m_ExportProductInstance= params->m_ExportProductInstance;
			m_ExportProductMaterial=params->m_ExportProductMaterial;
			m_ExportSubProduct=params->m_ExportSubProduct;
			m_ExportApproval=params->m_ExportApproval;
			m_ExportPrj=params->m_ExportPrj;	
			m_ExportPrjVer=params->m_ExportPrjVer;	
			m_ExportFolders=params->m_ExportFolders;
			m_ExportBP=params->m_ExportBP;
			m_ExportBPRes=params->m_ExportBPRes;
			m_IgnoreAddDict=params->m_bIgnoreAddDict;
			m_OutFile= filename;
			bFormateETDPacket = (params->m_bFormateETDPacket==TRUE);
			bDeleteTempraryFiles = (params->m_bFormateETDPacket==TRUE);
		}
		else if(m_api->m_ModeInteractive)
		{
			CaplSetResourceHandle setres(module_inst);

			CExportInstanceDialog dlg;
			dlg.m_exp_categ=m_ExportSubCategory;
			dlg.m_exp_classif=m_ExportClassifiers;
			dlg.m_exp_doc=m_ExportAssDocuments;
			dlg.m_exp_prd_charact=m_ExportProductCharacteristics;
			dlg.m_exp_req=m_ExportRequirments;
			dlg.m_exp_prd_mater=m_ExportProductMaterial;
			dlg.m_exp_prd_struct=m_ExportSubProduct;
			dlg.m_ignore_add_dict=m_IgnoreAddDict;
			dlg.m_exp_appr=m_ExportApproval;
			dlg.m_exp_prj=m_ExportPrj;
			dlg.m_exp_prj_ver=m_ExportPrjVer;
			dlg.m_exp_folder=m_ExportFolders;
			dlg.m_exp_bp=m_ExportBP;
			dlg.m_exp_bpres=m_ExportBPRes;


			CString sOldFileName, sFileName=filename;
			{
				CRegKey key;
				TCHAR buf[1024];
				DWORD len=1024;
				memset(buf,0,1024);
				if(key.Open(HKEY_CURRENT_USER,
					_T("Software\\CALS Centre \"Applied Logistic\"\\PDM STEP Suite\\options"))
					!=ERROR_SUCCESS) return FALSE;
#if _MSC_VER >= 1400
				if(key.QueryStringValue(_T("LastExportedFile"),buf,&len)==ERROR_SUCCESS)
#else
				if(key.QueryValue(buf,_T("LastExportedFile"),&len)==ERROR_SUCCESS)
#endif
				{
					buf[len]=0;
					sOldFileName=buf;
				}
			}
			if(sFileName==_T("")) sFileName=sOldFileName;
			else
			{
				// Проверяем расширение и копируем из старого, если надо.
				
				CString sExt;
				int i_p=sFileName.ReverseFind(_T('.'));
				if(i_p>0)
				{
					sExt=sFileName.Right(sFileName.GetLength()-(i_p+1));

					sExt.MakeLower();

					if( !( sExt==_T("stp") || sExt==_T("std") || sExt==_T("std") || sExt==_T("txt") ))  sExt=_T("");
				}
				if(sExt==_T("")) 
				{
					// Копируем из старого
					i_p=sOldFileName.ReverseFind(_T('.'));
					if(i_p>0)
					{
						sExt=sOldFileName.Right(sOldFileName.GetLength()-(i_p+1));
						sFileName+=_T('.');
						sFileName+=sExt;
					}
				}
			}
			// Сохраняем путь
			int i_r=sFileName.ReverseFind(_T('\\'));
			if(i_r<0)
			{
				i_r=sOldFileName.ReverseFind(_T('\\'));
				if(i_r>=0) sFileName.Insert(0,sOldFileName.Left(i_r+1));
			}

			dlg.m_file_name=sFileName;


			if(dlg.DoModal()!=IDOK)  return false;

			m_ExportSubCategory=dlg.m_exp_categ;
			m_ExportClassifiers=dlg.m_exp_classif;
			m_ExportAssDocuments=dlg.m_exp_doc;
			m_ExportProductCharacteristics=dlg.m_exp_prd_charact;
			m_ExportRequirments=dlg.m_exp_req;
			m_ExportProductInstance= dlg.m_exp_prd_inst;
			m_ExportProductMaterial=dlg.m_exp_prd_mater;
			m_ExportSubProduct=dlg.m_exp_prd_struct;
			m_ExportApproval=dlg.m_exp_appr;
			m_ExportPrj=dlg.m_exp_prj;
			m_ExportPrjVer=dlg.m_exp_prj_ver;
			m_ExportFolders=dlg.m_exp_folder;
			m_ExportBP=dlg.m_exp_bp;
			m_ExportBPRes=dlg.m_exp_bpres;
			m_IgnoreAddDict=dlg.m_ignore_add_dict;
			m_OutFile=dlg.m_file_name;
			bFormateETDPacket = (bool)(dlg.m_bAutoFormateETDPacket==TRUE);
			bDeleteTempraryFiles = (bool)(dlg.m_bDeleteTempraryFiles==TRUE);

			m_ExportDocReqvToExtFile=dlg.m_bSaveRequsiteFiles;

			CRegKey key;
			if(key.Open(HKEY_CURRENT_USER,
				_T("Software\\CALS Centre \"Applied Logistic\"\\PDM STEP Suite\\options"))
				==ERROR_SUCCESS)
			{
#if _MSC_VER >= 1400
				key.SetStringValue(_T("LastExportedFile"),dlg.m_file_name);
#else
				key.SetValue(dlg.m_file_name,_T("LastExportedFile"));
#endif
			}


		}
		else m_OutFile= filename;

		m_OutPath=_T("");
		int i=m_OutFile.ReverseFind(_T('\\'));
		if(i>0) m_OutPath=m_OutFile.Left(i+1);

		CreateDirectory(m_OutPath, NULL);

		bSaveFile=true;
		m_changed_values.Clear();
		m_changed_values_new.RemoveAll();
		m_changed_values_old.RemoveAll();
	}
	
	long wait_dlg=0;
	int prgs_count=0;
	CaplSetResourceHandle setres(module_inst);
	CaplMgrPrgsDlg prgs_dlg;
	bool prevModeInteractive;
	if(bRecursive){
		INC_EXP_POS;
	}else{
		if(!m_api->m_data.GetHideMode()){
			//wait_dlg=aplStartWaitDlg(APL_T("Идет экспорт данных ..."));
			wait_dlg=1;
			prgs_dlg.Create(IDD_PRGS_DLG);
			prgs_dlg.ShowWindow(SW_SHOW);
			m_prgs_dlg=&prgs_dlg;
			prgs_count=0;
			m_recurs_level=1;
			prgs_dlg.SetText( APL_T("Рекурсивный разбор дерева"));prgs_dlg.SetRange(MAX_RANGE);
		}
		prevModeInteractive=m_api->m_ModeInteractive;
		m_api->SetModeInteractive(false);
	}

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

		if(m_data->IsKindOf(inst,m_api->m_doc_mgr.e_doc))
			ExportDocument(inst,m_OutPath);

		else if(m_data->IsKindOf(inst,m_api->m_categ_mgr.e_categ))
			ExportCategory(inst);

		else if(m_data->IsKindOf(inst,m_api->m_project_mgr->e_project))
			ExportProject(inst);
		
		else if(m_data->IsKindOf(inst,m_api->m_classifier_mgr.e_apl_classifier_level))
			ExportClassifier(inst);

		else if(m_data->IsKindOf(inst,m_api->m_classifier_mgr.e_apl_classifier_system))
			ExportClassifier(inst);
		
		else if(m_data->IsKindOf(inst,m_api->m_prd_mgr.e_prd))
			ExportProduct(inst);
		
		else if(m_data->IsKindOf(inst,m_api->m_prd_mgr.e_pdf))
			ExportProduct(inst);
		
		else if(m_data->IsKindOf(inst, m_api->m_prd_inst_mgr.e_prd_inst))
			ExportProductInst(inst);

		else if(m_data->IsKindOf(inst, m_api->m_prd_inst_mgr.e_lot))
			ExportProductInst(inst);

		else if(m_data->IsKindOf(inst,m_api->m_folder_mgr.e_folder))
			ExportFolder(inst);

		else if(m_data->IsKindOf(inst,m_api->m_bp_mgr.e_bp))
			ExportBP(inst);

		else if(m_data->IsKindOf(inst,m_api->m_bp_mgr.e_apl_bp_inst))
			ExportBP(inst);

		else if(m_data->IsKindOf(inst, m_api->m_appr_mgr.e_org))
			ExportOrg(inst);
		else if(m_data->IsKindOf(inst, m_api->m_appr_mgr.e_person))
			ExportOrg(inst);
		else if(m_data->IsKindOf(inst, m_api->m_appr_mgr.e_official))
			ExportOrg(inst);
		else if(m_data->IsKindOf(inst, m_api->m_appr_mgr.e_apl_user))
			ExportOrg(inst);
		else if(m_data->IsKindOf(inst, m_api->m_appr_mgr.e_po_role))
			ExportRoles(inst);
		else if(m_data->IsKindOf(inst, m_api->m_charact_mgr.e_apl_charact_value))
			ExportCharacteristic(inst);
		else if(m_data->IsKindOf(inst, m_api->m_charact_mgr.e_apl_charact))
			ExportCharacteristicType(inst);
		else if(m_data->IsKindOf(inst, m_api->m_options_mgr.e_str) || m_data->IsKindOf(inst, m_api->m_options_mgr.e_int) || m_data->IsKindOf(inst, m_api->m_options_mgr.e_inst))
			ExportOptions(inst);
		else if(m_data->IsKindOfBN(inst,_T("apl_logbook_access")))
			ExportLogbookAccess(inst);
		else if(m_data->IsKindOf(inst, m_api->m_message_mgr.e_message))
			ExportMessages(inst);
		else if(m_data->IsKindOf(inst, m_api->m_prd_inst_mgr.e_prd_inst_rel))
			ExportPrdInstRelations(inst);
		else if(m_data->IsKindOf(inst, m_api->m_doc_mgr.e_dt))
			ExportDocumentType(inst);
		else if(m_data->IsKindOf(inst, m_api->m_change_mgr.e_chng))
			ExportChange(inst);
		else if(m_data->IsKindOf(inst, m_api->m_req_mgr.e_requirement) && m_ExportRequirments)
			ExportRequirement(inst);
		else if (m_data->IsKindOfBN(inst, _T("apl_composition_requirement_enumeration")))
			ExportConfigartionOptions(inst);
		else if (m_data->IsKindOfBN(inst, _T("apl_composition_requirement_enumeration_item")))
			ExportOptionValue(inst);
		else if (m_data->IsKindOfBN(inst, _T("apl_product_appearance")))
			ExportAppearance(inst);
		else if (m_data->IsKindOfBN(inst, _T("apl_appearance_requirement_limit_relationship")))
			ExportAppLimitRel(inst);
		else if (m_data->IsKindOfBN(inst, _T("apl_appearance_requirement_relationship")))
			ExportAppOptionRel(inst);
		else if (m_data->IsKindOfBN(inst, _T("apl_appearance_requirement_limit")))
			ExportAppLimit(inst);
		else if (m_data->IsKindOfBN(inst, _T("apl_appearence_composition")))
			ExportComplectation(inst);
		else if (m_data->IsKindOfBN(inst, _T("apl_classifier_association")))
			ExportClassifierAssociation(inst);
		else
		{
			if(wait_dlg!=0){
				//aplEndWaitDlg(wait_dlg);								
				if(prgs_dlg.GetSafeHwnd())
				{
					prgs_dlg.ShowWindow(SW_HIDE);
					prgs_dlg.DestroyWindow();
				}
				m_prgs_dlg=0;				
				m_api->SetModeInteractive(m_api->m_ModeInteractive);
			}
			if(bRecursive!=true){
				m_api->SetModeInteractive(m_api->m_ModeInteractive);
				m_recurs_level--;
			}
			continue;
			//return false;
		}
	}
	ExportItemsApproval(m_exported_items_4_approval);


	bool retval=true;
	if(bRecursive)
	{
		DEC_EXP_POS;
	}
	else
	{
		if(m_array.GetSize()==0){
			retval=false;
		}
		else
		{
			if(m_prgs_dlg!=0){m_prgs_dlg->SetText( APL_T("Сохранение в файл..."));}
			SaveArr2File();

			if(m_ExportDocReqvToExtFile && 1==ext.GetSize())
			{
				// Делаем корневой файл реквизитов
				CaplInstance *minst=ext[0];
				if(m_api->m_data.IsKindOf(minst,m_api->m_prd_mgr.e_pdf))
				{
					CString sId,sName,sVer,sRLine,sEntries4File,sFilePath;
					m_api->m_data.GetAttr(minst,m_api->m_prd_mgr.a_pdf_id,sVer);
					CaplInstance *prd;
					m_api->m_data.GetAttr(minst,m_api->m_prd_mgr.a_pdf_prd,prd);
					if(0!=prd)
					{
						m_api->m_data.GetAttr(prd,m_api->m_prd_mgr.a_prd_id,sId);
						m_api->m_data.GetAttr(prd,m_api->m_prd_mgr.a_prd_name,sName);
					}

					sId.Replace(_T('\t'),_T(' '));
					sId.Replace(_T('\n'),_T(' '));
					sId.Replace(_T("\r"),_T(""));

					sName.Replace(_T('\t'),_T(' '));
					sName.Replace(_T('\n'),_T(' '));
					sName.Replace(_T("\r"),_T(""));

					sVer.Replace(_T('\t'),_T(' '));
					sVer.Replace(_T('\n'),_T(' '));
					sVer.Replace(_T("\r"),_T(""));
					
					sRLine.Format(_T("\"Обозначение\"=\"%s\""),sId);
					sEntries4File+=sRLine;

					sRLine.Format(_T("\n\"Наименование\"=\"%s\""),sName);
					sEntries4File+=sRLine;

					sRLine.Format(_T("\n\"Версия\"=\"%s\""), sVer);
					sEntries4File+=sRLine;

					sFilePath=m_OutFile+_T(".requisite");
					CaplStringFile RFile;
					if(RFile.Open(sFilePath,CaplFile::modeWrite|CFile::modeCreate,aplUTF8))
					{
						RFile.WriteString(sEntries4File);
						RFile.Flush();
						RFile.Close();
					}
				}
			}
		}

		if(wait_dlg!=0){
			//aplEndWaitDlg(wait_dlg);
			if(prgs_dlg.GetSafeHwnd())
			{
				prgs_dlg.ShowWindow(SW_HIDE);
				prgs_dlg.DestroyWindow();
			}
				m_prgs_dlg=0;
			m_api->SetModeInteractive(prevModeInteractive);
		}
	}

	if(retval && bFormateETDPacket)
	{
		return FormateWinETDPacket(m_OutFile, inst, bDeleteTempraryFiles,err_mess);
	}
	
	return retval;
}

bool CaplExchangeManager::SaveArr2File()
{
	CString s_extension; //=m_OutFile.Right(4);

	int i=m_OutFile.ReverseFind(_T('.'));
	if(i>0) s_extension=m_OutFile.Right(m_OutFile.GetLength()-i);
	else s_extension=_T(".std");

	s_extension.MakeLower();
	
	CString sPath = m_OutFile;
	if(sPath.ReverseFind(_T('\\'))>-1)
		sPath = sPath.Left(sPath.ReverseFind(_T('\\'))+1);
	
	CString buf=m_OutFile;
	
	int file_ind = 1;
	bool rval=true;
// 	CaplFictiveStepData fict_data;
// 	fict_data.Initialize(m_data,&m_array);
// 	for(i=0;i<m_changed_values.Size;i++)m_changed_values[i]->Set(m_changed_values_new[i]);

	CaplMap inst_map;
	CaplStepData file_data;
	if(m_api->m_data.IsConnected())
	{
		//CString FullDictName;
		//m_api->m_data.GetFullDictName(FullDictName);
		//file_data.LoadDictionaryFromFile(FullDictName);

		CaplDataBuf dBuf;
		m_api->m_data.SaveDictionaryToMemory(dBuf);
		file_data.LoadDictionaryFromMemory(dBuf);
	}
	else
	{
		file_data.m_DictionatyFolder=m_api->m_data.m_DictionatyFolder;
		file_data.LoadDictionary(m_api->m_data.m_CurSchema);
	}
	CopyData(m_array, inst_map, &file_data);

	//Сохранение файлов и замена атрибутов
	CaplAttr *pAttrHTML = file_data.GetAttrDefinitionBN(_T("apl_requirement"), _T("html"));
	CaplAttr *pAttrPictures = file_data.GetAttrDefinitionBN(_T("apl_requirement"), _T("pictures"));
	CaplAttr *pAttr = file_data.GetAttrDefinitionBN(_T("apl_stored_document"), _T("source"));
	CaplAttr *pApprovalAttr = file_data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("digital_sign_cert"));
	aplExtent stored_docs, aeApproval, requirements, ext_DocRev;
	CaplInstance *inst;
	CString sFileName;
	
	// для документов
	file_data.GetEntityExtentBN(_T("apl_stored_document"), stored_docs);
	file_data.GetEntityExtentBN(_T("apl_requirement"), requirements);


	for(i=0; i<stored_docs.GetSize(); i++)
	{
		CaplInstance *stor=stored_docs[i];
		inst = (CaplInstance*)inst_map.GetByOut((long)stor);

		// смотрим, если это документ - картинка из требования, то нужна дополнительная обрабокта
		aplExtent aePictures;
		CString html, oldSource;
		CaplInstance *ciPicturesReq = 0;

		for(int j=0; j<requirements.Size; j++)
		{
			file_data.GetAttr(requirements[j], pAttrPictures, aePictures);
			for(int z=0; z<aePictures.Size; z++)
			{
				if(aePictures[z] == stored_docs[i])
				{
					ciPicturesReq = requirements[j];
					break;
				}
			}

			if(ciPicturesReq) break;
		}

		if(inst==NULL || inst==(CaplInstance*)-1) continue;
		sFileName.Format(_T("apl_%d.blob"), file_ind++);

		if(m_ExportDocWithOriginalNames)
		{
			CString sNewFullName, sTmpBuf;
			CString sN0=sFileName;
			CString sOriginalFileName;
			file_data.GetAttrBN(stor, _T("file_name"), sOriginalFileName);
			int i_dir=sOriginalFileName.ReverseFind(_T('\\'));
			if(i_dir>=0) 
			{
				sTmpBuf=sOriginalFileName.Right(sOriginalFileName.GetLength()-(i_dir+1));
				sOriginalFileName=sTmpBuf;
			}

			int i_num=0, i_point=-1;
			sFileName=sOriginalFileName;
			while(true) // Подбираем имя файла для случая, если файл с таким именем уже есть
			{
				sNewFullName=sPath+sFileName;
				if(!CaplFile::IsFileExist(sNewFullName)) break;

				if(i_point<0) i_point=sOriginalFileName.ReverseFind(_T('.'));
				if(i_point<0) i_point=sOriginalFileName.GetLength();
				i_num++;
				sTmpBuf.Format(_T("(%i)"),i_num);
				sFileName=sOriginalFileName;
				sFileName.Insert(i_point,sTmpBuf);
			}
		}

		if(ciPicturesReq)
		{
			file_data.GetAttr(ciPicturesReq, pAttrHTML, html);
			file_data.GetAttr(stored_docs[i], pAttr, oldSource);
			m_api->m_req_mgr.ReplaceReferenceInHTML(html, oldSource, sFileName);
			file_data.PutAttr(ciPicturesReq, pAttrHTML, html);
		}

		if(m_api->m_data.NET_LoadBlob(inst, m_api->m_doc_mgr.a_apl_stored_document_source, sPath+sFileName))
			file_data.PutAttr(stored_docs[i], pAttr, sFileName);
		else
			file_data.PutAttr(stored_docs[i], pAttr, _T(""));
	}

	// для статусов
	CString blob;
	file_data.GetEntityExtentBN(_T("apl_approval_person_organization"), aeApproval);
	for(i=0; i<aeApproval.Size; ++i)
	{
		inst = (CaplInstance*)inst_map.GetByOut((long)aeApproval[i]);
		if(inst==NULL || inst==(CaplInstance*)-1) continue;

		file_data.GetAttr(inst, m_api->m_appr_mgr.a_appr_dg_sign_cert, blob);
		if(blob.IsEmpty()) continue;

		sFileName.Format(_T("apl_%d.blob"), file_ind++);
		if(m_api->m_data.NET_LoadBlob(inst, m_api->m_appr_mgr.a_appr_dg_sign_cert, sPath+sFileName))
			file_data.PutAttr(aeApproval[i], pApprovalAttr, sFileName);
		else
			file_data.PutAttr(aeApproval[i], pApprovalAttr, _T(""));
	}

	if(m_ExportDocReqvToExtFile)  // Сохраняем копию реквизитов в файл
	{
		file_data.GetEntityExtentBN(_T("apl_document_revision"), ext_DocRev);
		
		aplExtent ext_approvals;
		file_data.GetEntityExtentBN(_T("apl_approval_person_organization"), ext_approvals);
		CSortClass::SortExtentById(ext_approvals); // Для записи по номерам

		CaplAggrMap appr_map;

		for(i=0; i<ext_approvals.GetSize(); i++)
		{
			CaplInstance *appr=ext_approvals[i];
			CaplInstance *item;
			file_data.GetAttrBN(appr, _T("item"), item);
			appr_map.Add((long)item,appr);
		}

		aplExtent ext_req_values;

		CString sEntries4File,sRVal,sRName,sRLine,sFileName,sFilePath;
		CaplInstance *entry;

		for(i=0; i<ext_DocRev.GetSize(); i++)
		{
			CaplInstance *rev = ext_DocRev[i];
			file_data.GetAttrBN(rev, _T("entries"), ext_req_values);
			//CSortClass::SortExtentById(ext_req_values);

			sEntries4File=_T("");

			int j;
			for(j=0; j<ext_req_values.GetSize(); j++)
			{
				CaplInstance *reqval=ext_req_values[j];
				file_data.GetAttrBN(reqval, _T("value"), sRVal);
				if(sRVal==_T("")) continue;
				file_data.GetAttrBN(reqval, _T("entry"), entry);
				if(0==entry) continue;
				file_data.GetAttrBN(entry, S::name, sRName);

				sRVal.Replace(_T('\t'),_T(' '));
				sRVal.Replace(_T('\n'),_T(' '));
				sRVal.Replace(_T("\r"),_T(""));

				sRLine.Format(_T("\"%s\"=\"%s\""),sRName,sRVal);
				if(sEntries4File.GetLength()>0) sEntries4File+=_T("\n");
				sEntries4File+=sRLine;
			}

			if(sEntries4File==_T("")) // Реквизитов не было - пишем атрибуты
			{
				CString sVer,sId,sName;
				file_data.GetAttrBN(rev, S::revision_id,sVer);

				CaplInstance *pDoc; 
				file_data.GetAttrBN(rev, S::of_document,pDoc);
				if(0!=pDoc)
				{
					file_data.GetAttrBN(pDoc, S::id, sId);
					file_data.GetAttrBN(pDoc,S::name, sName);
				}

				sId.Replace(_T('\t'),_T(' '));
				sId.Replace(_T('\n'),_T(' '));
				sId.Replace(_T("\r"),_T(""));

				sName.Replace(_T('\t'),_T(' '));
				sName.Replace(_T('\n'),_T(' '));
				sName.Replace(_T("\r"),_T(""));

				sVer.Replace(_T('\t'),_T(' '));
				sVer.Replace(_T('\n'),_T(' '));
				sVer.Replace(_T("\r"),_T(""));

				sRLine.Format(_T("\"Обозначение\"=\"%s\""),sId);
				sEntries4File+=sRLine;

				sRLine.Format(_T("\n\"Наименование\"=\"%s\""),sName);
				sEntries4File+=sRLine;

				sRLine.Format(_T("\n\"Версия\"=\"%s\""), sVer);
				sEntries4File+=sRLine;
			}
			
			CaplAggr *aggrSign=appr_map.QGetByIn((long)rev);
			if(0!=aggrSign)
			{
				if(aggrSign->GetSize()>0)
				{
					for(j=0; j<aggrSign->GetSize(); j++)
					{
						CaplInstance *appr=0;
						aggrSign->GetByIndex(j,appr);
						if(0==appr) continue;

						CString sRole,sStatus,sDate,sFio;

						file_data.GetAttrBN(appr, _T("role"), sRole);
						CaplInstance *instStatus;
						file_data.GetAttrBN(appr, _T("status"), instStatus);
						if(0!=instStatus) file_data.GetAttrBN(instStatus, _T("name"), sStatus);

						file_data.GetAttrBN(appr, _T("approval_date_time_s"), sDate);
						COleDateTime odt;
						aplString2Date(sDate,odt);
						sDate=odt.Format(_T("%d.%m.%Y  %H:%M:%S"));

						file_data.GetAttrBN(appr, _T("digital_sign_author"), sFio);
						if(sFio==_T(""))
						{
							CaplInstance *po,*po_src;
							file_data.GetAttrBN(appr, _T("person_organization"), po);
							if(0!=po)
							{
								po_src = (CaplInstance*)inst_map.GetByOut((long)po);
								if((void*)-1==po_src) po_src=0; 
								if(0!=po_src)m_api->m_appr_mgr.GetPersonName(po_src,sFio,false);
							}
						}

						if(sEntries4File.GetLength()>0) sEntries4File+=_T("\n");
						sEntries4File+=_T("{");

						sRLine.Format(_T("\n\"Рубрика\"=\"%s\""),sStatus);
						sEntries4File+=sRLine;
						sRLine.Format(_T("\n\"Субъект\"=\"%s\""),sFio);
						sEntries4File+=sRLine;
						sRLine.Format(_T("\n\"Роль\"=\"%s\""),sRole);
						sEntries4File+=sRLine;
						sRLine.Format(_T("\n\"Дата и время подписания\"=\"%s\""),sDate);
						sEntries4File+=sRLine;
						sEntries4File+=_T("\n}");
					}
				}
			}

			if(0==sEntries4File.GetLength()) continue;

			CaplInstance *stored;
			file_data.GetAttrBN(rev, _T("access_form"), stored);
			if(0==stored) continue;
			file_data.GetAttrBN(stored, _T("source"), sFileName);

			sFilePath=sPath+sFileName+_T(".requisite");

			CaplStringFile RFile;
			if(!RFile.Open(sFilePath,CaplFile::modeWrite|CFile::modeCreate,aplUTF8)) continue;
			RFile.WriteString(sEntries4File);
			RFile.Flush();
			RFile.Close();
		}
	}

	if(s_extension==_T(".stp"))
	{
		aplP21Header header;
		rval=file_data.SaveP21(buf,header);
		//m_FileData->SaveP21(buf,header);
	}
	else if(s_extension==_T(".std"))
	{
		rval=file_data.SaveToFile(buf);
		//m_FileData->SaveToFile(buf);
	}
	else if(s_extension==_T(".json"))
	{
		rval=file_data.SaveToJsonFile(buf);
		//m_FileData->SaveToFile(buf);
	}
	else if(s_extension==_T(".txt"))
	{
		rval=file_data.SaveToTextFile(buf);
		//m_FileData->SaveToFile(buf);
	}
	else
	{
		buf+=_T(".std");
		rval=file_data.SaveToFile(buf);
		//m_FileData->SaveToFile(buf);
	}
	if(!rval){m_LastErrDescr=file_data.GetLastErrorDescription();}else{m_LastErrDescr=_T("");}
// 	for(i=0;i<m_changed_values.Size;i++)m_changed_values[i]->Set(m_changed_values_old[i]);
	m_changed_values.Clear();
	m_changed_values_new.RemoveAll();
	m_changed_values_old.RemoveAll();

	return rval;
}
bool CaplExchangeManager::ExportItemsApproval(aplExtent &ext)
{
	if(ext.GetSize()<1) return false;
	aplExtent ext_appr;

	INC_EXP_POS;
	m_api->m_appr_mgr.LoadItemApproval(ext,ext_appr);
	int i;
	for(i=0;i<ext_appr.Size;i++)
	{
		LoadInstanceTree(ext_appr[i], m_array, this);
		if(m_ExportNotes) ExportNotes(ext_appr[i]);
	}
	DEC_EXP_POS;
	return true;
}

bool CaplExchangeManager::ExportItemApproval(CaplInstance * item)
{
	if(m_data==0) return false;
	if(item==0) return false;
	if(item->GetType()==0) return false;
	if(item->GetAccessmode()>aplRO) return false;

	INC_EXP_POS;
	aplExtent ext;
	m_api->m_appr_mgr.LoadItemApproval(item,ext);
	int i;
	for(i=0;i<ext.Size;i++)
	{
		LoadInstanceTree(ext[i], m_array, this);
		if(m_ExportNotes) ExportNotes(ext[i]);
	}
	DEC_EXP_POS;
	return true;
}
//********************************************************************************
//********************************************************************************
//********************************************************************************

// Импорт

// Импорт словаря отличается от импорта данных тем,
// что значения атрибутов не меняются.

bool CaplExchangeManager::ImportDictionary(CaplMap &map, aplExtent &ext_copy)
{////////////////импорт данных из файла///////////////////
	if(m_data==0) return false;

	aplExtent ext_main, ext;
	CaplAttrValue tst_values[7];
	CString id, buf;
	//CaplMap map;
	CaplAggr aggr;
	CaplValue value;
	CaplEntity * ent;
	CaplInstance * inst;
	int i, j;

	//////////////////импорт APL_UNIT////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_charact_mgr.e_apl_unit, ext_main);
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttrBN(ext_main[i],_T("id"),id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_data->GetAttrDefinition(m_api->m_charact_mgr.e_apl_unit,_T("id"));
		m_data->NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_apl_unit,1,&tst_values[0],ext,false);

		if(ext.Size>0) map.Add((long)ext_main[i],(long)ext[0]);
		else
		{
			if(ext_main[i]!=0) ext_copy.Add(ext_main[i]);
			if(m_FileData->IsKindOf(ext_main[i],m_fileApi->m_charact_mgr.e_apl_conv_base_unit))
			{
				m_FileData->GetAttrBN(ext_main[i],_T("conversion_factor"),inst);
				if(inst!=0) ext_copy.Add(inst);
			}
			else if(m_FileData->IsKindOf(ext_main[i],m_fileApi->m_charact_mgr.e_apl_derived_unit))
			{
				m_FileData->GetAttrBN(ext_main[i],_T("elements"),aggr);
				for(j=0; j<aggr.GetSize();j++)
				{
					aggr.GetByIndex(j,inst);
					if(inst!=0) ext_copy.Add(inst);
				}
			}
			else if(m_FileData->IsKindOf(ext_main[i],m_fileApi->m_charact_mgr.e_table_unit))
			{
				m_FileData->GetAttrBN(ext_main[i],_T("columns"),aggr);
				
				for(j=0; j<aggr.GetSize();j++)
				{
					aggr.GetByIndex(j,inst);
					if(inst!=0) ext_copy.Add(inst);
				}
			}
			if(m_data->IsKindOf(ext_main[i],m_fileApi->m_charact_mgr.e_apl_named_unit))
			{
				m_FileData->GetAttrBN(ext_main[i],_T("dimensions"),inst);
				if(inst!=0) ext_copy.Add(inst);
			}
		}
	}
	////////////////////импорт APL_CHARACTERISTIC//////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_charact_mgr.e_apl_charact, ext_main);
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_charact_mgr.a_apl_charact_id,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_charact_mgr.a_apl_charact_id;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_apl_charact,1,&tst_values[0],ext,false);

		if(ext.Size>0)
				map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}

	// Группы характеристик
	aplExtent group_ext;
	m_FileData->GetEntityExtent(m_fileApi->m_charact_mgr.e_apl_charact_union,group_ext);
	for(i=0; i<group_ext.Size;i++)
	{
		CString id, name;
		m_FileData->GetAttr(group_ext[i],m_fileApi->m_charact_mgr.a_apl_charact_union_id,id);
		m_FileData->GetAttr(group_ext[i],m_fileApi->m_charact_mgr.a_apl_charact_union_name,name);
		tst_values[0].value.Set(id);
		tst_values[0].attr = m_api->m_charact_mgr.a_apl_charact_union_id;

		tst_values[1].value.Set(name);
		tst_values[1].attr = m_api->m_charact_mgr.a_apl_charact_union_name;

		aplExtent ext;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_apl_charact_union,2,&tst_values[0],ext,false);
		if(ext.Size>0)
		{
			map.Add((long)group_ext[i],(long)ext[0]);
		}
		else ext_copy.Add(group_ext[i]);
	}

	if(m_ImportCategory)
	{
		ImportCategory(map ,ext_copy);
	}

	/////////////////////////импорт APL_CHARACTERISTIC_TYPE///////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_charact_mgr.e_apl_charact_type, ext_main);
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_charact_mgr.a_apl_charact_type_name,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_charact_mgr.a_apl_charact_type_name;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_apl_charact_type,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}

	////////////////////////////импорт APPROVAL_STATUS///////////////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_appr_mgr.e_appr_status, ext_main);
	tst_values[0].attr=m_data->GetAttrDefinition(m_api->m_appr_mgr.e_appr_status,_T("name"));

	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_appr_mgr.a_appr_status_name,id);
		tst_values[0].value.Set((LPCTSTR)id);
		
		m_data->NET_FindInstancesWithAttrValues(m_api->m_appr_mgr.e_appr_status,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}


	CopyData(ext_copy,map,m_data);
	ext_copy.Clear();


/////////////////////////импорт APL_ENTRY/////////////////////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_doc_mgr.e_entry, ext_main);
	m_fileApi->LoadExtentInfo(ext_main);
	
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_doc_mgr.a_entry_name,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_doc_mgr.a_entry_name;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_doc_mgr.e_entry,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}

	CopyData(ext_copy,map,m_data);
	ext_copy.Clear();


	////////////////////////////////импорт PROJECT_TYPE/////////////////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_project_mgr->e_project_type, ext_main);
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_project_mgr->a_project_type_name,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_project_mgr->a_project_type_name;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_project_mgr->e_project_type,1,&tst_values[0],ext,false);

		if(ext.Size>0)
		{
			map.Add((long)ext_main[i],(long)ext[0]);
		}
		else
			ext_copy.Add(ext_main[i]);	
	}

	CopyData(ext_copy,map,m_data);
	ext_copy.Clear();

////////////////////////////////импорт DOCUMENT_TYPE/////////////////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_doc_mgr.e_dt, ext_main);

	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_doc_mgr.a_dt_pdt,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_doc_mgr.a_dt_pdt;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_doc_mgr.e_dt,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
		{
			map.Add((long)ext_main[i],(long)ext[0]);
		}
		else
			ext_copy.Add(ext_main[i]);	
	}

	CopyData(ext_copy,map,m_data);
	ext_copy.Clear();

	// Копируем реквизиты в виды документов

	// Если в БД есть такой вид документа и у него есть реквизиты - они остаются.
	// Если в БД есть такой вид документа и у него нет реквизитов - они копируются из исходного.


	aplExtent aeDTEntries;

	for (i=0;i<ext_main.Size;i++)
	{
		CaplInstance *dt_in= ext_main[i];
		CaplInstance *dt_out= (CaplInstance*)map.GetByInP((long)dt_in);

		if(0==dt_out) AfxMessageBox( APL_T("Ошибка при копировании вида документа!"));

		m_api->m_data.GetAttr(dt_out,m_api->m_doc_mgr.a_dt_entries,aeDTEntries);
		if(aeDTEntries.GetSize()>0) 
			continue;

		m_FileData->GetAttr(ext_main[i],m_fileApi->m_doc_mgr.a_dt_entries,aeDTEntries);
		if(aeDTEntries.GetSize()<1) continue;

		CopyData(aeDTEntries,map,m_data);
		
		aplExtent aeDTEntriesOut;

		for(j=0;j<aeDTEntries.GetSize();j++)
		{
			CaplInstance *entry2=(CaplInstance *)map.GetByInP((long)aeDTEntries[j]);
			if(0!=entry2) aeDTEntriesOut.Add(entry2);
		}

		m_api->m_data.PutAttr(dt_out,m_api->m_doc_mgr.a_dt_entries,aeDTEntriesOut);
	}




	/////////////////////////импорт APL_BP_TYPE///////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_bp_mgr.e_bp_type, ext_main);
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_bp_mgr.a_bp_type_name,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_bp_mgr.a_bp_type_name;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_bp_mgr.e_bp_type,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}
/////////////////////////импорт APL_BP_RES_TYPE///////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_bp_mgr.e_bp_res_type, ext_main);
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_bp_mgr.a_bp_res_type_name,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_bp_mgr.a_bp_res_type_name;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_bp_mgr.e_bp_res_type,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}

/////////////////////////импорт PD_CONTEXT ///////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_prd_mgr.e_pd_context, ext_main);
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_prd_mgr.a_pd_context_name,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_prd_mgr.a_pd_context_name;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_prd_mgr.e_pd_context,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}

////////////////////////////импорт PERSON_AND_ORGANIZATION_ROLE///////////////////////////////
	m_FileData->GetEntityExtentBN(_T("person_and_organization_role"), ext_main);
	ent=m_data->GetEntityBN(_T("person_and_organization_role"));
	tst_values[0].attr=m_data->GetAttrDefinition(ent,_T("name"));

	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttrBN(ext_main[i],_T("name"),id);
		tst_values[0].value.Set((LPCTSTR)id);
		m_data->NET_FindInstancesWithAttrValues(ent,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}

//////////////////////импорт PERSON_AND_ORGANIZATION/////////////////////////
	///PERSON////////////////////////////////////////////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_appr_mgr.e_person, ext_main);
	tst_values[0].attr=m_api->m_appr_mgr.a_pers_id;
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_appr_mgr.a_pers_id,id);
		tst_values[0].value.Set((LPCTSTR)id);

		m_data->NET_FindInstancesWithAttrValues(m_api->m_appr_mgr.e_person,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}
	///ORGANIZATION////////////////////////////////////////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_appr_mgr.e_org, ext_main);
	tst_values[0].attr=m_api->m_appr_mgr.a_org_id;
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_appr_mgr.a_org_id,id);
		tst_values[0].value.Set((LPCTSTR)id);

		m_data->NET_FindInstancesWithAttrValues(m_api->m_appr_mgr.e_org,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}
	///PERSON_AND_ORGANIZATION/////////////////////////////////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_appr_mgr.e_pers_org, ext_main);
	CaplInstance *i_prs, *o_prs,*i_org, *o_org, *o_pao;
	for (i=0;i<ext_main.Size;i++)
	{
		o_pao=0;
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_appr_mgr.a_po_the_pers,i_prs);
		o_prs=(CaplInstance*)map.QGetPointerByIn((long)i_prs);

		if(o_prs!=0)
		{
			m_FileData->GetAttr(ext_main[i],m_fileApi->m_appr_mgr.a_po_the_org,i_org);
			o_org=(CaplInstance*)map.QGetPointerByIn((long)i_org);
			if(o_org!=0)
			{
				if((o_prs->GetId()!=0)&&(o_org->GetId()!=0))
				{
					tst_values[0].value.Set(o_prs);
					tst_values[0].attr=m_api->m_appr_mgr.a_po_the_pers;
					tst_values[1].value.Set(o_org);
					tst_values[1].attr=m_api->m_appr_mgr.a_po_the_org;

					m_data->NET_FindInstancesWithAttrValues(m_api->m_appr_mgr.e_pers_org,2,&tst_values[0],ext,false);

					if(ext.Size>0) 
					{
						map.Add((long)ext_main[i],(long)ext[0]);
						o_pao=ext_main[i];
					}
				}
				if(o_pao==0)
					ext_copy.Add(ext_main[i]);
			}
			else ext_copy.Add(ext_main[i]);
		}
		else ext_copy.Add(ext_main[i]);
	}
	
	///ORGANIZATION_RELATIONSHIP/////////////////////////////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_appr_mgr.e_org_rel, ext_main);
	CaplInstance *i_ring, *o_ring,*i_red, *o_red, *o_orl;
	for (i=0;i<ext_main.Size;i++)
	{
		o_orl=0;
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_appr_mgr.a_org_rel_relating,i_ring);
		o_ring=(CaplInstance*)map.QGetPointerByIn((long)i_ring);
		if(o_ring!=0)
		{
			m_FileData->GetAttr(ext_main[i],m_fileApi->m_appr_mgr.a_org_rel_related,i_red);
			o_red=(CaplInstance*)map.QGetPointerByIn((long)i_red);
			if(o_red!=0)
			{
				if((o_ring->GetId()!=0)&&(o_red->GetId()!=0))
				{
					tst_values[0].value.Set(o_ring);
					tst_values[0].attr=m_api->m_appr_mgr.a_org_rel_relating;
					tst_values[1].value.Set(o_red);
					tst_values[1].attr=m_api->m_appr_mgr.a_org_rel_related;

					m_data->NET_FindInstancesWithAttrValues(m_api->m_appr_mgr.e_org_rel,2,&tst_values[0],ext,false);
					if(ext.Size>0) 
					{
						map.Add((long)ext_main[i],(long)ext[0]);
						o_orl=ext_main[i];
					}
				}
				if(o_orl==0)
					ext_copy.Add(ext_main[i]);
			}
			else ext_copy.Add(ext_main[i]);
		}
		else ext_copy.Add(ext_main[i]);
	}

	
	////////////////////////////импорт Профиля  ///////////////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_prd_mgr.e_assortment_shape, ext_main);

	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_prd_mgr.a_assortment_shape_id,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_prd_mgr.a_assortment_shape_id;
		
		m_data->NET_FindInstancesWithAttrValues(m_api->m_prd_mgr.e_assortment_shape,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}
	////////////////////////////импорт Сортаментов  ///////////////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_prd_mgr.e_assortment, ext_main);
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_prd_mgr.a_assortment_id,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_prd_mgr.a_assortment_id;
		
		m_data->NET_FindInstancesWithAttrValues(m_api->m_prd_mgr.e_assortment,1,&tst_values[0],ext,false);
		
		if(ext.Size>0)
			map.Add((long)ext_main[i],(long)ext[0]);
		else
			ext_copy.Add(ext_main[i]);
	}

	//Группы.
	aplExtent groups;
	m_FileData->GetEntityExtent(m_fileApi->m_charact_mgr.e_apl_unit_group,groups);
	for(i=0; i<groups.Size;i++)
	{
		CString id, name;
		m_FileData->GetAttr(groups[i],m_fileApi->m_charact_mgr.a_apl_unit_group_id,id);
		tst_values[0].value.Set(id);
		tst_values[0].attr = m_api->m_charact_mgr.a_apl_unit_group_id;
		m_FileData->GetAttr(groups[i],m_fileApi->m_charact_mgr.a_apl_unit_group_name,name);
		tst_values[1].value.Set(name);
		tst_values[1].attr = m_api->m_charact_mgr.a_apl_unit_group_name;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_apl_unit_group,2,&tst_values[0], ext,false);
		if(ext.Size>0)
		{
			map.Add((long)groups[i],(long)ext[0]);
		}
		else ext_copy.Add(groups[i]);
	}
	m_FileData->GetEntityExtent(m_fileApi->m_charact_mgr.e_apl_charact_group,groups);
	for(i=0; i<groups.Size;i++)
	{
		CString id, name;
		m_FileData->GetAttr(groups[i],m_fileApi->m_charact_mgr.a_apl_charact_group_id,id);
		tst_values[0].value.Set(id);
		tst_values[0].attr = m_api->m_charact_mgr.a_apl_charact_group_id;
		m_FileData->GetAttr(groups[i],m_fileApi->m_charact_mgr.a_apl_charact_group_name,name);
		tst_values[1].value.Set(name);
		tst_values[1].attr = m_api->m_charact_mgr.a_apl_charact_group_name;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_apl_charact_group,2,&tst_values[0], ext,false);
		if(ext.Size>0)
		{
			map.Add((long)groups[i],(long)ext[0]);
		}
		else ext_copy.Add(groups[i]);
	}

	m_FileData->GetEntityExtent(m_fileApi->m_charact_mgr.e_apl_charact_union_group,groups);
	for(i=0; i<groups.Size;i++)
	{
		CString id, name;
		m_FileData->GetAttr(groups[i],m_fileApi->m_charact_mgr.a_apl_charact_union_group_id,id);
		tst_values[0].value.Set(id);
		tst_values[0].attr = m_api->m_charact_mgr.a_apl_charact_union_group_id;
		m_FileData->GetAttr(groups[i],m_fileApi->m_charact_mgr.a_apl_charact_union_group_name,name);
		tst_values[1].value.Set(name);
		tst_values[1].attr = m_api->m_charact_mgr.a_apl_charact_union_group_name;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_apl_charact_union_group,2,&tst_values[0], ext,false);
		if(ext.Size>0)
		{
			map.Add((long)groups[i],(long)ext[0]);
		}
		else ext_copy.Add(groups[i]);
	}

		//Импорт персон оффициал role.
		aplExtent org_ext;
		m_FileData->GetEntityExtent(m_fileApi->m_appr_mgr.e_person,org_ext);//person
		for(i=0; i<org_ext.Size;i++)
		{
			CString id, first_name, last_name;
			m_FileData->GetAttr(org_ext[i],m_fileApi->m_appr_mgr.a_pers_id,id);
			tst_values[0].value.Set(id);
			tst_values[0].attr = m_api->m_appr_mgr.a_pers_id;
			m_FileData->GetAttr(org_ext[i],m_fileApi->m_appr_mgr.a_pers_first_name,first_name);
			tst_values[1].value.Set(first_name);
			tst_values[1].attr = m_api->m_appr_mgr.a_pers_first_name;
			m_FileData->GetAttr(org_ext[i],m_fileApi->m_appr_mgr.a_pers_last_name,last_name);
			tst_values[2].value.Set(last_name);
			tst_values[2].attr = m_api->m_appr_mgr.a_pers_last_name;
			m_data->NET_FindInstancesWithAttrValues(m_api->m_appr_mgr.e_person,3,&tst_values[0], ext,false);
			if(ext.Size>0)
				map.Add((long)org_ext[i],(long)ext[0]);
			else ext_copy.Add(org_ext[i]);
		}
		m_FileData->GetEntityExtent(m_fileApi->m_appr_mgr.e_official,org_ext);
		for(i=0; i<org_ext.Size;i++)
		{
			CString id;
			m_FileData->GetAttr(org_ext[i],m_fileApi->m_appr_mgr.a_official_id,id);
			tst_values[0].value.Set(id);
			tst_values[0].attr = m_api->m_appr_mgr.a_official_id;
			m_data->NET_FindInstancesWithAttrValues(m_api->m_appr_mgr.e_official,1,&tst_values[0], ext,false);
			if(ext.Size>0)
			{
				map.Add((long)org_ext[i],(long)ext[0]);
			}
			else ext_copy.Add(org_ext[i]);
		}
		
		m_FileData->GetEntityExtent(m_fileApi->m_appr_mgr.e_org,org_ext);
		for(i=0; i<org_ext.Size;i++)
		{
			CString id, name;
			m_FileData->GetAttr(org_ext[i],m_fileApi->m_appr_mgr.a_org_id,id);
			tst_values[0].value.Set(id);
			tst_values[0].attr = m_api->m_appr_mgr.a_org_id;
			m_FileData->GetAttr(org_ext[i],m_fileApi->m_appr_mgr.a_org_name,name);
			tst_values[1].value.Set(id);
			tst_values[1].attr = m_api->m_appr_mgr.a_org_name;
			m_data->NET_FindInstancesWithAttrValues(m_api->m_appr_mgr.e_org,2,&tst_values[0], ext,false);
			if(ext.Size>0)
				map.Add((long)org_ext[i],(long)ext[0]);
			else ext_copy.Add(org_ext[i]);
		}

	CopyData(ext_copy,map,m_data);

	return true;
}

//********************************************************************************
bool CaplExchangeManager::CopyData(aplExtent &ext_copy, CaplMap &map, CaplStepData * data)
{
	int count = 0;

	//////////////////////////////////копирование инстэнсов///////////////////////////////////
	long i, j, li_items_col, li_attr_col;
	if(data==0) return false;
	CaplEntity * pEntityRef;			// Рабочие указатели
	CaplInstance * inst;
	CaplAttr * pAttrRef;
	CaplMap new_ent, new_attr;

	li_items_col = ext_copy.GetSize();
	if (li_items_col == 0) return false;

	// Сначала копируем Instancы
	int cnt_create = 0;
	for (i = 0; i < li_items_col;  i++)		// По всем данным Inst-ам
	{
		CaplInstance *inst_i=ext_copy[i];
		if(0==inst_i) continue;
		if(0==inst_i->GetType()) continue;
		if(m_IgnoreAddDict && inst_i->GetType()->id>20000) continue;

		pEntityRef=0;
		if(map.QGetPointerByIn((long)inst_i)!=0) continue;
		
		pEntityRef=(CaplEntity*)new_ent.GetByInP((long)inst_i->GetType());
		//Создаем энтити и добавляем ее в мэп			
		if(pEntityRef==0)
		{
			pEntityRef = data->GetEntityBN( inst_i->GetType()->name );	// Ссылка на тип Instance во втором StepData		
			if(pEntityRef==0) 
				continue;
			new_ent.Add((long)inst_i->GetType(),(long)pEntityRef);
		}
		inst=data->CreateInstance( pEntityRef );	
		map.Add((long)inst_i,(long)inst);// Добавили экземпляр
		cnt_create++;
		count++;

		/* Зачем сохранять источник ?
		if(count == 3000)
		{
			m_api->SaveChanges();
			count = 0;
		}*/
	}
	//if(cnt_create==0) return false; чтобы копировались атрибуты для уже имеющихся в БД объектов
			
	for (i = 0; i < li_items_col; i++)
	{
		count++;
		/* Зачем сохранять источник ?
		if(count == 3000)
		{
			m_api->SaveChanges();
			count = 0;
		}*/

		// Копируем атрибуты и перекрестные ссылки :
		CaplInstance *inst_i=ext_copy[i];
		if(0==inst_i) continue;
		if(0==inst_i->GetType()) continue;
		if(m_IgnoreAddDict && inst_i->GetType()->id>20000) continue;
		if(0==inst_i->attrs) continue;

		li_attr_col = ext_copy[i]->GetType()->all_attrs.GetSize();				
		for (j = 0; j < li_attr_col; j++)	
		{	
			pAttrRef=0;

			inst=(CaplInstance * )map.QGetPointerByIn((long)inst_i);
			if(0==inst) continue;

			pAttrRef=(CaplAttr*)new_attr.GetByInP((long)inst_i->GetType()->all_attrs[j]);

			if(pAttrRef==0)
			{
				pAttrRef = data->GetAttrDefinition(inst->GetType(), inst_i->GetType()->all_attrs[j]->name );
				if(((long)pAttrRef==0)||((long)pAttrRef==-1)) continue;
				new_ent.Add((long)inst_i->GetType(),(long)pEntityRef);
			}

			if(m_IgnoreAddDict && pAttrRef->id>20000) continue;
			
			// Атрибут INSTANCE
			if ( ext_copy[i]->attrs[j].value.type == aplINSTANCE )
			{
				CaplInstance * finded =(CaplInstance *) map.QGetPointerByIn((long)inst_i->attrs[j].value.instval);
				if (finded!=0)
					data->PutAttr(inst, pAttrRef, finded );
			}
			else	
			{
				// Простой атрибут
				data->PutAttr(inst, pAttrRef, inst_i->attrs[j].value);	// Присвоили значение
				// Атрибут AGGR
				if ( inst_i->attrs[j].value.type == aplAGGR )	// Если атрибут - AGGR
				{
//					RemapAggrToNewDB(*(inst->attrs[j]->value.aggrval),map);
					for(int iAttr=0; iAttr<inst->GetType()->all_attrs.GetSize();iAttr++)
						if(inst->GetType()->all_attrs[iAttr]==pAttrRef) {RemapAggrToNewDB(*inst->attrs[iAttr].value.aggrval,map);break;}
				}
			}			
		}
	}

	if(count != 0) m_api->SaveChanges();
	return true;
}
//********************************************************************************
//bool CaplExchangeManager::ExportDictionary(const char *file)
//{
//	if(file==_T("")) return false;
//
//	CaplNetStepData data;
//	if(!data.LoadDictionary(m_data->m_CurSchema)) return false;
//	bool s=ExportDictionary(&data);
//	data.SaveToFile(file);
//	aplP21Header header;
//	data.SaveP21(file,header);
//	return true;
//}


//********************************************************************************
//bool CaplExchangeManager::ExportDictionary(CaplNetStepData *data)
bool CaplExchangeManager::ExportDictionary(const TCHAR *filename)

{
//	if(data==0) return false;
	if(m_data==0) return false;
	if(m_api==0) return false;

	CaplSetResourceHandle setres(module_inst);

	CSelectName dlg;
	if(filename==0){
		CRegKey key;
		TCHAR buf[1024];
		DWORD len=1024;
		memset(buf,0,len);
		if(key.Open(HKEY_CURRENT_USER,
			_T("Software\\CALS Centre \"Applied Logistic\"\\PDM STEP Suite\\options"))
			==ERROR_SUCCESS)
		{
#if _MSC_VER >= 1400
			if(key.QueryStringValue(_T("LastExportedFile"),buf,&len)==ERROR_SUCCESS)
#else
			if(key.QueryValue(buf,_T("LastExportedFile"),&len)==ERROR_SUCCESS)
#endif
			{
				buf[len]=0;
				dlg.m_FileName=buf;
			}
		}
	}else{
		dlg.m_FileName=filename;
	}


	dlg.m_api=m_api;
//	dlg.m_data=m_data;
//	dlg.m_appr=&m_api->m_appr_mgr;
//	dlg.m_catg=&m_api->m_categ_mgr;
//	dlg.m_doc=&m_api->m_doc_mgr;
//	dlg.m_char=&m_api->m_charact_mgr;
//	dlg.m_prMan=&m_api->m_prd_mgr;

	dlg.m_exch=this;

	if(dlg.DoModal()==IDOK)
	{
		CRegKey key;
		if(key.Open(HKEY_CURRENT_USER,
			_T("Software\\CALS Centre \"Applied Logistic\"\\PDM STEP Suite\\options"))
			==ERROR_SUCCESS)
		{
#if _MSC_VER >= 1400
			key.SetStringValue(_T("LastExportedFile"),dlg.m_FileName);
#else
			key.SetValue(dlg.m_FileName,_T("LastExportedFile"));
#endif
		}

	}
	return true;
}
//********************************************************************************
void CaplExchangeManager::ImportClassifierEsquisse(CaplInstance* inst_api,CaplInstance* inst_file)
{
	CString name,temp_name;
	long code;
	int k,n;
	CaplAttr *attr_file_esquisse,*attr_file_esquisse_name,*attr_api_esquisse,*attr_api_esquisse_name;
	if(m_api->m_data.IsKindOf(inst_api,m_api->m_classifier_mgr.e_apl_classifier_system))
	{
		if(!m_FileData->IsKindOf(inst_file,m_fileApi->m_classifier_mgr.e_apl_classifier_system))return;
		attr_file_esquisse=m_fileApi->m_classifier_mgr.a_apl_classifier_system_esquisse;
		attr_file_esquisse_name=m_fileApi->m_classifier_mgr.a_apl_classifier_system_esquisse_name;
		attr_api_esquisse=m_api->m_classifier_mgr.a_apl_classifier_system_esquisse;
		attr_api_esquisse_name=m_api->m_classifier_mgr.a_apl_classifier_system_esquisse_name;
	}
	else if(m_api->m_data.IsKindOf(inst_api,m_api->m_classifier_mgr.e_apl_classifier_level))
	{
		if(!m_FileData->IsKindOf(inst_file,m_fileApi->m_classifier_mgr.e_apl_classifier_level))return;
		attr_file_esquisse=m_fileApi->m_classifier_mgr.a_apl_classifier_level_esquisse;
		attr_file_esquisse_name=m_fileApi->m_classifier_mgr.a_apl_classifier_level_esquisse_name;
		attr_api_esquisse=m_api->m_classifier_mgr.a_apl_classifier_level_esquisse;
		attr_api_esquisse_name=m_api->m_classifier_mgr.a_apl_classifier_level_esquisse_name;
	}
	else
	{
		return;
	}

	m_api->m_data.GetAttr(inst_api,attr_api_esquisse_name,name);
	m_FileData->GetAttr(inst_file,attr_file_esquisse_name,temp_name);
	if(temp_name!=_T("")){
		if(name!=_T("")){
			// удаляем старый блоб - если он есть
			m_api->m_data.NET_DeleteBlob(inst_api,attr_api_esquisse);
		}
		temp_name=GetOnlyFileName(temp_name);
		if(m_api->m_data.NET_SaveBlob(inst_api,attr_api_esquisse,m_InPath+temp_name,code))
		{
			k=temp_name.GetLength();
			n=0;
			name=temp_name;
			do{
				k--;
				if(temp_name[k]==_T('\\') || temp_name[k]==_T('/')){
					name=temp_name.Right(temp_name.GetLength()-k-1);
					break;
				}
				if(temp_name[k]==_T('.')){n++;}
				if(n==2){
					name=temp_name.Right(temp_name.GetLength()-k-1);
					break;
				}
			}while(k>0);
		}
		m_api->m_data.PutAttr(inst_api,attr_api_esquisse_name,name);
	}
}

//********************************************************************************
bool CaplExchangeManager::ImportDataFromFile(const TCHAR *filename, CaplInstance *packet)
{
	if(m_data==0) return false;

	int i, j;//, k, k_1;
	aplExtent pds_ext;
	CaplEntity *e_packet = m_api->m_data.GetEntityBN(_T("etd_packet"));
	CaplEntity *e_file_ds = m_api->m_data.GetEntityBN(_T("etd_file_data_set"));
	CaplAttr	*a_file_ds_name = m_api->m_data.GetAttrDefinition(e_file_ds, _T("name"));
	CaplAttr	*a_ds_packet = m_api->m_data.GetAttrDefinitionBN(_T("etd_data_set"), _T("of_packet"));
	CaplAttr	*a_file_ds_source = m_api->m_data.GetAttrDefinition(e_file_ds, _T("data"));

	if(packet)
	{
		if(!m_api->m_data.IsKindOf(packet, e_packet)) packet = NULL;
	}

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

		aplExtent ext;
		CaplInstance *inst;
		m_api->m_data.GetEntityExtent(e_file_ds, ext);
		for(i=0; i<ext.GetSize(); i++)
		{
			m_api->m_data.GetAttr(ext[i], a_ds_packet, inst);
			if(inst==packet) pds_ext.Add(ext[i]);
		}
	}

	bool AutoSave= m_api->m_AutoSave;
	m_api->SetAutoSave(false);
	
	m_InFile=filename;
	
	CaplSetResourceHandle setres(module_inst);

	CString ChangeId, ChangeBase, ChangeDescr;
	if(m_InFile.IsEmpty())
	{
		CImportDialog dlg;
		dlg.m_imp_categ=m_ImportCategory;
		dlg.m_imp_classif=m_ImportClassifiers;
		dlg.m_imp_doc=m_ImportAssDocuments;
		dlg.m_imp_prd_charact=m_ImportProductCharacteristics;
		dlg.m_imp_prd_struct=m_ImportProductStruct;
		dlg.m_imp_appr=m_ImportApproval;
		dlg.m_imp_folders=m_ImportFolders;
		dlg.m_imp_project=m_ImportProject;
		dlg.m_imp_bp=m_ImportBP;
		dlg.m_imp_bp_res=m_ImportBPRes;
		dlg.m_imp_req=m_ImportRequirement;

		if(dlg.DoModal()!=IDOK) return true;

		m_ImportCategory=dlg.m_imp_categ;
		m_ImportClassifiers=dlg.m_imp_classif;
		m_ImportAssDocuments=dlg.m_imp_doc;
		m_ImportProductCharacteristics=dlg.m_imp_prd_charact;
		m_ImportProductStruct=dlg.m_imp_prd_struct;
		m_ImportApproval=dlg.m_imp_appr;
		m_ImportFolders=dlg.m_imp_folders;
		m_ImportProject=dlg.m_imp_project;
		m_ImportBP=dlg.m_imp_bp;
		m_ImportBPRes=dlg.m_imp_bp_res;
		m_InFile=dlg.m_file_name;
		m_ImportRequirement=dlg.m_imp_req;

		ChangeId=dlg.m_change_id;
		ChangeBase=dlg.m_change_base;
		ChangeDescr=dlg.m_change_descr;

	}

	int prgs_count=0;

	m_InPath=_T("");
	i=m_InFile.ReverseFind(_T('\\'));
	if(i>0) m_InPath=m_InFile.Left(i+1);

	m_fileApi=new CaplAPI;
	m_FileData=&(m_fileApi->m_data);
	m_FileData->SetErrorMessageMode(false);
	m_FileData->SetHideMode(true);

	/************************************************************************/
	//Распаковка пакета
	CString sPath;
	CStringArray sFiles;
	CString sExt;
	int f_ind;
	bool bLoadFromPacket=false;
	f_ind = m_InFile.ReverseFind(_T('\\'));
	if(f_ind>-1)
		sPath = m_InFile.Left(f_ind+1);
	f_ind = m_InFile.ReverseFind(_T('.'));
	if(f_ind>-1)
		sExt = m_InFile.Right(m_InFile.GetLength()-f_ind-1);
	if(sExt.CompareNoCase(_T("etd"))==0)
	{
		bLoadFromPacket=true;
		CaplPacket packet;
		if(0!=packet.Load(m_InFile)) 
		{
			if(m_api->m_ModeInteractive)
				AfxMessageBox( APL_T("Не удалось прочитать пакет!"));
			return false;
		}
		aplGetTempPath(sPath);
		sPath+=_T("pss\\");
		if(!SetCurrentDirectory(sPath))
			CreateDirectory(sPath, NULL);

		m_InPath = sPath;

		if(!packet.SaveAsFiles(sPath, &sFiles))
		{
			if(m_api->m_ModeInteractive)
				AfxMessageBox( APL_T("Не удалось сохранить файлы пакета на диск!"));
			return false;
		}

		m_InFile=_T("");

		//ищем std или stp; если таких нет, то первый попавшийся txt, если и таких нет, то первый попавшийся файл
		for(i=0; i<sFiles.GetSize(); i++)
		{
			f_ind = sFiles[i].ReverseFind(_T('.'));
			if(f_ind>-1)
				sExt = sFiles[i].Right(sFiles[i].GetLength()-f_ind-1);
			if(sExt.CompareNoCase(_T("std"))==0)
			{
				m_InFile = sFiles[i];
				break;
			}
			if(sExt.CompareNoCase(_T("stp"))==0)
			{
				m_InFile = sFiles[i];
				break;
			}
		}
		if(m_InFile.IsEmpty())
		{
			for(i=0; i<sFiles.GetSize(); i++)
			{
				f_ind = sFiles[i].ReverseFind(_T('.'));
				if(f_ind>-1)
					sExt = sFiles[i].Left(sFiles[i].GetLength()-f_ind-1);
				if(sExt.CompareNoCase(_T("txt"))==0)
				{
					m_InFile = sFiles[i];
					break;
				}
			}
		}
		if(m_InFile.IsEmpty() && sFiles.GetSize()>0)
			m_InFile = sFiles[0];
		if(m_InFile.IsEmpty())
		{
			if(m_api->m_ModeInteractive)
				AfxMessageBox( APL_T("Пакет пуст!"));
			return false;
		}
	}

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

	if(!m_FileData->LoadFromFile(m_InFile))
	{
		delete m_fileApi;
		m_fileApi=0;
		m_FileData=0;

		if(m_api->m_ModeInteractive)
			AfxMessageBox( APL_T("Ошибка открытия файла !"));
		//Удаляем файлы
		for(i=0; i<sFiles.GetSize(); i++)
			::DeleteFile(sFiles[i]);

		return false;
	}
	m_fileApi->Init();
	CaplMgrPrgsDlg prgs_dlg;
	prgs_dlg.Create(IDD_PRGS_DLG);
	prgs_dlg.ShowWindow(SW_SHOW);
	m_prgs_dlg=&prgs_dlg;

	CaplMap map;
	map.bAutoSort= true;
	
	aplExtent ext_copy;
	ImportDictionary(map,ext_copy);

	m_fileApi->m_bp_mgr.m_AutoSave = false;
	m_fileApi->SetAutoSave(false);

	ext_copy.Clear();

	CaplAttrValue tst_values[5];
	CString id,name,ver,buf;

	aplExtent ext, extPrd, extPdf, extPd, extPdr, extEff, ext_rel, ext1, act_vers,ext_eff, ext_rel1, ext2;
	aplExtent set_active;//Для установки активной версии
	CaplInstance *inst0,*inst1;

	// Загрузка справочников
	if (m_ImportClassifiers)
	{
		// сами справочники
		aplExtent ext_classif_s,ext_classif_l,ext_classif_a;
		CaplInstance *inst_s_file,*inst_s_api;

		m_FileData->GetEntityExtent(m_fileApi->m_classifier_mgr.e_apl_classifier_system, ext_classif_s);

		for (i = 0; i < ext_classif_s.Size; i++) 
		{
			INC_PRGS_POS(i,5);
			m_FileData->GetAttr(ext_classif_s[i], m_fileApi->m_classifier_mgr.a_apl_classifier_system_id, id);

			tst_values[0].value.Set((LPCTSTR)id);
			tst_values[0].attr=m_api->m_classifier_mgr.a_apl_classifier_system_id;
			m_data->NET_FindInstancesWithAttrValues(m_api->m_classifier_mgr.e_apl_classifier_system, 1, &tst_values[0], ext, false);

			if (ext.Size > 0)
				map.Add((long)ext_classif_s[i], (long)ext[0]);
			else 
				ext_copy.Add(ext_classif_s[i]);
		}

		m_FileData->GetEntityExtent(m_fileApi->m_classifier_mgr.e_apl_classifier_level, ext_classif_l);

		for (i = 0; i < ext_classif_l.Size; i++)
		{
			INC_PRGS_POS(i,5);
			m_FileData->GetAttr(ext_classif_l[i],m_fileApi->m_classifier_mgr.a_apl_classifier_level_id,id);
			m_FileData->GetAttr(ext_classif_l[i],m_fileApi->m_classifier_mgr.a_apl_classifier_level_system,inst_s_file);
			inst_s_api = (CaplInstance*)map.QGetPointerByIn((long)inst_s_file);

			if (inst_s_api != NULL)
			{
				tst_values[0].value.Set((LPCTSTR)id);
				tst_values[0].attr=m_api->m_classifier_mgr.a_apl_classifier_level_id;
				tst_values[1].value.Set(inst_s_api);
				tst_values[1].attr=m_api->m_classifier_mgr.a_apl_classifier_level_system;

				m_data->NET_FindInstancesWithAttrValues(m_api->m_classifier_mgr.e_apl_classifier_level,
					2, &tst_values[0], ext, false);

				if (ext.Size > 0)
					map.Add((long)ext_classif_l[i], (long)ext[0]);
				else
					ext_copy.Add(ext_classif_l[i]);
			}
			else
			{
				ext_copy.Add(ext_classif_l[i]);
			}
		}

		// их эскизы
		// см после копирования

		// формы

		//импорт конфигурационных опционов
		aplExtent aeConfingOpts;
		aplExtent aeItems;
		CString sName;
		CString sCode;
		CString sDescr;
		CString sRule;
		m_FileData->GetEntityExtentBN(_T("apl_composition_requirement_enumeration"),aeConfingOpts);
		CaplEntity* e_comp_req = m_data->GetEntityBN(_T("apl_composition_requirement"));
		CaplEntity* e_comp_req_item = m_data->GetEntityBN(_T("apl_composition_requirement_enumeration_item"));

		for (i=0; i<aeConfingOpts.Size; i++)
		{
			m_FileData->GetAttrBN(aeConfingOpts[i],_T("code"),sCode);
			m_FileData->GetAttrBN(aeConfingOpts[i],_T("name"),sName);
			m_FileData->GetAttrBN(aeConfingOpts[i],_T("description"),sDescr);
			m_FileData->GetAttrBN(aeConfingOpts[i],_T("rule"),sRule);

			tst_values[0].value.Set(sCode);
			tst_values[0].attr=m_api->m_data.GetAttrDefinitionBN(_T("apl_composition_requirement"),_T("code"));

			m_data->NET_FindInstancesWithAttrValues(e_comp_req, 1, &tst_values[0], ext, false);

			if(ext.Size > 0)
			{
				m_api->m_data.PutAttrBN(ext[0], _T("name"), sName);
				m_api->m_data.PutAttrBN(ext[0], _T("description"), sDescr);
				m_api->m_data.PutAttrBN(ext[0], _T("rule"), sRule);
				map.Add((long)aeConfingOpts[i],(long)ext[0]);
			}
			else
				ext_copy.Add(aeConfingOpts[i]);

			m_FileData->GetAttrBN(aeConfingOpts[i],_T("values"),aeItems);

			for (j = 0; j < aeItems.Size; j++)
			{
				m_FileData->GetAttrBN(aeItems[j],_T("code"),sCode);
				m_FileData->GetAttrBN(aeItems[j],_T("name"),sName);

				tst_values[0].value.Set(sCode);
				tst_values[0].attr=m_api->m_data.GetAttrDefinitionBN(_T("apl_composition_requirement_enumeration_item"),_T("code"));

				m_data->NET_FindInstancesWithAttrValues(e_comp_req_item, 1, &tst_values[0], ext, false);

				if(ext.Size > 0)
				{
					m_api->m_data.PutAttrBN(ext[0], _T("name"), sName);
					map.Add((long)aeItems[j],(long)ext[0]);
				}
				else
					ext_copy.Add(aeItems[j]);
			}
		}


		// ассоциации
		m_FileData->GetEntityExtent(m_fileApi->m_classifier_mgr.e_apl_classifier_association, ext_classif_a);

		for(i = 0; i < ext_classif_a.Size; i++)
		{
			CaplInstance *pAssociationItem = NULL;
			CaplInstance *pSystem = NULL;

			m_FileData->GetAttr(ext_classif_a[i], m_fileApi->m_classifier_mgr.a_apl_classifier_association_item, pAssociationItem);
			m_FileData->GetAttr(ext_classif_a[i], m_fileApi->m_classifier_mgr.a_apl_classifier_association_system, pSystem);

			CaplInstance *pMapAssociationItem = (CaplInstance*)map.QGetPointerByIn((long)pAssociationItem);
			CaplInstance *pMapSystem = (CaplInstance*)map.QGetPointerByIn((long)pSystem);

			if (pMapAssociationItem && pMapSystem)
			{
				tst_values[0].value.Set(pMapAssociationItem);
				tst_values[0].attr = m_api->m_classifier_mgr.a_apl_classifier_association_item;
				tst_values[1].value.Set(pMapSystem);
				tst_values[1].attr = m_api->m_classifier_mgr.a_apl_classifier_association_system;

				m_data->NET_FindInstancesWithAttrValues(m_api->m_classifier_mgr.e_apl_classifier_association,
					2, &tst_values[0], ext, false);

				if (ext.Size > 0)
					map.Add((long)ext_classif_a[i], (long)ext[0]);
				
			}
			ext_copy.Add(ext_classif_a[i]);
		}
	}


	// Загрузка папок
	if(m_ImportFolders)
	{
		aplExtent ext_folders;
		m_FileData->GetEntityExtent(m_fileApi->m_folder_mgr.e_folder, ext_folders);
		for(i=0; i<ext_folders.Size; i++)
		{
			m_fileApi->m_data.GetAttr(ext_folders[i], m_fileApi->m_folder_mgr.a_folder_name, buf);
			m_fileApi->m_data.GetAttr(ext_folders[i], m_fileApi->m_folder_mgr.a_folder_parent, inst0);
			
			tst_values[0].attr= m_api->m_folder_mgr.a_folder_name;
			tst_values[0].value.Set(buf);
			tst_values[1].attr= m_api->m_folder_mgr.a_folder_parent;
			inst1= (CaplInstance*)map.QGetPointerByIn((long)inst0);
			tst_values[1].value.Set(inst1);

			m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_folder_mgr.e_folder, 2, &tst_values[0], ext, false);
			if(ext.GetSize()) map.Add((long)ext_folders[i], (long)ext[0]);

			ext_copy.Add(ext_folders[i]);
		}
	}

	if(m_ImportProject){
		ImportProject(map ,ext_copy);
	}
	
	//импорт конфигурационных базисов, правил, конфигураций и связей.
	CaplEntity *e_pdf_app = m_data->GetEntityBN(_T("apl_product_appearance"));
	CaplEntity *e_app_req_lim_rel = m_data->GetEntityBN(_T("apl_appearance_requirement_limit_relationship"));	
	CaplEntity *e_app_req_lim = m_data->GetEntityBN(_T("apl_appearance_requirement_limit"));	
	CaplEntity *e_app_req_rel = m_data->GetEntityBN(_T("apl_appearance_requirement_relationship"));	
	CaplEntity *e_pdf_app_comp = m_data->GetEntityBN(_T("apl_appearence_composition"));
	aplExtent extApps;
	aplExtent extAppLimRels;
	aplExtent extLimits;
	aplExtent extAppOptRels;
	aplExtent extOptions;
	aplExtent extComplectations;
	aplExtent aeItems;	

	m_FileData->GetEntityExtentBN(_T("apl_product_appearance"), extApps);
	m_fileApi->LoadExtentInfo(extApps);
	m_FileData->GetEntityExtentBN(_T("apl_appearance_requirement_limit_relationship"), extAppLimRels);
	m_FileData->GetEntityExtentBN(_T("apl_appearance_requirement_limit"), extLimits);	
	m_FileData->GetEntityExtentBN(_T("apl_appearance_requirement_relationship"), extAppOptRels);
	m_FileData->GetEntityExtentBN(_T("apl_appearence_composition"), extComplectations);

	// Копируем конфигурационные базисы
	CString strAppCode;
	CString strAppName;
	CString strAppDescr;
	
	for (int iIndex = 0; iIndex < extApps.GetSize(); iIndex++)
	{
		m_FileData->GetAttrBN(extApps[iIndex], _T("code"), strAppCode);
		m_FileData->GetAttrBN(extApps[iIndex], _T("name"), strAppName);
		m_FileData->GetAttrBN(extApps[iIndex], _T("description"), strAppDescr);

		// Поиск базисов, найденных в файле, в БД для фильтрации дубликатов
		tst_values[0].value.Set(strAppCode);
		tst_values[0].attr = m_api->m_data.GetAttrDefinitionBN(_T("apl_product_appearance"), _T("code"));
// 		tst_values[1].value.Set(strAppName);
// 		tst_values[1].attr = m_api->m_data.GetAttrDefinitionBN(_T("apl_product_appearance"), _T("name"));
		
		m_data->NET_FindInstancesWithAttrValues(e_pdf_app, 1, &tst_values[0], ext, false);
		
		if (ext.GetSize() > 0)
		{
			m_api->m_data.PutAttrBN(ext[0], _T("name"), strAppName);
			m_api->m_data.PutAttrBN(ext[0], _T("description"), strAppDescr);
			map.Add((long)extApps[iIndex], (long)ext[0]);
		}
		else
			ext_copy.Add(extApps[iIndex]);
	}

	// Копируем правила
	CString strLimitCode;
	CString strLimitName;
	CString strLimitErrorMsg;
	CString strLimitRule;
	
	for (int iIndex = 0; iIndex < extLimits.GetSize(); iIndex++)
	{
		m_FileData->GetAttrBN(extLimits[iIndex], _T("code"), strLimitCode);
		m_FileData->GetAttrBN(extLimits[iIndex], _T("name"), strLimitName);
		m_FileData->GetAttrBN(extLimits[iIndex], _T("error"), strLimitErrorMsg);
		m_FileData->GetAttrBN(extLimits[iIndex], _T("limit"), strLimitRule);

		// Поиск правил, найденных в файле, в БД для фильтрации дубликатов
		tst_values[0].value.Set(strLimitCode);
		tst_values[0].attr = m_api->m_data.GetAttrDefinitionBN(_T("apl_appearance_requirement_limit"), _T("code"));

		m_data->NET_FindInstancesWithAttrValues(e_app_req_lim, 1, &tst_values[0], ext, false);

		if (ext.GetSize() > 0)
		{
			m_api->m_data.PutAttrBN(ext[0], _T("name"), strLimitName);
			m_api->m_data.PutAttrBN(ext[0], _T("error"), strLimitErrorMsg);
			m_api->m_data.PutAttrBN(ext[0], _T("limit"), strLimitRule);
			map.Add((long)extLimits[iIndex], (long)ext[0]);
		}
		else
			ext_copy.Add(extLimits[iIndex]);
	}

	// Копируем комплектации (конфигурации)
	CString strCompCode;
	CString strCompName;
	CString strCompDescr;
	CString strCompSerialNumbers;
	CString strCompVersionID;
	
	for (int iIndex = 0; iIndex < extComplectations.GetSize(); iIndex++)
	{
		m_FileData->GetAttrBN(extComplectations[iIndex], _T("code"), strCompCode);
		m_FileData->GetAttrBN(extComplectations[iIndex], _T("name"), strCompName);
		m_FileData->GetAttrBN(extComplectations[iIndex], _T("description"), strCompDescr);
		m_FileData->GetAttrBN(extComplectations[iIndex], _T("serial_numbers"), strCompSerialNumbers);
		m_FileData->GetAttrBN(extComplectations[iIndex], _T("version_id"), strCompVersionID);

		// Поиск комплектаций, найденных в файле, в БД для фильтрации дубликатов
		tst_values[0].value.Set(strCompCode);
		tst_values[0].attr = m_api->m_data.GetAttrDefinitionBN(_T("apl_appearence_composition"), _T("code"));
// 		tst_values[1].value.Set(strCompName);
// 		tst_values[1].attr = m_api->m_data.GetAttrDefinitionBN(_T("apl_appearence_composition"), _T("name"));

		m_data->NET_FindInstancesWithAttrValues(e_pdf_app_comp, 1, &tst_values[0], ext, false);

		if (ext.GetSize() > 0)
		{
			m_api->m_data.PutAttrBN(ext[0], _T("name"), strCompName);
			m_api->m_data.PutAttrBN(ext[0], _T("description"), strCompDescr);
			m_api->m_data.PutAttrBN(ext[0], _T("serial_numbers"), strCompSerialNumbers);
			m_api->m_data.PutAttrBN(ext[0], _T("version_id"), strCompVersionID);
			map.Add((long)extComplectations[iIndex], (long)ext[0]);
		}
		else
			ext_copy.Add(extComplectations[iIndex]);
	}

	// Копируем связи базис <-> правило	
	for (int iIndex = 0; iIndex < extAppLimRels.GetSize(); iIndex++)
	{
		CaplInstance *pAppLimitApp = NULL;
		CaplInstance *pAppLimitLim = NULL;

		m_FileData->GetAttrBN(extAppLimRels[iIndex], _T("appearance"), pAppLimitApp);
		m_FileData->GetAttrBN(extAppLimRels[iIndex], _T("limit"), pAppLimitLim);

		CaplInstance *pMapAppInstance = (CaplInstance*)map.QGetPointerByIn((long)pAppLimitApp);
		CaplInstance *pMapLimInstance = (CaplInstance*)map.QGetPointerByIn((long)pAppLimitLim);

		if (pMapAppInstance == NULL)
			pMapAppInstance = pAppLimitApp;

		if (pMapLimInstance == NULL)
			pMapLimInstance = pAppLimitLim;

		// Поиск связей "базис <-> правило", найденных в файле, в БД для фильтрации дубликатов
		tst_values[0].value.Set(pMapAppInstance);
		tst_values[0].attr = m_api->m_data.GetAttrDefinitionBN(_T("apl_appearance_requirement_limit_relationship"), _T("appearance"));
		tst_values[1].value.Set(pMapLimInstance);
		tst_values[1].attr = m_api->m_data.GetAttrDefinitionBN(_T("apl_appearance_requirement_limit_relationship"), _T("limit"));

		m_data->NET_FindInstancesWithAttrValues(e_app_req_lim_rel, 2, &tst_values[0], ext, false);

		if (ext.GetSize() > 0)
			map.Add((long)extAppLimRels[iIndex], (long)ext[0]);
		else
			ext_copy.Add(extAppLimRels[iIndex]);
	}

	// Копируем связи базис <-> опцион
	for (int iIndex = 0; iIndex < extAppOptRels.GetSize(); iIndex++)
	{
		CaplInstance *pAppReqApp = NULL;
		CaplInstance *pAppReqReq = NULL;

		m_FileData->GetAttrBN(extAppOptRels[iIndex], _T("appearance"), pAppReqApp);
		m_FileData->GetAttrBN(extAppOptRels[iIndex], _T("option"), pAppReqReq);

		CaplInstance *pMapAppInstance = (CaplInstance*)map.QGetPointerByIn((long)pAppReqApp);
		CaplInstance *pMapOptInstance = (CaplInstance*)map.QGetPointerByIn((long)pAppReqReq);

		if (pMapAppInstance == NULL)
			pMapAppInstance = pAppReqApp;

		if (pMapOptInstance == NULL)
			pMapOptInstance = pAppReqReq;

		// Поиск связей "базис <-> опцион", найденных в файле, в БД для фильтрации дубликатов
		tst_values[0].value.Set(pMapAppInstance);
		tst_values[0].attr = m_api->m_data.GetAttrDefinitionBN(_T("apl_appearance_requirement_relationship"), _T("appearance"));
		tst_values[1].value.Set(pMapOptInstance);
		tst_values[1].attr = m_api->m_data.GetAttrDefinitionBN(_T("apl_appearance_requirement_relationship"), _T("option"));

		m_data->NET_FindInstancesWithAttrValues(e_app_req_rel, 2, &tst_values[0], ext, false);

		if (ext.GetSize() > 0)
			map.Add((long)extAppOptRels[iIndex], (long)ext[0]);
		else
			ext_copy.Add(extAppOptRels[iIndex]);
	}

	// Загрузка типов документов (loggbook)
	//Пока импортируем только типы документов. если такого нет, то копируем со структурой. если такой есть, то не копируем совсем.
	prgs_dlg.SetText( APL_T("Поиск типов документов (ИЛП)"));prgs_dlg.SetRange(extPrd.Size);
	CaplEntity *e_logbook = m_api->m_data.GetEntityBN(_T("apl_logbook"));
	aplExtent logbooks;
	aplExtent logbook_items;
	m_FileData->GetEntityExtentBN(_T("apl_logbook"), logbooks);
	m_FileData->GetEntityExtentBN(_T("apl_logbook_item"), logbook_items);
	ext.Clear();
	for(i=0;i<logbooks.Size;i++)
	{
		INC_PRGS_POS(i, logbooks.Size);
		m_FileData->GetAttrBN(logbooks[i], _T("id"), id);
		tst_values[0].value.Set(id);
		tst_values[0].attr=m_api->m_data.GetAttrDefinitionBN(_T("apl_logbook"), _T("id"));
		m_data->NET_FindInstancesWithAttrValues(e_logbook, 1, &tst_values[0], ext, false);
		if(ext.Size>0)
			map.Add((long)logbooks[i],(long)ext[0]);
		else
		{
			m_FileData->GetAttrBN(logbooks[i], _T("items"), ext);
			ext_copy.Append(ext);
		}
		ext_copy.Add(extPrd[i]);
	}

	// Загрузка изделий
	m_FileData->GetEntityExtent(m_fileApi->m_prd_mgr.e_prd, extPrd);
	m_FileData->GetEntityExtent(m_fileApi->m_prd_mgr.e_pdf, extPdf);
	m_FileData->GetEntityExtentBN(_T("product_definition_relationship"), extPdr);
	m_FileData->GetEntityExtent(m_fileApi->m_prd_mgr.e_pd_eff, extEff);

	prgs_dlg.SetText( APL_T("Поиск изделий"));prgs_dlg.SetRange(extPrd.Size);
	for(i=0;i<extPrd.Size;i++)
	{
		INC_PRGS_POS(i,5);
		m_FileData->GetAttr(extPrd[i],m_fileApi->m_prd_mgr.a_prd_id,id);

		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_prd_mgr.a_prd_id;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_prd_mgr.e_prd,1,&tst_values[0],ext,false);

		if(ext.Size>0) map.Add((long)extPrd[i],(long)ext[0]);
		//else
			ext_copy.Add(extPrd[i]);
	}

	prgs_dlg.SetText( APL_T("Поиск версий изделий"));prgs_dlg.SetRange(extPdf.Size);
	for(i=0;i<extPdf.Size;i++)
	{
		INC_PRGS_POS(i,5);
		m_FileData->GetAttr(extPdf[i],m_fileApi->m_prd_mgr.a_pdf_id,id);
		m_FileData->GetAttr(extPdf[i],m_fileApi->m_prd_mgr.a_pdf_prd,inst0);
		inst1=(CaplInstance*)map.QGetPointerByIn((long)inst0);
		
		// поиск состава в файле		
		if(m_ImportProductStruct)
		{				
 			m_fileApi->m_prd_mgr.LoadAllSubProductEx(0,0,extPdf[i], ext_rel,ext1, false);
 			m_fileApi->m_prd_mgr.LoadAllZagotov(extPdf[i], ext_rel1, ext2, true);
		}

		if((inst1!=0)&&((long)inst1!=-1))
		{
			tst_values[0].value.Set((LPCTSTR)id);
			tst_values[0].attr=m_api->m_prd_mgr.a_pdf_id;
			tst_values[1].value.Set(inst1);
			tst_values[1].attr=m_api->m_prd_mgr.a_pdf_prd;

			m_data->NET_FindInstancesWithAttrValues(m_api->m_prd_mgr.e_pdf,2,&tst_values[0],ext,false);
			
			if(ext.Size>0)
			{
				map.Add((long)extPdf[i],(long)ext[0]);
				
				// обрабатываем состав (связи), только если стоит галочка
				// иначе загрузятся только изделия
				if(m_ImportProductStruct)
				{				
					if(ext_rel.Size>0)
					{	
						// Очистка состава в базе
						m_api->m_prd_mgr.LoadAllSubProductEx(0,0,ext[0],ext_rel,ext1);
						for(j=0;j<ext_rel.Size;j++){
							// применяемости!
							m_api->m_prd_mgr.FindAllPDFEffectiviti(ext_rel[j],ext_eff);
							for(int k=0;k<ext_eff.GetSize();k++){
								m_data->DeleteInstance(ext_eff[k], false);
							}
							m_data->DeleteInstance(ext_rel[j], false);
						}
					}

					if(ext_rel1.Size>0)
					{
						// Очистка материалов в базе
						m_api->m_prd_mgr.LoadAllZagotov(ext[0], ext_rel1, ext2, true);
						for(j=0;j<ext_rel1.Size;j++){
							// применяемости!
							m_api->m_prd_mgr.FindAllPDFEffectiviti(ext_rel1[j],ext_eff);
							for(int k=0;k<ext_eff.GetSize();k++){
								m_data->DeleteInstance(ext_eff[k], false);
							}
							m_data->DeleteInstance(ext_rel1[j], false);
						}
					}
				}
			}
		}
		ext_copy.Add(extPdf[i]);
	}	
	
	if(m_ImportProductStruct)
	{
		for(i=0;i<extPdr.Size;i++)
			ext_copy.Add(extPdr[i]);// Загрузка состава изделия
		for(i=0;i<extEff.Size;i++)
			ext_copy.Add(extEff[i]);// Загрузка применяемостей
	}

	if(m_ImportBP) ImportBP(map, ext_copy, prgs_count);
	if(m_ImportProductInst) ImportPI(map, ext_copy, prgs_count);

	// Загрузка требований
	aplExtent ext_req;
	aplExtent aePictures;

	if(m_ImportRequirement)
	{
		m_FileData->GetEntityExtent(m_fileApi->m_req_mgr.e_requirement, ext_req);
		for(i=0; i<ext_req.Size; i++)
		{
			m_FileData->GetAttr(ext_req[i], m_fileApi->m_req_mgr.a_req_pictures, aePictures);

			ext_copy.Append(aePictures);
			ext_copy.Add(ext_req[i]);
		}	
	}

	aplExtent ext_doc, extUpdatedDoc;
	if(m_ImportAssDocuments)
	{
		// Загрузка документов
		int iForceDocVerDateChange=0;
		m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Настройка документов\\Заменять дату активной версии при импорте"),iForceDocVerDateChange, 0);
		
		CString sBuf, sDkvd, sKdvzohi, sPart;;
		//CaplInstance *af;
		CaplInstance *dt, *file_dt;
		prgs_dlg.SetText( APL_T("Поиск документов"));prgs_dlg.SetRange(ext_doc.Size);

		m_FileData->GetEntityExtent(m_fileApi->m_doc_mgr.e_doc, ext_doc);
		for(i=0; i<ext_doc.Size; i++)
		{
			INC_PRGS_POS(i,ext_doc.Size);
			m_FileData->GetAttr(ext_doc[i],m_fileApi->m_doc_mgr.a_doc_id,id);
			m_FileData->GetAttr(ext_doc[i],m_fileApi->m_doc_mgr.a_doc_kind, file_dt);

			dt = NULL;
			if(file_dt)
			{
				m_FileData->GetAttr(file_dt, m_fileApi->m_doc_mgr.a_dt_pdt, sBuf);
				dt = m_api->m_doc_mgr.GetDocumentTypeBN(sBuf);
			}

			tst_values[0].value.Set((LPCTSTR)id);
			tst_values[0].attr=m_api->m_doc_mgr.a_doc_id;
			tst_values[1].value.Set(dt);
			tst_values[1].attr=m_api->m_doc_mgr.a_doc_kind;
			//m_data->NET_FindInstancesWithAttrValues(m_api->m_doc_mgr.e_apl_doc, 2, &tst_values[0], ext, false);

			m_FileData->GetAttr(ext_doc[i],m_fileApi->m_doc_mgr.a_doc_add_dt_code,sDkvd);
			tst_values[2].value.Set(sDkvd);
			tst_values[2].attr=m_api->m_doc_mgr.a_doc_add_dt_code;

			m_FileData->GetAttr(ext_doc[i],m_fileApi->m_doc_mgr.a_doc_code_depend_desp,sKdvzohi);
			tst_values[3].value.Set(sKdvzohi);
			tst_values[3].attr=m_api->m_doc_mgr.a_doc_code_depend_desp;

			m_FileData->GetAttr(ext_doc[i],m_fileApi->m_doc_mgr.a_doc_part,sPart);
			tst_values[4].value.Set(sPart);
			tst_values[4].attr=m_api->m_doc_mgr.a_doc_part;

			m_data->NET_FindInstancesWithAttrValues(m_api->m_doc_mgr.e_apl_doc, 5, &tst_values[0], ext, false);

			if(ext.Size>0)
			{
				CaplInstance *db_doc=ext[0], *db_rev=0;
				CaplInstance *file_rev;
				CString file_rev_id;
				map.Add((long)ext_doc[i],(long)db_doc);
				aplExtent ext_db_rev;

				m_FileData->GetAttr(ext_doc[i],m_fileApi->m_doc_mgr.a_apl_doc_active,file_rev);
				m_FileData->GetAttr(file_rev,m_fileApi->m_doc_mgr.a_apl_doc_rev_id,file_rev_id);

				// Поиск версии с таким-же обозначением.
				tst_values[0].value.Set((LPCTSTR)file_rev_id);
				tst_values[0].attr=m_api->m_doc_mgr.a_apl_doc_rev_id;
				tst_values[1].value.Set(db_doc);
				tst_values[1].attr=m_api->m_doc_mgr.a_apl_doc_rev_doc;
				m_data->NET_FindInstancesWithAttrValues(m_api->m_doc_mgr.e_apl_doc_rev, 2, &tst_values[0], ext_db_rev, false);

				if(ext_db_rev.Size>0)
				{
					db_rev=ext_db_rev[0];

					CaplLoadData ld(m_data,DEF_SOURCE);
					ld.AddQuery(0,db_rev,true);
					ld.LoadEx();
					
					COleDateTime time;
					m_api->aplGetCurrentTime(time);		

					// копируем реквизиты версии
					CString t_str;
					aplExtent aeRevEntryVals, aeExt;
					CaplInstance *cit = NULL, *ciNewEntryVal = NULL, *ciEntry=0;

					/* ЯАИ  копировать реквизиты в существующую версию - так себе идея
					m_fileApi->m_data.GetAttr(file_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_entries, aeRevEntryVals);						
					for(int s=0; s<aeRevEntryVals.GetSize(); s++)
					{
						ciNewEntryVal = m_data->CreateInstance(m_api->m_doc_mgr.e_doc_entry_val);

						if(ciNewEntryVal)
						{
							m_FileData->GetAttr(aeRevEntryVals[s], m_fileApi->m_doc_mgr.a_doc_entry_val_descr, t_str);
							m_api->m_data.PutAttr(ciNewEntryVal, m_api->m_doc_mgr.a_doc_entry_val_descr, t_str);

							m_FileData->GetAttr(aeRevEntryVals[s], m_fileApi->m_doc_mgr.a_doc_entry_val_prev, cit);
							m_api->m_data.PutAttr(ciNewEntryVal, m_api->m_doc_mgr.a_doc_entry_val_prev, cit);

							m_FileData->GetAttr(aeRevEntryVals[s], m_fileApi->m_doc_mgr.a_doc_entry_val_val, t_str);
							m_api->m_data.PutAttr(ciNewEntryVal, m_api->m_doc_mgr.a_doc_entry_val_val, t_str);

							m_FileData->GetAttr(aeRevEntryVals[s], m_fileApi->m_doc_mgr.a_doc_entry_val_entry, cit);
							if(cit)
							{
								m_FileData->GetAttr(cit, m_fileApi->m_doc_mgr.a_entry_name, t_str);
								ciEntry = m_api->m_doc_mgr.GetEntryBN(t_str);

								if(ciEntry)
								{
									m_api->m_data.PutAttr(ciNewEntryVal, m_api->m_doc_mgr.a_doc_entry_val_entry, ciEntry);
									map.Add((long)cit, (long)ciEntry);
								}
								else
								{
									ext_copy.Add(cit);
								}
							}

							aeExt.Add(ciNewEntryVal);
						}
					}

					m_api->m_data.PutAttr(db_rev, m_api->m_doc_mgr.a_apl_doc_rev_entries, aeExt);
					*/

					// Сравниваем CRC
					int crc_1,crc_2;
					m_api->m_data.GetAttr(db_rev, m_api->m_doc_mgr.a_apl_doc_rev_crc, crc_1);
					m_FileData->GetAttr(file_rev,m_fileApi->m_doc_mgr.a_apl_doc_rev_crc,crc_2);
					if(crc_1==crc_2)
					{
						// Делаем версию активной и выходим.
						m_data->PutAttr(db_doc,m_api->m_doc_mgr.a_apl_doc_active,db_rev);
						if(iForceDocVerDateChange==1)//если установлена опция, меняем дату активной версии (это позволит отследить все свежезагруженные документы)
						{
							aplDate2String(time,buf);
							m_data->PutAttr(db_rev,m_api->m_doc_mgr.a_apl_doc_rev_end_s,buf);
						}
						continue;
					}
					// Переименовываем старую
					m_api->m_data.GetAttr(db_rev, m_api->m_doc_mgr.a_apl_doc_rev_id, id);
					buf.Format(_T("%s replaced %s %s"), id, time.Format(VAR_DATEVALUEONLY), time.Format(_T("%H:%M:%S")));
					m_api->m_data.PutAttr(db_rev, m_api->m_doc_mgr.a_apl_doc_rev_id, buf);

					db_rev=0;					
				}
				
				/* ayatsk - изменена логика
				// Чтенение активной версии
				CaplInstance *inst_old_rev;
				CaplLoadData ld(m_data,DEF_SOURCE);
				j=ld.AddQuery(_T('i'), db_doc->GetId(), 0,m_api->m_doc_mgr.a_apl_doc_active, true,true);
				  ld.AddQuery(_T('d'), j, 0,m_api->m_doc_mgr.a_apl_doc_rev_access_form, true,true);
				ld.LoadEx();

				m_data->GetAttr(db_doc,m_api->m_doc_mgr.a_apl_doc_active,inst_old_rev);
				if(inst_old_rev==0){
					extUpdatedDoc.Add(ext_doc[i]);continue;
				}

				m_data->GetAttr(inst_old_rev, m_api->m_doc_mgr.a_apl_doc_rev_crc, k_1);

				m_FileData->GetAttr(ext_doc[i],m_fileApi->m_doc_mgr.a_apl_doc_active,inst0);
				//m_FileData->GetAttr(inst0,m_fileApi->m_doc_mgr.a_apl_doc_rev_id,id);
				if(inst0==0){
					extUpdatedDoc.Add(ext_doc[i]);continue;
				}
				m_FileData->GetAttr(inst0,m_fileApi->m_doc_mgr.a_apl_doc_rev_crc,k);

				if(k==k_1)// crc активных версий совпадают
				{
					m_FileData->GetAttr(inst0, m_fileApi->m_doc_mgr.a_apl_doc_rev_access_form, af);
					map.Add((long)inst0,(long)inst_old_rev);
					//Обновляем af сейчас
					CaplInstance *af_old;
					CString sBuf, sBuf2;

					m_data->GetAttr(inst_old_rev, m_api->m_doc_mgr.a_apl_doc_rev_access_form, af_old);
					m_fileApi->m_data.GetAttr(af, m_fileApi->m_doc_mgr.a_apl_stored_document_file_name, sBuf);
					m_api->m_data.PutAttr(af_old, m_api->m_doc_mgr.a_apl_stored_document_file_name, sBuf);
					m_fileApi->m_data.GetAttr(af, m_fileApi->m_doc_mgr.a_apl_stored_document_code, sBuf);
					m_api->m_data.PutAttr(af_old, m_api->m_doc_mgr.a_apl_stored_document_code, sBuf);

					CString sFileName;
					CString sCode;
					aplExtent pics, tmp_pics;
					bool bAdd = false;
					CaplInstance *sd;
					long code;
					m_fileApi->m_data.GetAttr(inst0, m_fileApi->m_doc_mgr.a_apl_doc_rev_pictures, pics);
					m_api->m_data.GetAttr(inst_old_rev, m_api->m_doc_mgr.a_apl_doc_rev_pictures, tmp_pics);
					for(j=0; j<pics.GetSize(); j++)
					{
						bAdd = true;
						m_fileApi->m_data.GetAttr(pics[j], m_api->m_doc_mgr.a_apl_stored_document_code, sCode);
						m_fileApi->m_data.GetAttr(pics[j], m_fileApi->m_doc_mgr.a_apl_stored_document_source, sFileName);
						//проверяем уникальность по коду и имени файла
						for(int u=0; u<tmp_pics.Size; u++)
						{
							m_api->m_data.GetAttr(tmp_pics[u], m_api->m_doc_mgr.a_apl_stored_document_source, sBuf);
							m_api->m_data.GetAttr(tmp_pics[u], m_api->m_doc_mgr.a_apl_stored_document_code, sBuf2);
							if(sBuf.CompareNoCase(sFileName)==0 && sBuf2.CompareNoCase(sCode)==0) {bAdd = false; break;}
						}

						if(!bAdd) continue;

						sd = NULL;
						
						if(packet!=NULL)
						{
							CString sName;
							for(j=0; j<pds_ext.Size; j++)
							{
								m_api->m_data.GetAttr(pds_ext[j], a_file_ds_name, sName);
								if(sName.CompareNoCase(sFileName)==0)
								{
									m_api->m_data.GetAttr(pds_ext[j], a_file_ds_source, sd);
									break;
								}
							}
						}
						if(sd==NULL)
						{
							sFileName = m_InPath+sFileName;
							sd = m_api->m_data.CreateInstance(m_api->m_doc_mgr.e_apl_stored_document);
							m_api->m_data.NET_SaveBlob(sd, m_api->m_doc_mgr.a_apl_stored_document_source, sFileName, code, buf);
						}
						m_fileApi->m_data.GetAttr(pics[j], m_fileApi->m_doc_mgr.a_apl_stored_document_file_name, sFileName);
						m_api->m_data.PutAttr(sd, m_api->m_doc_mgr.a_apl_stored_document_file_name, sFileName);
						m_fileApi->m_data.GetAttr(pics[j], m_fileApi->m_doc_mgr.a_apl_stored_document_code, sFileName);
						m_api->m_data.PutAttr(sd, m_api->m_doc_mgr.a_apl_stored_document_code, sFileName);
						tmp_pics.Add(sd);
					}
					m_api->m_data.PutAttr(inst_old_rev, m_api->m_doc_mgr.a_apl_doc_rev_pictures, tmp_pics);

					
				}
				else
				{
					TRACE(APL_T("Не совпали crc32 %s\n"), id);
					extUpdatedDoc.Add(ext_doc[i]);
				}*/
			}
			//else 
				extUpdatedDoc.Add(ext_doc[i]);

			ext_copy.Add(ext_doc[i]);						
		}
	}
	if(m_ImportProductInst)
	{
		aplExtent prd_inst, prd_lot;
		m_FileData->GetEntityExtent(m_fileApi->m_prd_inst_mgr.e_prd_inst, prd_inst);
		
		for(i= 0; i<prd_inst.GetSize(); i++)
		{
			CaplInstance* pdf= NULL;
			m_FileData->GetAttr(prd_inst[i], m_fileApi->m_prd_inst_mgr.a_prd_inst_pdf, pdf);
			CaplInstance* pdf_db=(CaplInstance*)map.QGetPointerByIn((long)pdf);
			if(pdf_db!=0)
			{
				m_FileData->GetAttr(prd_inst[i], m_fileApi->m_prd_inst_mgr.a_prd_inst_id, id);
				tst_values[0].value.Set((LPCTSTR)id);
				tst_values[0].attr= m_api->m_prd_inst_mgr.a_prd_inst_id;

				tst_values[1].value.Set(pdf_db);
				tst_values[1].attr= m_api->m_prd_inst_mgr.a_prd_inst_pdf;
				m_data->NET_FindInstancesWithAttrValues(m_api->m_prd_inst_mgr.e_prd_inst,2,&tst_values[0],ext,false);
				
				if(ext.GetSize()>0)
				{
					m_api->LoadExtentInfo(ext);
					map.Add((long)prd_inst[i],(long)ext[0]);
					aplExtent rel, extt;
					m_api->m_prd_inst_mgr.LoadInsertedInstances(ext[0],rel,extt);
					for(int r=0; r<rel.Size;r++)
						m_data->DeleteInstance(rel[r]);
				}
				else
					ext_copy.Add(prd_inst[i]);
			}
			else
				ext_copy.Add(prd_inst[i]);
		}

		m_FileData->GetEntityExtent(m_fileApi->m_prd_inst_mgr.e_lot, prd_lot);		
		ext_copy.Append(prd_lot);
	}
	
	// Непосредственно копирование данных
	prgs_dlg.SetText( APL_T("Копирование данных ..."));prgs_dlg.SetRange(0);prgs_dlg.SetPos(0);
	CopyData(ext_copy,map,m_data);
	ext_copy.Clear();
	prgs_dlg.SetText( APL_T("Сохранение данных ..."));
	m_data->NET_SaveChanges();

	// Загрузка справочников - дополнительная настройка
	if(m_ImportClassifiers)
	{
		// системы
		aplExtent ext_classif_s,ext_classif_l,ext_file,ext_api,ext_add;
		CaplInstance *inst_s_file,*inst_s_api,*inst_l_file,*inst_l_api;
		CString temp_name,name;
		int j,k;
		bool not_found;
		m_FileData->GetEntityExtent(m_fileApi->m_classifier_mgr.e_apl_classifier_system, ext_classif_s);
		for(i=0; i<ext_classif_s.Size; i++) 
		{
			INC_PRGS_POS(i,5);
			// дополнение уровней, входящих в справочник
			inst_s_file=ext_classif_s[i];
			m_FileData->GetAttr(inst_s_file,
				m_fileApi->m_classifier_mgr.a_apl_classifier_system_childs,ext_file);
			inst_s_api=(CaplInstance*)map.QGetPointerByIn((long)inst_s_file);
			if(inst_s_api==0){
				continue;
			}

			m_api->m_data.GetAttr(inst_s_api,
				m_api->m_classifier_mgr.a_apl_classifier_system_childs,ext_api);
			not_found=true;
			ext_add.Clear();
			for(j=0;j<ext_file.GetSize();j++){
				inst_l_file=ext_file[j];
				inst_l_api=(CaplInstance*)map.QGetPointerByIn((long)inst_l_file);
				if(inst_l_api==0){
					continue;
				}
				for(k=0;k<ext_api.GetSize();k++){
					if(ext_api[k]==inst_l_api){
						not_found=false;break;
					}
				}
				if(not_found){
					ext_add.Add(inst_l_api);
				}
			}
			ext_api.Append(ext_add);

			// эскизы для справочника
			ImportClassifierEsquisse(inst_s_api,inst_s_file);

		}
		
		// эскизы для уровней
		
		m_FileData->GetEntityExtent(m_fileApi->m_classifier_mgr.e_apl_classifier_level, ext_classif_l);
		for(i=0; i<ext_classif_l.Size; i++)
		{
			INC_PRGS_POS(i,5);
			inst_l_file=ext_classif_l[i];
			inst_l_api=(CaplInstance*)map.QGetPointerByIn((long)inst_l_file);
			if(inst_l_api==0){
				continue;
			}
			ImportClassifierEsquisse(inst_l_api,inst_l_file);

		}
		
	
		// формы
	}

	if(m_ImportAssDocuments)
	{
		bool curr_ModeInteractive=m_api->m_ModeInteractive;
		m_api->m_ModeInteractive=false;
		// Обновление содержимого документов
		prgs_dlg.SetText( APL_T("Обновление содержимого документов"));prgs_dlg.SetRange(extUpdatedDoc.Size);
		for(i=0; i<extUpdatedDoc.Size; i++)
		{
			INC_PRGS_POS(i,1);
			m_fileApi->m_doc_mgr.GetFileName(extUpdatedDoc[i],buf);
			name=m_InPath+buf;

			CaplInstance *doc=(CaplInstance*)map.QGetPointerByIn((long)extUpdatedDoc[i]);
			if(doc==0) continue;

			CaplInstance *inst_old_rev;
			m_data->GetAttr(doc,m_api->m_doc_mgr.a_apl_doc_active,inst_old_rev);
			
			//Тело
			CaplInstance *a_rev, *file_af, *db_af, *old_aver, *tst_inst;
			long code = 0;
			int max_id = 0;
			int i_crc = 0;
			CString sFileName=name;
			CString sBuf, doc_rev_id;
			m_fileApi->m_data.GetAttr(extUpdatedDoc[i], m_fileApi->m_doc_mgr.a_apl_doc_active, a_rev);
			if(a_rev)
			{
				m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_access_form, file_af);
				if(file_af)
				{
					m_fileApi->m_data.GetAttr(file_af, m_fileApi->m_doc_mgr.a_apl_stored_document_source, sFileName);
					if(packet==NULL)
					{
						sFileName = m_InPath+sFileName;
						if(bLoadFromPacket) sFileName=name;
						inst0=m_api->m_doc_mgr.CreateDocumentRevision(doc, sFileName, true, true);
						if(inst0==NULL) continue;

						// при импорте документов с состоянием _T("approved") надо ручками делать версию активной
						m_api->m_data.GetAttr(doc,m_api->m_doc_mgr.a_apl_doc_active,tst_inst);
						if(tst_inst==0)
						{
							m_api->m_data.PutAttr(doc,m_api->m_doc_mgr.a_apl_doc_active,inst0);
						}
						
						// так же ручками копируем атрибуты версии документа
						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_id, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_id, buf);
						
						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_descr, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_descr, buf);
						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_label, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_label, buf);
						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_litera, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_litera, buf);

						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_format, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_format, buf);
						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_sheets, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_sheets, buf);
						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_total_sheets, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_total_sheets, buf);
						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_total_sheets_count_a4, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_total_sheets_count_a4, buf);

						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_user, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_user, buf);
						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_start_s, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_start_s, buf);
						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_end_s, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_end_s, buf);

						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_src_date, buf);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_src_date, buf);
						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_crc, i_crc);
						m_data->PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_crc, i_crc);

						m_api->m_data.GetAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_access_form, db_af);
						//ayatsk не понял смысла
						//m_api->m_data.NET_SaveBlob(db_af, m_api->m_doc_mgr.a_apl_stored_document_source, sFileName, code, buf);
						
						// копируем реквизиты версии
						CString t_str;
						aplExtent aeRevEntryVals, aeExt;
						CaplInstance *cit = NULL, *ciNewEntryVal = NULL, *ciEntry=0;

						m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_entries, aeRevEntryVals);						
						for(int s=0; s<aeRevEntryVals.GetSize(); s++)
						{
							ciNewEntryVal = m_data->CreateInstance(m_api->m_doc_mgr.e_doc_entry_val);

							if(ciNewEntryVal)
							{
								m_FileData->GetAttr(aeRevEntryVals[s], m_fileApi->m_doc_mgr.a_doc_entry_val_descr, t_str);
								m_api->m_data.PutAttr(ciNewEntryVal, m_api->m_doc_mgr.a_doc_entry_val_descr, t_str);

								m_FileData->GetAttr(aeRevEntryVals[s], m_fileApi->m_doc_mgr.a_doc_entry_val_prev, cit);
								m_api->m_data.PutAttr(ciNewEntryVal, m_api->m_doc_mgr.a_doc_entry_val_prev, cit);

								m_FileData->GetAttr(aeRevEntryVals[s], m_fileApi->m_doc_mgr.a_doc_entry_val_val, t_str);
								m_api->m_data.PutAttr(ciNewEntryVal, m_api->m_doc_mgr.a_doc_entry_val_val, t_str);

								m_FileData->GetAttr(aeRevEntryVals[s], m_fileApi->m_doc_mgr.a_doc_entry_val_entry, cit);
								if(cit)
								{
									m_FileData->GetAttr(cit, m_fileApi->m_doc_mgr.a_entry_name, t_str);
									ciEntry = m_api->m_doc_mgr.GetEntryBN(t_str);

									if(ciEntry)
									{
										m_api->m_data.PutAttr(ciNewEntryVal, m_api->m_doc_mgr.a_doc_entry_val_entry, ciEntry);
										map.Add((long)cit, (long)ciEntry);
									}
									else
									{
										ext_copy.Add(cit);
									}
								}

								aeExt.Add(ciNewEntryVal);
							}
						}

						m_api->m_data.PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_entries, aeExt);
					}
					else //Искаем среди наших
					{
						db_af = NULL;
						CString sName;
						for(j=0; j<pds_ext.Size; j++)
						{
							m_api->m_data.GetAttr(pds_ext[j], a_file_ds_name, sName);
							if(sName.CompareNoCase(sFileName)==0)
							{
								m_api->m_data.GetAttr(pds_ext[j], a_file_ds_source, db_af);
								break;
							}
						}
						if(!db_af) 
						{
							TRACE(_T("db_af=0 %s\n"), sFileName);
							return false;
						}
						//Создаем версию
						m_api->m_data.GetAttr(doc, m_api->m_doc_mgr.a_apl_doc_active, old_aver);
						
						if(m_data->IsConnected())
						{
							CaplLoadData ld(m_data,DEF_SOURCE);
							int iNum = ld.AddQuery(_T('b'), doc->GetId(), m_api->m_doc_mgr.e_apl_doc_rev, m_api->m_doc_mgr.a_apl_doc_rev_doc, true);
							ld.AddQuery(_T('d'), iNum, 0, m_api->m_doc_mgr.a_apl_doc_rev_doc, true);
							ld.AddQuery(_T('d'), iNum, 0, m_api->m_doc_mgr.a_apl_doc_rev_id, true);
							ld.LoadEx();
						}
						
						aplExtent ext_rev;
						int max_id=-1;
						int tmp;
						m_data->GetEntityExtent(m_api->m_doc_mgr.e_apl_doc_rev, ext_rev);
						for(j=0; j<ext_rev.Size; j++)
						{
							m_data->GetAttr(ext_rev[j], m_api->m_doc_mgr.a_apl_doc_rev_doc, tst_inst);
							if(tst_inst==doc)
							{
								m_data->GetAttr(ext_rev[j], m_api->m_doc_mgr.a_apl_doc_rev_id, buf);
								tmp=_atoi(buf);
								if(tmp>max_id) max_id=tmp;
							}
						}
						max_id++;
						doc_rev_id.Format(_T("%d"),max_id);
						//Создаем для документа активную версию и связываем её с сторед документ в БД.
						CaplInstance *doc_ver;
						m_api->GetItemName(m_api->m_data.GetCurrUser(), buf);
						inst0 = doc_ver = m_api->m_data.CreateInstance(m_api->m_doc_mgr.e_apl_digital_document);
						m_api->m_data.PutAttr(doc, m_api->m_doc_mgr.a_apl_doc_active, doc_ver);
						m_api->m_data.PutAttr(doc_ver, m_api->m_doc_mgr.a_apl_doc_rev_id, doc_rev_id);
						m_api->m_data.PutAttr(doc_ver, m_api->m_doc_mgr.a_apl_doc_rev_doc, doc);
						m_api->m_data.PutAttr(doc_ver, m_api->m_doc_mgr.a_apl_doc_rev_base, old_aver);
						m_api->m_data.PutAttr(doc_ver, m_api->m_doc_mgr.a_apl_doc_rev_user, m_api->m_appr_mgr.GetOperatorName()); // Установка автора
						
						{
							int crc32 = -1;
							long size;
							BYTE* pBlobBuf = NULL;
							//Вычисляем CRC32 для блоба в БД
							m_api->m_data.NET_GetBlobSize(db_af, m_api->m_doc_mgr.a_apl_stored_document_source, size);
							if(size>0)
							{
								pBlobBuf = new BYTE[size];
								m_api->m_data.NET_LoadBlob2Memory(db_af, m_api->m_doc_mgr.a_apl_stored_document_source, pBlobBuf,size);
								crc32 = GetCRC32((char*)pBlobBuf, size);
								delete [] pBlobBuf;
							}
							m_api->m_data.PutAttr(doc_ver, m_api->m_doc_mgr.a_apl_doc_rev_access_form, db_af);
							m_api->m_data.PutAttr(doc_ver, m_api->m_doc_mgr.a_apl_doc_rev_crc, crc32);
						}
					}
					m_fileApi->m_data.GetAttr(file_af, m_fileApi->m_doc_mgr.a_apl_stored_document_file_name, sFileName);
					m_api->m_data.PutAttr(db_af, m_api->m_doc_mgr.a_apl_stored_document_file_name, sFileName);
					m_fileApi->m_data.GetAttr(file_af, m_fileApi->m_doc_mgr.a_apl_stored_document_code, sBuf);
					m_api->m_data.PutAttr(db_af, m_api->m_doc_mgr.a_apl_stored_document_code, sBuf);
				}
				CaplInstance *sd;
				aplExtent pics, tmp_pics;
				m_fileApi->m_data.GetAttr(a_rev, m_fileApi->m_doc_mgr.a_apl_doc_rev_pictures, pics);
				for(j=0; j<pics.GetSize(); j++)
				{
					m_fileApi->m_data.GetAttr(pics[j], m_fileApi->m_doc_mgr.a_apl_stored_document_source, sFileName);
					sd = NULL;

					if(packet!=NULL)
					{
						CString sName;
						int j1;
						for(j1=0; j1<pds_ext.Size; j1++)
						{
							m_api->m_data.GetAttr(pds_ext[j1], a_file_ds_name, sName);
							if(sName.CompareNoCase(sFileName)==0)
							{
								m_api->m_data.GetAttr(pds_ext[j1], a_file_ds_source, sd);
								break;
							}
						}
						if(sd==NULL)
							return false;
					}
					if(sd==NULL)
					{
						sFileName = m_InPath+sFileName;
						sd = m_api->m_data.CreateInstance(m_api->m_doc_mgr.e_apl_stored_document);
						m_api->m_data.NET_SaveBlob(sd, m_api->m_doc_mgr.a_apl_stored_document_source, sFileName, code, buf);
					}

					m_fileApi->m_data.GetAttr(pics[j], m_fileApi->m_doc_mgr.a_apl_stored_document_file_name, sFileName);
					m_api->m_data.PutAttr(sd, m_api->m_doc_mgr.a_apl_stored_document_file_name, sFileName);
					m_fileApi->m_data.GetAttr(pics[j], m_fileApi->m_doc_mgr.a_apl_stored_document_code, sFileName);
					m_api->m_data.PutAttr(sd, m_api->m_doc_mgr.a_apl_stored_document_code, sFileName);
					tmp_pics.Add(sd);
				}
				m_api->m_data.PutAttr(inst0, m_api->m_doc_mgr.a_apl_doc_rev_pictures, tmp_pics);				
			}
			
			m_FileData->GetAttr(extUpdatedDoc[i],m_fileApi->m_doc_mgr.a_apl_doc_active,inst1);
			map.Add((long)inst1,(long)inst0);

			// ayatsk 2007_10_15  не работает (нулевые атрибуты типа m_api->m_doc_mgr.a_apl_doc_change_id)
			/*
			// Создание изменения
			if(inst_old_rev!=0)
			{
				CaplInstance *po=0,*change=m_data->CreateInstance(m_api->m_doc_mgr.e_apl_doc_change);
				m_data->PutAttr(change,m_api->m_doc_mgr.a_apl_doc_change_id,ChangeId);
				//m_data->PutAttr(change,m_api->m_doc_mgr.a_apl_doc_change_name,m_change_name);
				m_data->PutAttr(change,m_api->m_doc_mgr.a_apl_doc_change_basis,ChangeBase);
				m_data->PutAttr(change,m_api->m_doc_mgr.a_apl_doc_change_descr,ChangeDescr);
				m_data->PutAttr(change,m_api->m_doc_mgr.a_apl_doc_change_user,m_data->GetNameCurrUser());
				CaplInstance*user=((CaplNetStepData*)m_data)->GetCurrUser();
				m_data->GetAttrBN(user,_T("personality"),po);
				if(po)
				{
					if(m_api->m_data.IsKindOf(po, m_api->m_appr_mgr.e_pers_org))
						m_data->GetAttr(po, m_api->m_appr_mgr.a_po_the_pers, po);
					m_data->PutAttr(change,m_api->m_doc_mgr.a_apl_doc_change_person,po);
				}

				COleDateTime odt=COleDateTime::GetCurrentTime();
				CString s_date;
				aplDate2String(odt,s_date);
				m_data->PutAttr(change,m_api->m_doc_mgr.a_apl_doc_change_date_s,s_date);

				m_data->PutAttr(change,m_api->m_doc_mgr.a_apl_doc_change_doc,doc);
				m_data->PutAttr(change,m_api->m_doc_mgr.a_apl_doc_change_new,inst0);
				m_data->PutAttr(change,m_api->m_doc_mgr.a_apl_doc_change_old,inst_old_rev);
			}*/
		}

		// копирование связей документов
		ext_copy.Clear();
		CString sRefType;
		aplExtent ext_doc_ass;
		m_FileData->GetEntityExtent(m_fileApi->m_doc_mgr.e_apl_doc_ref, ext_doc_ass);
		for(i=0; i<ext_doc_ass.Size; i++)
		{
			m_FileData->GetAttr(ext_doc_ass[i],m_fileApi->m_doc_mgr.a_apl_doc_ref_item,inst0);
			inst0=(CaplInstance*)map.QGetPointerByIn((long)inst0);
			if(inst1==0) {ext_copy.Add(ext_doc_ass[i]); continue;}
			m_FileData->GetAttr(ext_doc_ass[i],m_fileApi->m_doc_mgr.a_apl_doc_ref_doc,inst1);
			inst1=(CaplInstance*)map.QGetPointerByIn((long)inst1);
			if(inst1==0){ext_copy.Add(ext_doc_ass[i]); continue;}

			tst_values[0].value.Set(inst0);
			tst_values[0].attr=m_api->m_doc_mgr.a_apl_doc_ref_item;
			tst_values[1].value.Set(inst1);
			tst_values[1].attr=m_api->m_doc_mgr.a_apl_doc_ref_doc;
			m_FileData->GetAttr(ext_doc_ass[i],m_fileApi->m_doc_mgr.a_apl_doc_ref_type,sRefType);
			tst_values[2].value.Set(sRefType);
			tst_values[2].attr=m_api->m_doc_mgr.a_apl_doc_ref_type;
			m_data->NET_FindInstancesWithAttrValues(m_api->m_doc_mgr.e_apl_doc_ref,3,&tst_values[0],ext,false);
			
			if(ext.Size<=0) ext_copy.Add(ext_doc_ass[i]);
		}
		aplExtent groups;
		m_FileData->GetEntityExtent(m_fileApi->m_doc_mgr.e_dt_group,groups);
		for(i=0; i<groups.Size;i++)
		{
			CString id, name;
			m_FileData->GetAttr(groups[i],m_fileApi->m_doc_mgr.a_dt_group_id,id);
			tst_values[0].value.Set(id);
			tst_values[0].attr = m_api->m_doc_mgr.a_dt_group_id;
			m_FileData->GetAttr(groups[i],m_fileApi->m_doc_mgr.a_dt_group_name,name);
			tst_values[1].value.Set(name);
			tst_values[1].attr = m_api->m_doc_mgr.a_dt_group_name;
			m_data->NET_FindInstancesWithAttrValues(m_api->m_doc_mgr.e_dt_group,2,&tst_values[0], ext,false);
			if(ext.Size>0)
			{
				map.Add((long)groups[i],(long)ext[0]);
			}
			else ext_copy.Add(groups[i]);
		}
		CopyData(ext_copy,map,m_data);
		ext_copy.Clear();
		prgs_dlg.SetText( APL_T("Сохранение данных ..."));prgs_dlg.SetRange(0);prgs_dlg.SetPos(0);
		m_data->NET_SaveChanges();
		m_api->m_ModeInteractive=curr_ModeInteractive;
	}
	
	if(m_ImportProductInst)
	{
		aplExtent prd_inst_rels;
		m_FileData->GetEntityExtent(m_fileApi->m_prd_inst_mgr.e_prd_inst_rel, prd_inst_rels);		
		ext_copy.Append(prd_inst_rels);
	}

	if(m_ImportProductCharacteristics) 
		ImportCharacteristics(map,ext_copy, prgs_count);

	ImportChanges(map, ext_copy);

	// Загрузка статусов
	if(m_ImportApproval)
	{
		CaplInstance *inst_po, *inst_status;
		CString role;

		aplExtent ext_po_appr;
		m_FileData->GetEntityExtent(m_fileApi->m_appr_mgr.e_apl_appr_pers_org, ext_po_appr);
		
		prgs_dlg.SetText( APL_T("Импорт электронных подписей"));prgs_dlg.SetRange(ext_po_appr.Size);
		for(i=0; i<ext_po_appr.Size; i++)
		{
			INC_PRGS_POS(i,5);

			CaplInstance *appr=ext_po_appr[i];

			m_FileData->GetAttr(appr,m_fileApi->m_appr_mgr.a_appr_status,inst_status);
			inst_status=(CaplInstance*)map.GetByInP((long)inst_status);
			if(inst_status==0) 
				continue;
			m_FileData->GetAttr(appr,m_fileApi->m_appr_mgr.a_appr_pers_org,inst_po);
			inst_po=(CaplInstance*)map.GetByInP((long)inst_po);
			if(inst_po==0) 
				continue;
			
			
			m_FileData->GetAttr(appr,m_fileApi->m_appr_mgr.a_appr_item,inst0);
			inst1=(CaplInstance*)map.GetByInP((long)inst0);
			if(inst1!=0) 
			{
				if(inst1->GetId()!=0)
				{
					m_FileData->GetAttr(ext_po_appr[i],m_fileApi->m_appr_mgr.a_appr_role,role);

					// Проверка наличия такого статуса в базе
					tst_values[0].value.Set(inst1);
					tst_values[0].attr=m_api->m_appr_mgr.a_appr_item;
					tst_values[1].value.Set(inst_status);
					tst_values[1].attr=m_api->m_appr_mgr.a_appr_status;
					tst_values[2].value.Set(role);
					tst_values[2].attr=m_api->m_appr_mgr.a_appr_role;
					tst_values[3].value.Set(inst_po);
					tst_values[3].attr=m_api->m_appr_mgr.a_appr_pers_org;
				
					m_data->NET_FindInstancesWithAttrValues(m_api->m_appr_mgr.e_apl_appr_pers_org,4,&tst_values[0],ext,false);
				
					if(ext.Size>0) 
							continue;
				}
			}

			ext_copy.Add(ext_po_appr[i]);	

			aplExtent ext_entries;
			m_FileData->GetAttr(appr,m_fileApi->m_appr_mgr.a_appr_po_entries,ext_entries);
			int k;
			for(k=0;k<ext_entries.GetSize();k++) ext_copy.Add(ext_entries[k]);	
		}
	}


	// копируем данные
	CopyData(ext_copy,map,m_data);

	if(m_ImportProject) //Создаем новые версии для проектов
	{
		aplExtent ext_prj;
		m_FileData->GetEntityExtent(m_fileApi->m_project_mgr->e_project,ext_prj);
		for (i=0;i<ext_prj.Size;i++)
		{
			CaplInstance *prj=(CaplInstance*)map.GetByInP((long)ext_prj[i]);
			if(prj) m_api->m_project_mgr->CreateProjectVersion(prj);
		}
	}
	m_api->SaveChanges();

	// догружаем блобы сертификатов для статусов
	long code = 0;
	CString sFileName;
	CaplInstance *ciIn, *ciOut;
	for(i=0; i<map.Size; ++i)
	{
// 		ciIn = (CaplInstance*)map[i].in;
// 		ciOut = (CaplInstance*)map[i].out;
// 		if(!m_FileData->IsKindOf(ciIn, m_fileApi->m_appr_mgr.e_apl_appr_pers_org)) continue;
// 
// 		m_FileData->GetAttr(ciIn, m_fileApi->m_appr_mgr.a_appr_dg_sign_cert, sFileName);
// 		if(sFileName.IsEmpty()) continue;
// 
// 		sFileName = m_InPath+sFileName;
// 		m_api->m_data.PutAttr(ciOut, m_api->m_appr_mgr.a_appr_dg_sign_cert, _T(""));
// 		m_api->m_data.NET_SaveBlob(ciOut, m_api->m_appr_mgr.a_appr_dg_sign_cert, sFileName, code);

		ciIn = (CaplInstance*)map[i].in;
		ciOut = (CaplInstance*)map[i].out;
		if(m_FileData->IsKindOf(ciIn, m_fileApi->m_appr_mgr.e_apl_appr_pers_org))
		{
			m_FileData->GetAttr(ciIn, m_fileApi->m_appr_mgr.a_appr_dg_sign_cert, sFileName);
			if(sFileName.IsEmpty()) continue;
			
			sFileName = m_InPath+sFileName;
			m_api->m_data.PutAttr(ciOut, m_api->m_appr_mgr.a_appr_dg_sign_cert, _T(""));
			m_api->m_data.NET_SaveBlob(ciOut, m_api->m_appr_mgr.a_appr_dg_sign_cert, sFileName, code);
		}
		else if(m_FileData->IsKindOf(ciIn, m_fileApi->m_req_mgr.e_requirement))
		{
			CString html, sNewFileName;

			m_FileData->GetAttr(ciIn, m_fileApi->m_req_mgr.a_req_html, html);
			m_FileData->GetAttr(ciIn, m_fileApi->m_req_mgr.a_req_pictures, aePictures);

			for(int j=0; j<aePictures.Size; j++)
			{
				int nIndexOut = map.FindByIn((long)aePictures[j]);
				if(nIndexOut == -1) continue;

				CaplInstance *ciOutPicture = (CaplInstance*)map.Data[nIndexOut].out;

				m_FileData->GetAttr(aePictures[j], m_fileApi->m_doc_mgr.a_apl_stored_document_source, sFileName);
				m_api->m_data.PutAttr(ciOutPicture, m_api->m_doc_mgr.a_apl_stored_document_source, _T(""));

				m_api->m_data.NET_SaveBlob(ciOutPicture, m_api->m_doc_mgr.a_apl_stored_document_source, sFileName, code);								
				m_api->m_data.GetAttr(ciOutPicture, m_api->m_doc_mgr.a_apl_stored_document_source, sNewFileName);

				// замена в коде HTML : apl_blob_1 на новый_блоб (чтобы знать откуда брать картинку
				m_api->m_req_mgr.ReplaceReferenceInHTML(html, sFileName, sNewFileName);
			}

			m_api->m_data.PutAttr(ciOut, m_api->m_req_mgr.a_req_html, html);
		}
	}	

	ext_copy.Clear();
	prgs_dlg.SetText( APL_T("Сохранение данных ..."));
	m_data->NET_SaveChanges();

	m_api->SetAutoSave(AutoSave);

	prgs_dlg.ShowWindow(SW_HIDE);
	prgs_dlg.DestroyWindow();
	m_prgs_dlg=0;
	
	delete m_fileApi;
	m_fileApi=0;
	m_FileData=0;

	for(i=0; i<sFiles.GetSize(); i++)
		::DeleteFile(sFiles[i]);

	if(m_api->m_ModeInteractive)
		AfxMessageBox( APL_T("Импорт завершен !"));
	return true;
}

bool CaplExchangeManager::ExportChange(CaplInstance* inInst)
{
	int i;
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	
	m_array.Add(inInst);
	
	aplExtent items;
	aplExtent ext, effs, rels, pdfs, docs, revs, chars;
	CaplInstance* inst, *pdr, *pdf_ed, *pdf_ing;

	if(!m_api->m_data.IsKindOf(inInst, m_api->m_change_mgr.e_chng)) return false;
	m_api->m_change_mgr.LoadChangeInfo(inInst);

	m_api->m_data.GetAttr(inInst, m_api->m_change_mgr.a_chng_autor, inst);
	if(inst) m_array.Add(inst);
	
	m_api->m_data.GetAttr(inInst, m_api->m_change_mgr.a_chng_items, items);
	m_array.Append(items);
	m_api->m_change_mgr.LoadItemInfo(items);

	for(i= 0; i<items.GetSize(); i++)
	{
		if(m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_mat))
		{
			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_mat_der_unit, inst);
			LoadInstanceTree(inst, m_array, this);
		}

		if(m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_psc))
		{
			// правила применяемости - не экпортим, обрабатываются при провердении
//			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_psc_add_set, ext);
//			effs.Append(ext);
//			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_psc_cancel_set, ext);
//			effs.Append(ext);
//			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_psc_modif_set, ext);
//			effs.Append(ext);
			
			// на что заменили
			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_psc_changing_product, inst);
			if(inst && m_api->m_data.IsKindOf(inst, m_api->m_prd_mgr.e_apl_pdf))
				pdfs.Add(inst);

			// где поменяли
			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_psc_changed_product, inst);
			if(inst)
			{
				if(m_api->m_data.IsKindOf(inst, m_api->m_prd_mgr.e_apl_pdf))
					pdfs.Add(inst);
				else if(m_api->m_data.IsKindOf(inst, m_api->m_prd_mgr.e_pdr))
					rels.Add(inst);
			}

			// новая связь - не экпортим, создается при провердении
//			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_psc_created_pdr, inst);
//			if(inst && m_api->m_data.IsKindOf(inst, m_api->m_prd_mgr.e_pdr))
//				rels.Add(inst);
			
			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_psc_unit, inst);
			LoadInstanceTree(inst, m_array, this);
		}
		else if(m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_avc))
		{
			// экспортим документ и новую версию
			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_avc_doc, inst);
			if(inst)
				docs.Add(inst);

			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_avc_new_rev, inst);
			if(inst)
				revs.Add(inst);
		}
		else if(m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_char_change))
		{
			// экспортим характеристику и новую версию
			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_char_change_val, inst);
			if(inst)
				chars.Add(inst);

			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_char_change_new_rev, inst);
			if(inst)
				chars.Add(inst);
			
			m_api->m_data.GetAttr(items[i], m_api->m_change_mgr.a_char_change_old_rev, inst);
			if(inst)
				chars.Add(inst);
		}
		else if(m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_abpc))
		{
			
		}
	}
	
	// обрабатываем правила применяемости, читаем связи и изделия
	if(effs.GetSize())
	{
		CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
		for(i= 0; i<effs.GetSize(); i++)
			ld.AddQuery(0, effs[i], true);

		ld.AddQuery(_T('d'), 0, 0, m_api->m_prd_mgr.a_pde_usage, true, true);
		ld.LoadEx();
	}

	for(i= 0; i<effs.GetSize(); i++)
	{
		m_api->m_data.GetAttr(effs[i], m_api->m_prd_mgr.a_pde_usage, pdr);
		if(!pdr) continue;
		rels.Add(pdr);

		m_api->m_data.GetAttr(pdr, m_api->m_prd_mgr.a_pdr_r_ted, pdf_ed);
		if(!pdf_ed) continue;
		pdfs.Add(pdf_ed);

		m_api->m_data.GetAttr(pdr, m_api->m_prd_mgr.a_pdr_r_ting, pdf_ing);
		if(!pdf_ing) continue;
		pdfs.Add(pdf_ing);
	}

	// зачитка атрибутов для всех разом
	ext.Append(pdfs);
	ext.Append(docs);
	ext.Append(revs);
	ext.Append(chars);
	m_api->LoadExtentInfo(ext);
	
	// экспортируем изделия у версий (без состава)
	for(i= 0; i<pdfs.GetSize(); i++)
	{
		m_api->m_data.GetAttr(pdfs[i], m_api->m_prd_mgr.a_pdf_prd, inst);
		if(inst) m_array.Add(inst);
	}
	
	// экспортируем только новую версию
	for(i= 0; i<revs.GetSize(); i++)
		ExportDocument(revs[i],m_OutPath);

	// экспортируем значение, которое меняем, новую версию и item
	for(i=0 ;i<chars.GetSize(); i++)
	{		
		if(!m_api->m_data.IsKindOf(chars[i], m_api->m_charact_mgr.e_apl_charact_value))
		{
//			LoadInstanceTree(inst, m_array, this);
			continue;
		}
		
		m_api->m_data.GetAttr(chars[i], m_api->m_charact_mgr.a_apl_charact_val_charact, inst);
		if(inst)
			LoadInstanceTree(inst, m_array, this);

		m_api->m_data.GetAttr(chars[i], m_api->m_charact_mgr.a_apl_charact_val_item, inst);
		if(inst) 
			ExportInstance(inst, _T(""), true);
	}

	m_array.Append(effs);
	m_array.Append(rels);
	m_array.Append(pdfs);
	m_array.Append(docs);
	m_array.Append(chars);

	ExportDocument(inInst,m_OutPath);
	ExportItemApproval(inInst);
	
	return true;
}

void CaplExchangeManager::ImportChanges(CaplMap& map, aplExtent& ext_copy)
{
	CaplAttrValue find_val[5];
	aplExtent changes, ext, items, pdfs, prds, rels, chars_items, chars, old_rev, new_rev;
	aplExtent docs, new_doc_revs;
	CaplInstance* inst, *inst0, *inst1, *pdf, *prd, *pdf_ed, *pdf_ing;
	CaplInstance* item, *type, *charact;
	CString sId;
	int iCharNum;
	int i, j;

	m_fileApi->m_data.GetEntityExtent(m_fileApi->m_change_mgr.e_chng, changes);

	// сначала разбираем, что надо импортнуть
	if(m_prgs_dlg){m_prgs_dlg->SetText( APL_T("Поиск изменений"));m_prgs_dlg->SetRange(changes.Size);}
	for(i= 0; i<changes.GetSize(); i++)
	{
		m_fileApi->m_data.GetAttr(changes[i], m_fileApi->m_change_mgr.a_chng_id, sId);
		if(sId.IsEmpty()) continue;

		find_val[0].attr= m_api->m_change_mgr.a_chng_id;
		find_val[0].value.Set(sId);
		
		m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_change_mgr.e_chng, 1, &find_val[0], ext, false);
		if(ext.GetSize()) continue; // уже такое есть

		m_fileApi->m_data.GetAttr(changes[i], m_fileApi->m_change_mgr.a_chng_items, items);
		
		ext_copy.Append(items);

		for(j= 0; j<items.GetSize(); j++)
		{
			if(m_fileApi->m_data.IsKindOf(items[j], m_fileApi->m_change_mgr.e_mat))
			{
				
			}

			if(m_fileApi->m_data.IsKindOf(items[j], m_fileApi->m_change_mgr.e_psc))
			{
				m_fileApi->m_data.GetAttr(items[j], m_fileApi->m_change_mgr.a_psc_changing_product, pdf);
				if(pdf && m_fileApi->m_data.IsKindOf(pdf, m_fileApi->m_prd_mgr.e_apl_pdf))
				{
					m_fileApi->m_data.GetAttr(pdf, m_fileApi->m_prd_mgr.a_pdf_prd, prd);
					
					pdfs.Add(pdf);
					prds.Add(prd);
				}	

				m_fileApi->m_data.GetAttr(items[j], m_fileApi->m_change_mgr.a_psc_changed_product, inst);
				if(inst)
				{
					if(m_fileApi->m_data.IsKindOf(inst, m_fileApi->m_prd_mgr.e_pdr))
					{
						rels.Add(inst);
						
						m_fileApi->m_data.GetAttr(inst, m_fileApi->m_prd_mgr.a_pdr_r_ted, pdf_ed);
						m_fileApi->m_data.GetAttr(pdf_ed, m_fileApi->m_prd_mgr.a_pdf_prd, prd);						
						pdfs.Add(pdf_ed);
						prds.Add(prd);

						m_fileApi->m_data.GetAttr(inst, m_fileApi->m_prd_mgr.a_pdr_r_ting, pdf_ing);
						m_fileApi->m_data.GetAttr(pdf_ing, m_fileApi->m_prd_mgr.a_pdf_prd, prd);
						pdfs.Add(pdf_ing);
						prds.Add(prd);						
					}
					else if(m_fileApi->m_data.IsKindOf(inst, m_fileApi->m_prd_mgr.e_apl_pdf))
					{
						m_fileApi->m_data.GetAttr(inst, m_fileApi->m_prd_mgr.a_pdf_prd, prd);
						pdfs.Add(inst);
						prds.Add(prd);
					}
				}
			}
			else if(m_fileApi->m_data.IsKindOf(items[j], m_fileApi->m_change_mgr.e_avc))
			{
				m_fileApi->m_data.GetAttr(items[j], m_fileApi->m_change_mgr.a_avc_doc, inst);
				if(inst)
					docs.Add(inst);
				m_fileApi->m_data.GetAttr(items[i], m_fileApi->m_change_mgr.a_avc_new_rev, inst);
				if(inst)
					new_doc_revs.Add(inst);
			}
			else if(m_fileApi->m_data.IsKindOf(items[j], m_fileApi->m_change_mgr.e_char_change))
			{
				chars_items.Add(items[j]);
				m_fileApi->m_data.GetAttr(items[j], m_fileApi->m_change_mgr.a_char_change_val, inst);
				if(inst)
					chars.Add(inst);
				m_fileApi->m_data.GetAttr(items[j], m_fileApi->m_change_mgr.a_char_change_new_rev, inst);
				if(inst)
					new_rev.Add(inst);
				m_fileApi->m_data.GetAttr(items[j], m_fileApi->m_change_mgr.a_char_change_old_rev, inst);
				if(inst)
					old_rev.Add(inst);
			}
			else if(m_fileApi->m_data.IsKindOf(items[j], m_fileApi->m_change_mgr.e_abpc))
			{
				
			}
		}
	}

	ext_copy.Append(changes);
	
	/*создаем изделия*/
	if(m_prgs_dlg){m_prgs_dlg->SetText( APL_T("Поиск изменений изделий"));m_prgs_dlg->SetRange(prds.Size);}
	for(i= 0; i<prds.GetSize(); i++)
	{
		prd= (CaplInstance*)map.QGetPointerByIn((long)prd);

		if(!prd)
		{
			m_fileApi->m_data.GetAttr(prds[i], m_fileApi->m_prd_mgr.a_prd_id, sId);

			/*ищем изделие*/
			find_val[0].attr= m_api->m_prd_mgr.a_prd_id;
			find_val[0].value.Set(sId);
			
			m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_prd_mgr.e_prd, 1, &find_val[0], ext, false);

			if(ext.GetSize()) map.Add((long)prds[i], (long)ext[0]);
			ext_copy.Add(prds[i]);
		}
	}
	
	/*создаем версии изделия*/
	if(m_prgs_dlg){m_prgs_dlg->SetText( APL_T("Поиск изменений версий изделий"));m_prgs_dlg->SetRange(pdfs.Size);}
	for(i= 0; i<pdfs.GetSize(); i++)
	{
		pdf= (CaplInstance*)map.QGetPointerByIn((long)pdfs[i]);
		if(pdf) continue;

		m_fileApi->m_data.GetAttr(pdfs[i] ,m_fileApi->m_prd_mgr.a_pdf_id, sId);
		m_fileApi->m_data.GetAttr(pdfs[i], m_fileApi->m_prd_mgr.a_pdf_prd, inst);
		
		prd= (CaplInstance*)map.QGetPointerByIn((long)inst);

		if(prd)
		{
			find_val[0].value.Set((LPCTSTR)sId);
			find_val[0].attr=m_api->m_prd_mgr.a_pdf_id;
			find_val[1].value.Set(prd);
			find_val[1].attr=m_api->m_prd_mgr.a_pdf_prd;
		
			m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_prd_mgr.e_pdf, 2 ,&find_val[0], ext, false);
			if(ext.GetSize()) map.Add((long)pdfs[i], (long)ext[0]);
		}
		
		ext_copy.Add(pdfs[i]);			
	}

	/*создаем связи*/
	if(m_prgs_dlg){m_prgs_dlg->SetText( APL_T("Поиск изменений связей"));m_prgs_dlg->SetRange(rels.Size);}
	for(i= 0; i<rels.GetSize(); i++)
	{
		inst= (CaplInstance*)map.QGetPointerByIn((long)rels[i]);
		if(inst) continue; // случилось страшное и импортнулся состав???

		m_fileApi->m_data.GetAttr(rels[i], m_fileApi->m_prd_mgr.a_pdr_id, sId);
		m_fileApi->m_data.GetAttr(rels[i], m_fileApi->m_prd_mgr.a_pdr_r_ted, inst0);
		m_fileApi->m_data.GetAttr(rels[i], m_fileApi->m_prd_mgr.a_pdr_r_ting, inst1);	
		
		pdf_ed= (CaplInstance*)map.QGetPointerByIn((long)inst0);
		pdf_ing= (CaplInstance*)map.QGetPointerByIn((long)inst1);

		if(pdf_ed && pdf_ing)
		{
			find_val[0].attr= m_api->m_prd_mgr.a_pdr_r_ted;
			find_val[0].value.Set(pdf_ed);
			find_val[1].attr= m_api->m_prd_mgr.a_pdr_r_ting;
			find_val[1].value.Set(pdf_ing);
			find_val[2].attr= m_api->m_prd_mgr.a_pdr_id;
			find_val[2].value.Set(sId);

			m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_prd_mgr.e_pdr, 3 ,&find_val[0], ext, false);
			if(ext.GetSize()) map.Add((long)rels[i], (long)ext[0]);
		}

		ext_copy.Add(rels[i]);
	}

	/*создаем документы*/
	if(m_prgs_dlg){m_prgs_dlg->SetText( APL_T("Поиск изменений документов"));m_prgs_dlg->SetRange(rels.Size);}
	for(i= 0; i<docs.GetSize(); i++)
	{
		m_fileApi->m_data.GetAttr(docs[i], m_fileApi->m_doc_mgr.a_doc_id, sId);
		m_fileApi->m_data.GetAttr(docs[i], m_fileApi->m_doc_mgr.a_doc_kind, inst);
		type= (CaplInstance*) map.QGetPointerByIn((long)inst);

		find_val[0].attr= m_api->m_doc_mgr.a_doc_id;
		find_val[0].value.Set(sId);
		find_val[1].attr= m_api->m_doc_mgr.a_doc_kind;
		find_val[1].value.Set(type);

		m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_doc_mgr.e_doc, 1, &find_val[0], ext, false);
		if(ext.GetSize()) map.Add((long)docs[i], (long)ext[0]);
	}

	/*создаем характеристики*/
	if(m_prgs_dlg){m_prgs_dlg->SetText( APL_T("Поиск изменений характеристик"));m_prgs_dlg->SetRange(rels.Size);}
	for(i= 0; i<chars.GetSize(); i++)
	{
		m_fileApi->m_data.GetAttr(chars[i], m_fileApi->m_charact_mgr.a_apl_charact_val_item, inst);
		item= (CaplInstance*) map.QGetPointerByIn((long)inst); 

		m_fileApi->m_data.GetAttr(chars[i], m_fileApi->m_charact_mgr.a_apl_charact_val_charact, inst);
		charact= (CaplInstance*) map.QGetPointerByIn((long)inst);

		m_fileApi->m_data.GetAttr(chars[i], m_fileApi->m_charact_mgr.a_apl_charact_val_type, inst);
		type= (CaplInstance*) map.QGetPointerByIn((long)inst);

		m_fileApi->m_data.GetAttr(chars[i], m_fileApi->m_charact_mgr.a_apl_charact_val_num, iCharNum);
		
		if(item!=NULL && charact!=NULL)
		{
			find_val[0].value.Set(item);
			find_val[0].attr=m_api->m_charact_mgr.a_apl_charact_val_item;
			find_val[1].value.Set(type);
			find_val[1].attr=m_api->m_charact_mgr.a_apl_charact_val_type;
			find_val[2].value.Set(charact);
			find_val[2].attr=m_api->m_charact_mgr.a_apl_charact_val_charact;			
			find_val[3].value.Set(iCharNum);
			find_val[3].attr=m_api->m_charact_mgr.a_apl_charact_val_num;			
			
			m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_apl_charact_value, 4 ,&find_val[0], ext, false);
			if(ext.GetSize()) map.Add((long)chars[i], (long)ext[0]);
			else
			{
				/*Затаскивать изменения чего-то несуществующего как-то криво*/
				/*делаем эмитацию, что была такая характеристика, и активная версия у нее была	старая...*/
				m_fileApi->m_data.PutAttr(chars[i], m_fileApi->m_charact_mgr.a_apl_charact_val_act_ver, old_rev[i]);
				ext_copy.Add(chars[i]);
				ext_copy.Add(old_rev[i]);
			}
		}
		else
		{
			/*вот здесь вообще не понятно что делать... разбирать всю базу?
			поэтому делаем херню*/
			if(!item)
			{
				m_fileApi->m_data.GetAttr(chars[i], m_fileApi->m_charact_mgr.a_apl_charact_val_type, inst);
				if(inst)ext_copy.Add(inst);
			}
			if(!charact)/*или лучше вызвать ImportDictionary*/
			{
				m_fileApi->m_data.GetAttr(chars[i], m_fileApi->m_charact_mgr.a_apl_charact_val_charact, inst);				
				if(inst)ext_copy.Add(inst);
			}
		}

		ext_copy.Add(new_rev[i]);
	}

	if(m_prgs_dlg){m_prgs_dlg->SetText( APL_T("Копирование объектов..."));m_prgs_dlg->SetRange(0);m_prgs_dlg->SetPos(0);}
	CopyData(ext_copy, map, m_data);
	ext_copy.Clear();
	
	bool ModeInteractiv= m_api->m_ModeInteractive;
	bool AutoSave= m_api->m_AutoSave;
	m_api->SetModeInteractive(false);
	m_api->SetAutoSave(false);

	/*правим атрибуты изменений, чтобы провести заново*/
	for(i= 0; i<changes.GetSize(); i++)
	{
		inst= (CaplInstance*)map.QGetPointerByIn((long)changes[i]);
		if(!inst) continue;

		m_api->m_data.PutAttr(inst, m_api->m_change_mgr.a_chng_state, _T("not_applied"));
		m_api->m_data.PutAttr(inst, m_api->m_change_mgr.a_chng_apply_date, _T(""));

		m_api->m_data.GetAttr(changes[i], m_api->m_change_mgr.a_chng_items, items);
		
		for(int j= 0; j<items.GetSize(); j++)
			m_api->m_data.PutAttr(items[j], m_api->m_change_mgr.a_chng_item_accept_date, _T(""));

//		m_api->m_change_mgr.ApplyChange(inst);
	}

	m_api->SetModeInteractive(ModeInteractiv);
	m_api->SetAutoSave(AutoSave);

	if(m_AutoSave)
	{
		if(m_prgs_dlg){m_prgs_dlg->SetText( APL_T("Сохранение объектов..."));m_prgs_dlg->SetRange(0);m_prgs_dlg->SetPos(0);}
		m_api->SaveChanges();
	}
}

bool CaplExchangeManager::ExportNotes(CaplInstance *inInst)
{
	// к примечаниям нельзя прицепить объект, и все дерево примечаний связано с одним объектом.
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	aplExtent notes;
	m_api->m_appr_mgr.FindAssociatedNotes(inInst, notes);
	m_array.Add(inInst);
	for(int i=0; i<notes.Size;i++)
	{
		if(notes[i]==0) continue;
		if(notes[i]->GetType()==0) continue;
		if(notes[i]->GetAccessmode()>aplRO) continue;
		m_array.Add(notes[i]);
	}

	return true;
}

bool CaplExchangeManager::ExportRoles(CaplInstance *inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	LoadInstanceTree(inInst,m_array, this);
	return true;
}


bool CaplExchangeManager::ExportOptions(CaplInstance *inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	LoadInstanceTree(inInst,m_array, this);
	return true;
}

bool CaplExchangeManager::ExportLogbookAccess(CaplInstance *inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	LoadInstanceTree(inInst,m_array, this);
	return true;
}

bool CaplExchangeManager::ExportRequirement(CaplInstance *inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;

	int i, j;
	CString sSql;
	aplExtent aeRels;
	aplExtent aeDocs;
	aplExtent aeItems;
	aplExtent aePictures;

	// получаем все дочерние рекурсивно
	m_api->m_req_mgr.LoadChildsFromBase(inInst, aeItems, true);

	// загружаем атрибуты
	aeItems.Add(inInst);
	m_api->m_req_mgr.LoadReqInfo(aeItems);

	// сохраняем картинки
	for(i=0; i<aeItems.Size; i++)
	{
		m_api->m_data.GetAttr(aeItems[i], m_api->m_req_mgr.a_req_pictures, aePictures);
		for(j=0; j<aePictures.Size; j++) ExportDocument(aePictures[j]);
		m_array.Append(aePictures);
	}

	// сохраняем документы, связанные с требованием
	if(m_ExportAssDocuments)
	{
		m_api->m_doc_mgr.FindAssociatedDocuments(aeItems, aeDocs, aeRels);
		for(j=0; j<aeDocs.Size; j++) ExportDocument(aeDocs[j]);

		m_array.Append(aeRels);
		m_array.Append(aeDocs);
	}

	// требования
	m_array.Add(inInst);
	m_array.Append(aeItems);
	return true;
}

bool CaplExchangeManager::ExportMessages(CaplInstance *inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	LoadInstanceTree(inInst,m_array, this);

	//экспорт связанных объектов
	aplExtent ext_items;
	m_api->m_data.GetAttr(inInst,m_api->m_message_mgr.a_message_items,ext_items);
	if(ext_items.GetSize()) m_api->LoadExtentInfo(ext_items);
	for(int i=0;i<ext_items.GetSize();i++)
	{
		if(m_api->m_data.IsKindOf(ext_items[i],m_api->m_doc_mgr.e_doc)) ExportDocument(ext_items[i],m_OutPath);
		else ExportInstance(ext_items[i],_T(""),true);
	}
	return true;
}

bool CaplExchangeManager::ExportPrdInstRelations(CaplInstance *inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	LoadInstanceTree(inInst,m_array, this);
	return true;
}

bool CaplExchangeManager::ExportCharacteristicType(CaplInstance *inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	LoadInstanceTree(inInst,m_array, this);
	return true;
}

bool CaplExchangeManager::ExportDocumentType(CaplInstance *inInst)
{
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	LoadInstanceTree(inInst,m_array, this);
	return true;
}


bool CaplExchangeManager::ExportOrg(CaplInstance *inInst)
{
	int i;
	if(inInst==0) return false;
	if(inInst->GetType()==0) return false;
	if(inInst->GetAccessmode()>aplRO) return false;
	INC_EXP_POS;
	if(m_data->IsKindOf(inInst, m_api->m_appr_mgr.e_official))
	{
		LoadInstanceTree(inInst,m_array, this);
	}
	else if(m_data->IsKindOf(inInst, m_api->m_appr_mgr.e_org))
	{
		aplExtent ext, rel;
		m_api->m_appr_mgr.GetAllSubOrganization(inInst, ext, &rel);
		for(i=0; i<ext.Size;i++)
		{
			if(ext[i]!=0)
				m_array.Add(ext[i]);
		}
		for(i=0; i<rel.Size;i++)
		{
			if(rel[i]!=0)
				m_array.Add(rel[i]);
		}
		m_api->m_appr_mgr.GetAllSubPerson(inInst, ext, rel);
		for(i=0; i<ext.Size;i++)
		{
			if(ext[i]!=0)
				m_array.Add(ext[i]);
		}
		for(i=0; i<rel.Size;i++)
		{
			if(rel[i]!=0)
				m_array.Add(rel[i]);
		}
		LoadInstanceTree(inInst,m_array, this);
	}
	else if(m_data->IsKindOf(inInst, m_api->m_appr_mgr.e_person))
	{
		LoadInstanceTree(inInst,m_array, this);
	}
	else if(m_data->IsKindOf(inInst, m_api->m_appr_mgr.e_apl_user))
	{	
		LoadInstanceTree(inInst,m_array, this);
	}
	else{ DEC_EXP_POS;return false;}

	if(m_ExportProductCharacteristics) ExportCharacteristic(inInst);

	DEC_EXP_POS;
	return true;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
void CaplExchangeManager::ImportCharacteristics(CaplMap &map,aplExtent &ext_copy,  int &prgs_count)
{
	CaplAttrValue tst_values[5];
	//CString id,name,ver,buf;

	aplExtent ext, ext_rel, ext1, act_vers;
	CaplInstance *inst0,*inst1;

	int i;
	aplExtent group_ext;
	m_FileData->GetEntityExtent(m_fileApi->m_charact_mgr.e_charact_val_group,group_ext);
	for(i=0; i<group_ext.Size;i++)
	{
		CaplInstance *item,*def;
		m_FileData->GetAttr(group_ext[i],m_fileApi->m_charact_mgr.a_charact_val_group_item,item);
		item = (CaplInstance*)map.QGetPointerByIn((long)item); 
		
		m_FileData->GetAttr(group_ext[i],m_fileApi->m_charact_mgr.a_charact_val_group_def,def);
		def = (CaplInstance*)map.QGetPointerByIn((long)def); 

		if(!item || !def) continue;

		if((item->GetId()!=0) && (def->GetId()!=0))
		{
			tst_values[0].value.Set(item);
			tst_values[0].attr = m_api->m_charact_mgr.a_charact_val_group_item;
			tst_values[1].value.Set(item);
			tst_values[1].attr = m_api->m_charact_mgr.a_charact_val_group_def;

			aplExtent ext;
			m_data->NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_charact_val_group,2,&tst_values[0],ext,false);
			if(ext.Size>0)
			{
				map.Add((long)group_ext[i],(long)ext[0]);
			}
			else ext_copy.Add(group_ext[i]);
		}else ext_copy.Add(group_ext[i]);
	}

	// Загрузка значений характеристик
	aplExtent ext_characr_val;
	m_FileData->GetEntityExtent(m_fileApi->m_charact_mgr.e_apl_charact_value, ext_characr_val);
	if(m_prgs_dlg)m_prgs_dlg->SetText( APL_T("Импорт значений характеристик"));
	if(m_prgs_dlg)m_prgs_dlg->SetRange(ext_characr_val.Size);
	bool res_copy=false;

	for(i=0; i<ext_characr_val.Size; i++)
	{
		INC_PRGS_POS_P(i,5);

		inst1= (CaplInstance*)map.QGetPointerByIn((long)ext_characr_val[i]);
		if(inst1!=0) continue;

		m_FileData->GetAttr(ext_characr_val[i],m_fileApi->m_charact_mgr.a_apl_charact_val_item,inst0);
		inst1=(CaplInstance*)map.QGetPointerByIn((long)inst0);
		
		CaplInstance *ver_char_val_in_file;
		m_FileData->GetAttr(ext_characr_val[i],m_fileApi->m_charact_mgr.a_apl_charact_val_act_ver,ver_char_val_in_file);
				
		bool bCreateNew=true;
		if(inst1!=0)
		{
			CaplInstance *inst_charact;
			m_FileData->GetAttr(ext_characr_val[i],m_fileApi->m_charact_mgr.a_apl_charact_val_charact,inst_charact);
			inst_charact=(CaplInstance*)map.QGetPointerByIn((long)inst_charact); 

			if(inst_charact!=0)
			{
				if(inst1->GetId()!=0 && inst_charact->GetId()!=0)
				{
					CaplInstance *inst_type;
					m_FileData->GetAttr(ext_characr_val[i],m_fileApi->m_charact_mgr.a_apl_charact_val_type,inst_type);
					inst_type=(CaplInstance*)map.QGetPointerByIn((long)inst_type); 

					tst_values[0].value.Set(inst1);
					tst_values[0].attr=m_api->m_charact_mgr.a_apl_charact_val_item;

					tst_values[1].value.Set(inst_type);
					tst_values[1].attr=m_api->m_charact_mgr.a_apl_charact_val_type;

					tst_values[2].value.Set(inst_charact);
					tst_values[2].attr=m_api->m_charact_mgr.a_apl_charact_val_charact;
				
					int inst_num;
					m_FileData->GetAttr(ext_characr_val[i],m_fileApi->m_charact_mgr.a_apl_charact_val_num,inst_num);
					
					tst_values[3].value.Set(inst_num);
					tst_values[3].attr=m_api->m_charact_mgr.a_apl_charact_val_num;

					int num= 4;
			
					m_data->NET_FindInstancesWithAttrValues(m_api->m_charact_mgr.e_apl_charact_value,num,&tst_values[0],ext,false);

					if(ext.Size>0)
					{
						// Такая хар-ка уже есть
						bCreateNew = false;	

						/*
						m_api->m_charact_mgr.LoadCharacteristic(ext);

						!!! По идее здесь должно быть сравнение в зависимости от типа значения
						b если все равно, то в массив копируемых не добавляем
						
						Т.к. сравнивать - геморойно будем всегда создавать новую версию
						*/

						map.Add((long)ext_characr_val[i],(long)ext[0]);
					}
				}
			}
		}
		ext_copy.Add(ext_characr_val[i]);
		ext_copy.Add(ver_char_val_in_file);
	}

	//res_copy = CopyData(ext_copy,map,m_data);
	/* Должно взяться при копировании данных
	for(int isa=0; isa<set_active.GetSize();isa++)
	{
		CaplInstance *inst = (CaplInstance*)map.GetByIn((long)set_active.GetAt(isa));
		if((long)inst<=0) continue;
		if(m_data->IsKindOf(inst,m_api->m_charact_mgr.e_apl_charact_value_ver))
			m_api->m_charact_mgr.MakeCharValVersionActive(inst);
	}*/
}

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
void CaplExchangeManager::ImportPI(CaplMap &map,aplExtent &ext_copy,  int &prgs_count)
{
	CaplAttrValue tst_values[5];
	CString id,name,ver,buf;

	aplExtent ext, ext_bp, ext_bp_ref, extPrd, extPdf, extPd, extPdr, ext_rel, ext1, act_vers;

	m_FileData->GetEntityExtent(m_fileApi->m_bp_mgr.e_apl_bp_inst, ext_bp);
	
	if(m_prgs_dlg) m_prgs_dlg->SetText( APL_T("Поиск экземпляров бизнес-процессов"));
	if(m_prgs_dlg) m_prgs_dlg->SetRange(ext_bp.Size);
	
	int i, j;
	for(i=0;i<ext_bp.Size;i++)
	{
		m_FileData->GetAttr(ext_bp[i],m_fileApi->m_bp_mgr.a_bp_inst_id,id);

		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_bp_mgr.a_bp_inst_id;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_bp_mgr.e_apl_bp_inst,1,&tst_values[0],ext,false);

		if(ext.Size>0)
			map.Add((long)ext_bp[i],(long)ext[0]);
		else
		{
			//Импорт изменений ресурсов (ИЛП)
			aplExtent rc;
			CaplInstance *basis;
			m_FileData->GetEntityExtentBN(_T("apl_resource_changes"), rc);
			ext.Clear();
			for(j=0; j<rc.Size; j++)
			{
				m_FileData->GetAttrBN(rc[j], _T("basis"), basis);
				if(basis==ext_bp[i])
					ext_copy.Add(rc[j]);
			}
		}
		
		INC_PRGS_POS_P(i,5);
		ext_copy.Add(ext_bp[i]);
	}
	
	m_FileData->GetEntityExtent(m_fileApi->m_bp_mgr.e_bp_inst_ref, ext_bp_ref);
	
	if(m_prgs_dlg) m_prgs_dlg->SetText( APL_T("Поиск экземпляров бизнес-процессов"));
	if(m_prgs_dlg) m_prgs_dlg->SetRange(ext_bp_ref.Size);
	
	for(i=0;i<ext_bp_ref.Size;i++)
	{
		INC_PRGS_POS_P(i,5);
		CaplInstance *prc,*itm,*prc0,*itm0;
		CaplInstance *ref=ext_bp_ref[i];
		m_FileData->GetAttr(ref,m_fileApi->m_bp_mgr.a_bp_inst_ref_process, prc);
		m_FileData->GetAttr(ref,m_fileApi->m_bp_mgr.a_bp_inst_ref_item, itm);
		prc0=(CaplInstance*)map.QGetPointerByIn((long) prc);
		itm0=(CaplInstance*)map.QGetPointerByIn((long) itm);
		if(itm0!=0 && prc0!=0)
		{
			tst_values[0].value.Set(prc0);
			tst_values[0].attr=m_api->m_bp_mgr.a_bp_inst_ref_process;
			tst_values[1].value.Set(itm0);
			tst_values[1].attr=m_api->m_bp_mgr.a_bp_inst_ref_item;
			m_data->NET_FindInstancesWithAttrValues(m_api->m_bp_mgr.e_bp_inst_ref,2,&tst_values[0],ext,false);

			if(ext.Size>0) map.Add((long)ref,(long)ext[0]);	
		}
		ext_copy.Append(ext_bp_ref);
	}
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
void CaplExchangeManager::ImportBP(CaplMap &map,aplExtent &ext_copy,  int &prgs_count)
{
	CaplAttrValue tst_values[5];
	CString id,name,ver,buf;

	aplExtent ext, extPrd, ext_bp, extPdf, extPd, extPdr, ext_rel, ext1, act_vers;
	aplExtent set_active;//Для установки активной версии

	m_FileData->GetEntityExtent(m_fileApi->m_bp_mgr.e_bp, ext_bp);

	if(m_prgs_dlg) m_prgs_dlg->SetText( APL_T("Поиск бизнес-процессов"));
	if(m_prgs_dlg) m_prgs_dlg->SetRange(ext_bp.Size);
	
	int i;

	for(i=0;i<ext_bp.Size;i++)
	{
		INC_PRGS_POS_P(i,5);
		CString guid;
		m_FileData->GetAttr(ext_bp[i],m_fileApi->m_bp_mgr.a_bp_guid,guid);
		m_FileData->GetAttr(ext_bp[i],m_fileApi->m_bp_mgr.a_bp_id,id);

		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_bp_mgr.a_bp_id;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_bp_mgr.e_bp,1,&tst_values[0],ext,false);
		if(ext.Size>0)
		{
			map.Add((long)ext_bp[i],(long)ext[0]);
			aplExtent vers;
			m_fileApi->m_bp_mgr.GetAllBPVersion(ext_bp[i],vers);
			CString tg=_T("");
			bool find = false;
			// !!! Непонятно, та ли StepData используется ?
			// !!! В предыдущей GetAllBPVersion ранее использовалась не та.
			for(int v=0; v<vers.Size;v++)
			{
				m_data->GetAttr(vers[v],m_api->m_bp_mgr.a_bp_guid,tg);
				if(tg==guid) {find=true;break;}
			}
			if(!find)
			{
				aplExtent ext_char,ext_group;
				m_fileApi->m_charact_mgr.FindAssociatedCharacteristic(ext_bp[i],ext_char,ext_group,true);
				CaplInstance* ver = m_fileApi->m_bp_mgr.CreateBPVersion(ext_bp[i]);
				ext_copy.Add(ver);
				set_active.Add(ver);
			}
		}
		ext_copy.Add(ext_bp[i]);
	}
	// обновление свзей
	aplExtent ext_bp_ref;
	m_FileData->GetEntityExtent(m_fileApi->m_bp_mgr.e_bp_ref, ext_bp_ref);
	
	if(m_prgs_dlg) m_prgs_dlg->SetText( APL_T("Поиск бизнес-процессов"));
	if(m_prgs_dlg) m_prgs_dlg->SetRange(ext_bp_ref.Size);
	
	for(i=0;i<ext_bp_ref.Size;i++)
	{
		INC_PRGS_POS_P(i,5);
		CaplInstance *prc,*itm,*prc0,*itm0;
		CaplInstance *ref=ext_bp_ref[i];
		m_FileData->GetAttr(ref,m_fileApi->m_bp_mgr.a_bp_ref_process,prc);
		m_FileData->GetAttr(ref,m_fileApi->m_bp_mgr.a_bp_ref_item,itm);
		prc0=(CaplInstance*)map.QGetByIn((long) prc);
		if((long)prc0==-1) prc0=0;
		itm0=(CaplInstance*)map.QGetByIn((long) itm);
		if((long)itm0==-1) itm0=0;
		if(itm0!=0 && prc0!=0)
		{
			tst_values[0].value.Set(prc0);
			tst_values[0].attr=m_api->m_bp_mgr.a_bp_ref_process;
			tst_values[1].value.Set(itm0);
			tst_values[1].attr=m_api->m_bp_mgr.a_bp_ref_item;
			m_data->NET_FindInstancesWithAttrValues(m_api->m_bp_mgr.e_bp_ref,2,&tst_values[0],ext,false);

			if(ext.Size>0) map.Add((long)ref,(long)ext[0]);	
		}
		ext_copy.Add(ref);
	}
	
	if(m_ImportBPRes)
	{
		CaplInstance *bp,*exist_bp;
		aplExtent ext_bp_res;
		m_FileData->GetEntityExtent(m_fileApi->m_bp_mgr.e_bp_res, ext_bp_res);
		m_prgs_dlg->SetText( APL_T("Поиск ресурсов бизнес-процессов"));
		m_prgs_dlg->SetRange(ext_bp_res.Size);
		for(i=0;i<ext_bp_res.Size;i++)
		{
			INC_PRGS_POS_P(i,5);
			m_FileData->GetAttr(ext_bp_res[i],m_fileApi->m_bp_mgr.a_bp_res_id,id);
			m_FileData->GetAttr(ext_bp_res[i],m_fileApi->m_bp_mgr.a_bp_res_process,bp);

			exist_bp=(CaplInstance*)map.QGetPointerByIn((long) bp);
			if(exist_bp!=0) 
			{
				tst_values[0].value.Set((LPCTSTR)id);
				tst_values[0].attr=m_api->m_bp_mgr.a_bp_res_id;
				tst_values[1].value.Set(exist_bp);
				tst_values[1].attr=m_api->m_bp_mgr.a_bp_res_process;
				m_data->NET_FindInstancesWithAttrValues(m_api->m_bp_mgr.e_bp_res,2,&tst_values[0],ext,false);

				if(ext.Size>0) map.Add((long)ext_bp_res[i],(long)ext[0]);
			}
			ext_copy.Add(ext_bp_res[i]);
		}
	}
}

void CaplExchangeManager::ImportProject(CaplMap& map ,aplExtent& ext_copy)
{
	aplExtent ext_main,ext;
	int i,j;
	CString id;
	CString buf;
	CaplAttrValue tst_values [5];


	m_FileData->GetEntityExtent(m_fileApi->m_project_mgr->e_project,ext_main);
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_project_mgr->a_project_id,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_project_mgr->a_project_id;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_project_mgr->e_project,1,&tst_values[0],ext,false);
		if(ext.Size>0)
		{
			map.Add((long)ext_main[i],(long)ext[0]);
			aplExtent vers;
			// здесь надо создавать новую версию. Что-то я не понял как
			// m_fileApi->m_project_mgr->Create (ext_bp[i],vers);
		}
		ext_copy.Add(ext_main[i]);
		
		aplExtent ext1;
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_project_mgr->a_project_transactions,ext1);
		for(j=0;j<ext1.GetSize();j++)
		{
			ext_copy.Add(ext1[j]);
		}
		CaplInstance *tmp_inst;
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_project_mgr->a_project_labor_of_item,tmp_inst);
		ext_copy.Add(tmp_inst);
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_project_mgr->a_project_labor_useness,tmp_inst);
		ext_copy.Add(tmp_inst);
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_project_mgr->a_project_labor_useness_actual,tmp_inst);
		ext_copy.Add(tmp_inst);

//		aplExtent ext_char,ext_group;
//		m_fileApi->m_charact_mgr.FindAssociatedCharacteristic(ext_main[i],ext_char,ext_group,true);
	}

	// Импортируем связи
	aplExtent ext_rel;
	m_FileData->GetEntityExtent(m_fileApi->m_project_mgr->e_project_seg,ext_rel);
	ext_copy.Append(ext_rel);
}

void CaplExchangeManager::ImportCategory(CaplMap& map ,aplExtent& ext_copy)
{
	aplExtent ext_main,ext;
	int i;
	CString id;
	CString buf;
	CaplAttrValue tst_values [5];
	//////////////////////импорт APL_CATEGORY///////////////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_categ_mgr.e_categ, ext_main);
	for (i=0;i<ext_main.Size;i++)
	{
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_categ_mgr.a_categ_id,id);
		tst_values[0].value.Set((LPCTSTR)id);
		tst_values[0].attr=m_api->m_categ_mgr.a_categ_id;
		m_data->NET_FindInstancesWithAttrValues(m_api->m_categ_mgr.e_categ,1,&tst_values[0],ext,false);
		
		//типа, версия прийти не может... 46 ЦНИИ
		aplExtent ext1;
		CaplInstance* main_act_ver= m_FileData->CreateInstance(m_fileApi->m_categ_mgr.e_apl_product_category_ver);
		m_FileData->GetAttr(ext_main[i], m_fileApi->m_categ_mgr.a_categ_id, buf);
		m_FileData->PutAttr(main_act_ver, m_fileApi->m_categ_mgr.a_categ_ver_id, buf);
		m_FileData->GetAttr(ext_main[i], m_fileApi->m_categ_mgr.a_categ_name, buf);
		m_FileData->PutAttr(main_act_ver, m_fileApi->m_categ_mgr.a_categ_ver_name, buf);
		m_FileData->GetAttr(ext_main[i], m_fileApi->m_categ_mgr.a_categ_descr, buf);
		m_FileData->PutAttr(main_act_ver, m_fileApi->m_categ_mgr.a_categ_ver_descr, buf);
		m_FileData->GetAttr(ext_main[i], m_fileApi->m_categ_mgr.a_categ_products, ext1);
		m_FileData->PutAttr(main_act_ver, m_fileApi->m_categ_mgr.a_categ_ver_products, ext1);
		m_FileData->PutAttr(ext_main[i], m_fileApi->m_categ_mgr.a_categ_act, main_act_ver);
		m_FileData->PutAttr(main_act_ver, m_fileApi->m_categ_mgr.a_categ_ver_categ, ext_main[i]);
		main_act_ver->SetTemporary(true);
		
		if(ext.Size>0)
		{
			map.Add((long)ext_main[i],(long)ext[0]);
			
			m_api->m_categ_mgr.LoadCategoryInfo(ext);

			aplExtent main_prds, prds;
			m_FileData->GetAttr(ext_main[i], m_fileApi->m_categ_mgr.a_categ_products, main_prds);
			m_data->GetAttr(ext[0], m_api->m_categ_mgr.a_categ_products, prds);
			
			bool bNewVer= false;
			if(main_prds.GetSize()!=prds.GetSize()) bNewVer= true;
			else 
			{
				m_api->m_categ_mgr.IsProductsInCategory(ext, main_prds, prds);
				if(main_prds.GetSize()) bNewVer= true;
			}

			if(bNewVer)//создается новая версия
			{
				ext_copy.Add(main_act_ver);
			}
			else //ничего не создаем
			{
				CaplInstance* inst2= NULL;
				m_data->GetAttr(ext[0], m_api->m_categ_mgr.a_categ_act, inst2);					
				map.Add((long)main_act_ver,(long)inst2);
			}
		}
		else
		{
			//первая версия
			m_FileData->PutAttr(main_act_ver, m_fileApi->m_categ_mgr.a_categ_ver_id, _T("0"));
			ext_copy.Add(main_act_ver);
		}
		/*else
		{	
			/*if(m_data->IsKindOf(ext_main[i],m_api->m_categ_mgr.e_prd_rel_prd_categ))
			{
				m_FileData->GetAttr(ext_main[i],m_fileApi->m_categ_mgr.a_categ_products,aggr);
				for(j=0; j<aggr.GetSize();j++)
				{
					aggr.GetByIndex(j,inst);
					if(inst!=0) ext_copy.Add(inst);
				}
			}
			else	
		}*/
		ext_copy.Add(ext_main[i]);
	}

	//////////////импорт PRODUCT_CATEGORY_RELATIONSHIP////////////////
	m_FileData->GetEntityExtent(m_fileApi->m_categ_mgr.e_categ_rel, ext_main);
	CaplInstance *i_pc1, *o_pc1,*i_pc2, *o_pc2, *o_pcr;
	for (i=0;i<ext_main.Size;i++)
	{
		o_pcr=0;
		m_FileData->GetAttr(ext_main[i],m_fileApi->m_categ_mgr.a_categ_rel_category,i_pc1);
		o_pc1=(CaplInstance*)map.QGetPointerByIn((long)i_pc1);
		if(o_pc1!=0)
		{
			m_FileData->GetAttr(ext_main[i],m_fileApi->m_categ_mgr.a_categ_rel_sub_category,i_pc2);
			o_pc2=(CaplInstance*)map.QGetPointerByIn((long)i_pc2);
			if(o_pc2!=0)
			{
				if((o_pc1->GetId()!=0)&&(o_pc2->GetId()!=0))
				{
					tst_values[0].value.Set(o_pc1);
					tst_values[0].attr=m_api->m_categ_mgr.a_categ_rel_category;
					tst_values[1].value.Set(o_pc2);
					tst_values[1].attr=m_api->m_categ_mgr.a_categ_rel_sub_category;

					m_data->NET_FindInstancesWithAttrValues(m_api->m_categ_mgr.e_categ_rel,2,&tst_values[0],ext,false);
					if(ext.Size>0) 
					{
						map.Add((long)ext_main[i],(long)ext[0]);
		///				o_pcr=ext_main[i];
					}
				}
		//		if(o_pcr==0)
		//			ext_copy.Add(ext_main[i]);
			}
		//	else ext_copy.Add(ext_main[i]);
		}
		//else
		ext_copy.Add(ext_main[i]);
	}
}

bool CaplExchangeManager::SaveDocsToWinETDpackage(CaplInstance *ciItem, bool bShowMsg)
{
	if(ciItem == NULL) return false;

	// узнаем куда будем сохранять
	CFileDialog dlg(false, _T("etd"), NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,  APL_T("Пакеты WinETD (*.etd)|*.etd"));
	if(dlg.DoModal() == false) return false;

	CaplPacket packet;	
	CFileDataSet *pFileDS = 0;
	CString sPath, sAddInfoMsg;
	aplExtent aeDocs, aeApproval, aeRev;
	CString sResultFilePath = dlg.GetPathName();

	long dID = aplStartWaitDlg( APL_T("Формирование пакета..."));

	// сохраняем документы в папке
	if(m_api->m_data.IsKindOf(ciItem, m_api->m_folder_mgr.e_folder))
	{
		m_api->m_folder_mgr.GetAllSubDocuments(ciItem, aeDocs, false);
		
		packet.m_pRootDataSet = new CFolderDataSet(&packet);
		m_api->m_data.GetAttr(ciItem, m_api->m_folder_mgr.a_folder_name, packet.m_pRootDataSet->m_sName);
		
		for(int i=0; i<aeDocs.Size; ++i)
		{
			if(!m_api->m_data.IsKindOf(aeDocs[i], m_api->m_doc_mgr.e_doc)) continue;

			// создаем объект и задаем ему имя
			pFileDS = new CFileDataSet(&packet, packet.m_pRootDataSet);
			m_api->m_doc_mgr.GetFullFileName(aeDocs[i], pFileDS->m_sName);

			// загружаем тело документа
			aplGetTempPath(sPath);
			sPath += pFileDS->m_sName;

			m_api->m_doc_mgr.LoadRevision(aeDocs[i], sPath, false, false);
			pFileDS->LoadItem(sPath, false);

			// удаляем временный файл
			::DeleteFile(sPath);

			// добавляем параметры и подписи
			AddEntriesAndApprovalToDataSet(m_api->m_data, packet, pFileDS, aeDocs[i], sAddInfoMsg, false);
		}
		
	}
	// сохраняем один документ
	else if(m_api->m_data.IsKindOf(ciItem, m_api->m_doc_mgr.e_doc))
	{
		// создаем объект и задаем ему имя
		packet.m_pRootDataSet = new CFileDataSet(&packet);
		m_api->m_data.GetAttr(ciItem, m_api->m_doc_mgr.a_doc_id, packet.m_pRootDataSet->m_sName);
		m_api->m_doc_mgr.GetFullFileName(ciItem, packet.m_pRootDataSet->m_sName);	

		// загружаем тело документа
		aplGetTempPath(sPath);
		sPath += packet.m_pRootDataSet->m_sName;

		m_api->m_doc_mgr.LoadRevision(ciItem, sPath, false, false);
		packet.m_pRootDataSet->LoadItem(sPath, false);

		// удаляем временный файл
		::DeleteFile(sPath);

		// добавляем параметры и подписи		
		AddEntriesAndApprovalToDataSet(m_api->m_data, packet, (CFileDataSet*)packet.m_pRootDataSet, ciItem, sAddInfoMsg, false);
	}
	else
	{
		aplEndWaitDlg(dID);
		return false;
	}	

	bool bResult = packet.Save(sResultFilePath);
	aplEndWaitDlg(dID);

	if(!sAddInfoMsg.IsEmpty()) AfxMessageBox(sAddInfoMsg, MB_ICONINFORMATION);

	if(bResult && bShowMsg)
		AfxMessageBox( APL_T("Пакет WinETD успешно сформирован."), MB_ICONINFORMATION);		
	else if(!bResult && bShowMsg)	
		AfxMessageBox( APL_T("Пакет WinETD сформировать не удалось!"), MB_ICONERROR);		
	
	return bResult;
}

bool CaplExchangeManager::AddEntriesAndApprovalToDataSet(CaplStepData &data, CaplPacket &packet, CFileDataSet *pFileDS, CaplInstance *ciItem, CString &sAddInfoMsg, bool bInstFromFile, CString sDir)
{
	if(ciItem == 0) return false;	

	int i = 0;	
	COleDateTime time, t1, t2;
	CaplInstance *ciStatus = NULL;
	bool bNonActualApproval = false;
	CString sDocId, sStatus, sAuthor;
	CString sEntryName, sEntryValue, buf;
	CString sSubjName, sCertSN, sRoles, sCertBLOB, sBlob;
	aplExtent aeEntriesValue, aeEntries, aeApproval, aeTmp;
	CaplInstance *ciEntry = NULL, *ciAppr = NULL, *ciDoc, *cit;
	
	// инициализируем сущности
	CaplEntity *pDocRevision = data.GetEntityBN(_T("apl_document_revision"));
	CaplEntity *pDocument = data.GetEntityBN(_T("document"));

	// инициализируем атрибуты
	CaplAttr *pDocId = data.GetAttrDefinitionBN(_T("apl_document"), _T("id"));
	CaplAttr *pRevDoc = data.GetAttrDefinitionBN(_T("apl_document_revision"), _T("of_document"));

	CaplAttr *pDocActive = data.GetAttrDefinitionBN(_T("apl_document"), _T("active"));
	CaplAttr *pEntryName = data.GetAttrDefinitionBN(_T("apl_document_entry"), _T("name"));
	CaplAttr *pRevEntries = data.GetAttrDefinitionBN(_T("apl_document_revision"), _T("entries"));
	CaplAttr *pValEntry = data.GetAttrDefinitionBN(_T("apl_document_entry_value"), _T("entry"));
	CaplAttr *pEntryValVal = data.GetAttrDefinitionBN(_T("apl_document_entry_value"), _T("value"));

	CaplAttr *pStatusName = data.GetAttrDefinitionBN(_T("approval_status"), _T("name"));
	CaplAttr *pRole = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("role"));
	CaplAttr *pAppItem = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("item"));	
	CaplAttr *pStatus = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("status"));
	CaplAttr *pComment = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("notes"));
	CaplAttr *pSign = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("digital_sign"));
	CaplAttr *pHash = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("digital_sign_hash"));
	CaplAttr *pDate = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("approval_date_time_s"));	
	CaplAttr *pSystem = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("digital_sign_metdod"));		
	CaplAttr *pCertBlobAttr = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("digital_sign_cert"));
	CaplAttr *pAuthor = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("digital_sign_author"));
	CaplAttr *pNewSign = data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("entries_used"));

	// проверка на версию документа
	if(data.IsKindOf(ciItem, pDocument)) { m_data->GetAttr(ciItem, pDocActive, ciItem); }
	else if(data.IsKindOf(ciItem, pDocRevision)) { ciItem = ciItem; }
	else return false;

	if(ciItem == NULL) return false;


	/*******************************************************************************************************/
	/*                                      Копируем реквизиты в объект WinETD                             */
	/*******************************************************************************************************/


	// получаем значения реквизитов
	data.GetAttr(ciItem, pRevEntries, aeEntriesValue);				

	// загружаем атрибуты
	if(bInstFromFile == false)
	{
		m_api->LoadExtentInfo(aeEntriesValue);
		for(i=0; i<aeEntriesValue.Size; i++)
		{
			m_api->m_data.GetAttr(aeEntriesValue[i], m_api->m_doc_mgr.a_doc_entry_val_entry, ciEntry);
			aeEntries.Add(ciEntry);
		}

		m_api->LoadExtentInfo(aeEntries);		
		aeEntries.Clear();

		// пишем значения реквизитов в строку	
		m_api->m_doc_mgr.GetActualEntriesVal(ciItem, aeEntriesValue);
		for(i=0; i<aeEntriesValue.Size; ++i)
		{
			data.GetAttr(aeEntriesValue[i], pValEntry, ciEntry);
			if(ciEntry == 0) continue;

			// добавляем информацию о реквизите
			data.GetAttr(ciEntry, pEntryName, sEntryName);
			data.GetAttr(aeEntriesValue[i], pEntryValVal, sEntryValue);

			pFileDS->m_Parametrs.Add(new CDataSetParam(sEntryName, sEntryValue));			
		}
	}
	else
	{
		for(int i=aeEntriesValue.Size-1; i>=0; i--)
		{
			data.GetAttr(aeEntriesValue[i], pValEntry, ciEntry);
			if(ciEntry == 0) continue;

			// каждый реквизит только один раз
			int size = aeEntries.Size;
			aeEntries.Add(ciEntry);
			if(size == aeEntries.Size) continue;				

			// добавляем информацию о реквизите
			data.GetAttr(ciEntry, pEntryName, sEntryName);
			data.GetAttr(aeEntriesValue[i], pEntryValVal, sEntryValue);

			pFileDS->m_Parametrs.InsertAt(0, new CDataSetParam(sEntryName, sEntryValue));			
		}		
	}					

	/*******************************************************************************************************/
	/*                                      Копируем подписи в объект WinETD                               */
	/*******************************************************************************************************/


	// получаем подписи для версий документа		
	if(bInstFromFile)
	{
		data.GetEntityExtentBN(_T("apl_approval_person_organization"), aeTmp);		
		for(int z=0; z<aeTmp.Size; z++)
		{
			data.GetAttr(aeTmp[z], pAppItem, cit);
			if(cit == ciItem) aeApproval.Add(aeTmp[i]);
		}
	}
	else
	{
		m_api->m_appr_mgr.LoadItemApproval(ciItem, aeApproval, true);		
	}

	// копируем подписи в объект WinETD
	for(i=0; i<aeApproval.Size; ++i)
	{
		// смотрим актуальна ли подпись
		if(!bInstFromFile && !m_api->m_appr_mgr.IsApprovalActual(aeApproval[i]))
		{
			// запомианаем информацию о неактуальной подписи			
			data.GetAttr(aeApproval[i], pAppItem, ciItem);
			data.GetAttr(ciItem, pRevDoc, ciDoc);
			data.GetAttr(ciDoc, pDocId, sDocId);

			data.GetAttr(aeApproval[i], pStatus, ciStatus);
			data.GetAttr(ciStatus, pStatusName, sStatus);

			data.GetAttr(aeApproval[i], pAuthor, sAuthor);

			sAddInfoMsg +=  APL_T("Документ: \"")+ sDocId +  APL_T("\"  Статус: \"") + sStatus +  APL_T("\"  Автор: \"")+sAuthor+_T("\".\n");

			bNonActualApproval = true;
			continue;
		}
		
		// статусы без ЭЦП нам не интересны
		data.GetAttr(aeApproval[i], pCertBlobAttr, sBlob);
		if(sBlob.IsEmpty()) continue;

		// создаем сертификат
		CDataSetSign *Sign = new CDataSetSign(&packet);
		data.GetAttr(aeApproval[i], pNewSign, Sign->m_bNewSign);		
		Sign->m_pDataSet=pFileDS;
		data.GetAttr(aeApproval[i], pStatus, ciStatus);
		data.GetAttr(ciStatus, pStatusName, Sign->m_sStatus);

		data.GetAttr(aeApproval[i], pRole, Sign->m_sRole);
		data.GetAttr(aeApproval[i], pComment, Sign->m_sComment);
		data.GetAttr(aeApproval[i], pSystem, Sign->m_sHashSystem);
		data.GetAttr(aeApproval[i], pSystem, Sign->m_sSignSystem);
		data.GetAttr(aeApproval[i], pHash, Sign->m_sHashBS);
		data.GetAttr(aeApproval[i], pSign, Sign->m_sSignBS);

		data.GetAttr(aeApproval[i], pDate, Sign->m_sDate);
		aplString2Date(Sign->m_sDate, time);
		Sign->m_sDate.Format(_T("%.2d.%.2d.%.4d"), time.GetDay(), time.GetMonth(), time.GetYear());		

		// ищем сертификат
		if(!bInstFromFile)
		{
			aplGetTempPath(buf);
			buf += CaplCryptographicManager::GenRandom();

			// общие данные о сертификате
			m_api->m_data.NET_LoadBlob(aeApproval[i], pCertBlobAttr, buf);
			CaplCryptographicManager::GetCertSubjectNameAndSN(buf, sSubjName, sCertSN, sRoles, t1, t2);

			// тело самого сертификата
			BYTE *pbCertBLOB = 0;
			int nCertBLOBsize = 0;

			CaplCryptographicManager::ReadFromFile(buf, pbCertBLOB, nCertBLOBsize);
			pbCertBLOB = new BYTE[nCertBLOBsize];
			CaplCryptographicManager::ReadFromFile(buf, pbCertBLOB, nCertBLOBsize);

			int iBlobLen= 2*nCertBLOBsize + 1;
			LPTSTR szOpenKeyBlob= sCertBLOB.GetBuffer(iBlobLen);
			CaplCryptographicManager::ByteToStr(nCertBLOBsize, pbCertBLOB, (LPSTR)szOpenKeyBlob);
			sCertBLOB.ReleaseBuffer();
		}
		else if(!sDir.IsEmpty())
		{
			CString sCertFile = sDir + "\\" + sBlob;

			// общие данные о сертификате
			CaplCryptographicManager::GetCertSubjectNameAndSN(sCertFile, sSubjName, sCertSN, sRoles, t1, t2);

			// тело самого сертификата
			BYTE *pbCertBLOB = 0;
			int nCertBLOBsize = 0;

			CaplCryptographicManager::ReadFromFile(sCertFile, pbCertBLOB, nCertBLOBsize);
			pbCertBLOB = new BYTE[nCertBLOBsize];
			CaplCryptographicManager::ReadFromFile(sCertFile, pbCertBLOB, nCertBLOBsize);

			int iBlobLen= 2*nCertBLOBsize + 1;
			LPTSTR szOpenKeyBlob= sCertBLOB.GetBuffer(iBlobLen);
			CaplCryptographicManager::ByteToStr(nCertBLOBsize, pbCertBLOB, (LPSTR)szOpenKeyBlob);
			sCertBLOB.ReleaseBuffer();
		}

		// добавляем сертификат в пакет
		CSignSert *exist_sert= 0;
		for(int j=0; j<packet.m_Sertificates.GetSize(); j++)
		{
			if(!packet.m_Sertificates[j]->m_sCertSN.IsEmpty() && 
				!packet.m_Sertificates[j]->m_sCertSN.Compare(sCertSN))
				exist_sert=packet.m_Sertificates[j]; // типа, как-бы нашли
		}

		if(exist_sert!=0) 
			Sign->m_pSertificate=exist_sert;
		else
		{
			exist_sert=new CSignSert(&packet);  // типа, как-бы взяли из системы
			exist_sert->m_sCertBS = sCertBLOB;		
			exist_sert->m_sPersonName= sSubjName;
			exist_sert->m_sCertSN= sCertSN;
			Sign->m_pSertificate=exist_sert;
		}
	}

	if(bNonActualApproval) sAddInfoMsg =  APL_T("Следующие подписи не попали в пакет в виду своей неактуальности:\n\n") + sAddInfoMsg;
	return true;
}

bool CaplExchangeManager::FormateWinETDPacket(LPCTSTR lpszFileName, CaplInstance* inst, bool bDeleteTempraryFiles,CString *err_mess)
{
	if(lpszFileName==NULL || inst==NULL) return false;

	CString sEntryName;
	CString sEntryValue;

	aplExtent aeResult;
	aplExtent aeEntries;
	aplExtent aeEntriesValue;
	CaplInstance *ciEntry = 0;
	CaplInstance *ciActive, *ciStored;

	int i;
	CString sPath = lpszFileName;
	CString sFileName = lpszFileName;
	if(sFileName.Mid(sFileName.GetLength()-4, 1)!=_T(".")) sFileName+=_T(".std");

	if(sPath.IsEmpty()) return false;

	//Проверка файла и получинени списка документов
	CaplEntity *pEntSD, *pEntAD, *pEntHC;
	aplExtent ext, sd_ext;
	CaplStepData f_data;
	CString sName;

	if(!f_data.LoadFromFile(lpszFileName))
	{
		AfxMessageBox(_T("Ошибка формирования пакета!\n\n(Ошибка загрузки сформированного обменного файла.)"),MB_OK|MB_ICONSTOP);
		return false;
	}

	pEntSD = f_data.GetEntityBN(_T("apl_stored_document"));
	pEntAD = f_data.GetEntityBN(_T("apl_assigned_document"));
	pEntHC = f_data.GetEntityBN(_T("apl_hardcopy_document"));
	
	f_data.GetEntityExtentBN(_T("apl_document_revision"), ext);

	CaplAttr *pDocActive = f_data.GetAttrDefinitionBN(_T("apl_document"), _T("active"));
	CaplAttr *pStoredDoc = f_data.GetAttrDefinitionBN(_T("apl_document_revision"), _T("access_form"));
	CaplAttr *pFileName = f_data.GetAttrDefinitionBN(_T("apl_stored_document"), _T("file_name"));

	CaplAttr *pSDSource = f_data.GetAttrDefinition(pEntSD, _T("source"));
	CaplAttr *pADPath = f_data.GetAttrDefinition(pEntAD, _T("location_path"));
	CaplAttr *pDRAF = f_data.GetAttrDefinitionBN(_T("apl_document_revision"), _T("access_form"));
	CaplAttr *pOfDoc = f_data.GetAttrDefinitionBN(_T("apl_document_revision"), _T("of_document"));
	CaplAttr *pDocId = f_data.GetAttrDefinitionBN(_T("document"), _T("id"));	

	int f_ind = sPath.ReverseFind(_T('\\'));
	if(f_ind)
		sPath = sPath.Left(f_ind+1);
	else
	{
		GetCurrentDirectory(MAX_PATH, sPath.GetBuffer(MAX_PATH));
		sPath.ReleaseBuffer();
	}

	CaplInstance *doc;
	CaplInstance *af;
	CString sDocId, sDocDescr, sPacketId;
	CString buf, sExt, sAddInfoMsg;
	CaplPacket pakect;
	CFileDataSet *pFileDS;

	if(m_api->m_data.IsKindOf(inst, m_api->m_prd_mgr.e_pdf))
	{
		CaplInstance *tmp;
		m_api->m_data.GetAttr(inst, m_api->m_prd_mgr.a_pdf_prd, tmp);
		if(tmp)
			m_api->m_data.GetAttr(tmp, m_api->m_prd_mgr.a_prd_id, sPacketId);
	}
	else
	{
		CaplAttr	*pAttrId = m_api->m_data.GetAttrDefinition(inst->GetType(), _T("id"));
		if(pAttrId)
			m_api->m_data.GetAttr(inst, pAttrId, sPacketId);
	}
	if(sPacketId.IsEmpty())
		m_api->GetItemName(inst, sPacketId);

	pakect.m_pRootDataSet = new CFolderDataSet(&pakect);
	pakect.m_pRootDataSet->m_sName = sPacketId;
	pakect.m_pRootDataSet->m_Parametrs.Add(new CDataSetParam( APL_T("Идентификатор"), sPacketId));

	pFileDS = new CFileDataSet(&pakect, pakect.m_pRootDataSet);
	if(!pFileDS->LoadItem(sFileName, true)) return false;

	for(i=0; i<ext.GetSize(); i++)
	{
		f_data.GetAttr(ext[i], pOfDoc, doc);
		if(doc==NULL) continue; //какая то хрень получается
		f_data.GetAttr(ext[i], pDRAF, af);
		if(af==NULL) continue; //какая то хрень получается

		sd_ext.Add(af);

		if(f_data.IsKindOf(af, pEntSD))
		{
			f_data.GetAttr(af, pSDSource, buf);
			buf = sPath+buf;
		}
		else if(f_data.IsKindOf(af, pEntSD))
			f_data.GetAttr(af, pADPath, buf);
		else continue;

		f_data.GetAttr(doc, pDocId, sDocId);
		pFileDS = new CFileDataSet(&pakect, pakect.m_pRootDataSet);

		// загружаем тело файла без параметров
		if(!pFileDS->LoadItem(buf, false))
		{
			if(err_mess!=0){
				*err_mess= APL_T("Не удалось загрузить тело документа с обозначением '")+sDocId+_T("'");
			}
			return false;
		}
		f_data.GetAttr(doc, pDocActive, ciActive);
		f_data.GetAttr(ciActive, pStoredDoc, ciStored);
		f_data.GetAttr(ciStored, pFileName, pFileDS->m_sName);

		// добавляем реквизиты активной версии документа + подписи с ЭЦП
		AddEntriesAndApprovalToDataSet(f_data, pakect, pFileDS, ext[i], sAddInfoMsg, true, sPath);

		// удаляем ненужные временные файлы
		if(bDeleteTempraryFiles)
		{
			DWORD dwAttr = ::GetFileAttributes(buf);
			if(dwAttr&FILE_ATTRIBUTE_READONLY)
			{
				dwAttr&=~FILE_ATTRIBUTE_READONLY;
				::SetFileAttributes(buf, dwAttr);
			}
			::DeleteFile(buf);

			f_ind = buf.ReverseFind(_T('.'));
			if(f_ind>-1)
				sExt = buf.Right(buf.GetLength()-f_ind-1);
			else
				sExt=_T("");
			if(sExt.CompareNoCase(_T("aplrep"))==0)
			{
				buf = buf.Left(f_ind+1) + _T("aplpar");
				DWORD dwAttr = ::GetFileAttributes(buf);
				if(dwAttr&FILE_ATTRIBUTE_READONLY)
				{
					dwAttr&=~FILE_ATTRIBUTE_READONLY;
					::SetFileAttributes(buf, dwAttr);
				}
				::DeleteFile(buf);
			}
		}
	}

	f_data.GetEntityExtentBN(_T("apl_stored_document"), ext);
	for(i=0; i<ext.GetSize(); i++)
	{
		if(sd_ext.Find(ext[i])>-1) continue;
		f_data.GetAttr(ext[i], pSDSource, buf);
		buf = sPath+buf;

		pFileDS = new CFileDataSet(&pakect, pakect.m_pRootDataSet);
		if(!pFileDS->LoadItem(buf, true)){
			if(err_mess!=0){
				*err_mess= APL_T("Не удалось загрузить тело документа из файла '")+buf+_T("'");
			}
			return false;
		}
		if(bDeleteTempraryFiles)
		{
			DWORD dwAttr = ::GetFileAttributes(buf);
			if(dwAttr&FILE_ATTRIBUTE_READONLY)
			{
				dwAttr&=~FILE_ATTRIBUTE_READONLY;
				::SetFileAttributes(buf, dwAttr);
			}
			::DeleteFile(buf);
			
			f_ind = buf.ReverseFind(_T('.'));
			if(f_ind>-1)
				sExt = buf.Right(buf.GetLength()-f_ind-1);
			else
				sExt=_T("");
			if(sExt.CompareNoCase(_T("aplrep"))==0)
			{
				buf = buf.Left(f_ind+1) + _T("aplpar");
				DWORD dwAttr = ::GetFileAttributes(buf);
				if(dwAttr&FILE_ATTRIBUTE_READONLY)
				{
					dwAttr&=~FILE_ATTRIBUTE_READONLY;
					::SetFileAttributes(buf, dwAttr);
				}
				::DeleteFile(buf);
			}
		}
	}

	// сохраняем сертификаты с подписей
	aplExtent aeApproval;
	CaplAttr *pApprovalAttr = f_data.GetAttrDefinitionBN(_T("apl_approval_person_organization"), _T("digital_sign_cert"));
	f_data.GetEntityExtentBN(_T("apl_approval_person_organization"), aeApproval);

	for(i=0; i<aeApproval.Size; ++i)
	{
		f_data.GetAttr(aeApproval[i], pApprovalAttr, buf);
		if(buf.IsEmpty()) continue;
		
		buf = sPath+buf;

		pFileDS = new CFileDataSet(&pakect, pakect.m_pRootDataSet);
		if(!pFileDS->LoadItem(buf, true)){
			if(err_mess!=0){
				*err_mess= APL_T("Не удалось загрузить сертификат ЭЦП'")+buf+_T("'");
			}
			return false;
		}

		if(bDeleteTempraryFiles)
		{
			DWORD dwAttr = ::GetFileAttributes(buf);
			if(dwAttr&FILE_ATTRIBUTE_READONLY)
			{
				dwAttr&=~FILE_ATTRIBUTE_READONLY;
				::SetFileAttributes(buf, dwAttr);
			}
			::DeleteFile(buf);

			f_ind = buf.ReverseFind(_T('.'));
			if(f_ind>-1)
				sExt = buf.Right(buf.GetLength()-f_ind-1);
			else
				sExt=_T("");
			if(sExt.CompareNoCase(_T("aplrep"))==0)
			{
				buf = buf.Left(f_ind+1) + _T("aplpar");
				DWORD dwAttr = ::GetFileAttributes(buf);
				if(dwAttr&FILE_ATTRIBUTE_READONLY)
				{
					dwAttr&=~FILE_ATTRIBUTE_READONLY;
					::SetFileAttributes(buf, dwAttr);
				}
				::DeleteFile(buf);
			}
		}
	}
	
	if(bDeleteTempraryFiles)
	{
		DWORD dwAttr = ::GetFileAttributes(lpszFileName);
		if(dwAttr&FILE_ATTRIBUTE_READONLY)
		{
			dwAttr&=~FILE_ATTRIBUTE_READONLY;
			::SetFileAttributes(lpszFileName, dwAttr);
		}
		::DeleteFile(lpszFileName);
	}

	sPath = lpszFileName;
	sPath +=_T(".etd");
	
	return pakect.Save(sPath);
}


SParamExchangeManager::SParamExchangeManager()
{
	m_ExportRequirments=TRUE;
	m_ExportProductInstance=TRUE;
	m_ExportSubCategory=TRUE;
	m_ExportClassifiers=TRUE;
	m_ExportSubProduct=TRUE;
	m_ExportProductMaterial=TRUE;
	m_ExportProductCharacteristics=TRUE;
	m_ExportAssDocuments=TRUE;
	m_ExportApproval=TRUE;
	m_ExportPrj=TRUE;	
	m_ExportPrjVer=FALSE;	
	m_ExportFolders=TRUE;
	m_ExportBP=TRUE;
	m_ExportBPRes=TRUE;
	m_ExportNotes=TRUE;
	m_bIgnoreAddDict=TRUE;
	m_bFormateETDPacket=FALSE;
	m_bDeleteTempraryFiles=FALSE;
	m_ext_sender=0;
}

bool CaplExchangeManager::ExportTechAssemblies(aplExtent &ext, const TCHAR *filename,
											   CString *err_mess)
{
	if(m_data==0)
		return false;
	if(!ext.GetSize())
		return false;
	CaplInstance *inst = NULL;

	bool bSaveFile=false;
	bool bFormateETDPacket = false;
	bool bDeleteTempraryFiles = false;

	aplExtent aeCurrent;
	aplExtent aeAll;
	aplExtent aeChilds;
	aplExtent aeComplPdfs;
	aplExtent aeParentPdfs;
	aplExtent aeCurrentRels;
	aplExtent aeAllRels;
	aplExtent aeChildRels;
	aplExtent aeComplRels;
	aplExtent aeParentRels;
	aplExtent aeBufCharVals;
	aplExtent aeCharVals;
	aplExtent aeChars;
	aplExtent aeUnits;
	aplExtent aePrds;
	aplExtent aeChildComplsPdfs;

	CString sBuf;
	

	CaplInstance* ciPrd = NULL;
	CaplInstance* ciPdf = NULL;
	CaplInstance* ciRel = NULL;
	CaplInstance* ciCharVal = NULL;
	CaplInstance* ciUnit = NULL;
	CaplInstance* ciChar = NULL;
	CaplInstance* ciOrg = NULL;

	m_array.Clear();
	m_exported_prd.Clear();
	m_exported_pdf.Clear();
	m_exported_doc.Clear();
	m_exported_items_4_approval.Clear();

	m_OutFile= filename;

	m_OutPath=_T("");
	int i=m_OutFile.ReverseFind(_T('\\'));
	if(i>0) m_OutPath=m_OutFile.Left(i+1);

	CreateDirectory(m_OutPath, NULL);

	bSaveFile=true;

	m_changed_values.Clear();
	m_changed_values_new.RemoveAll();
	m_changed_values_old.RemoveAll();

	int trd  =aplStartWaitDlg( APL_T("Идет формирование пакета..."));

	m_api->m_prd_mgr.LoadPrdInfo(ext);
	aeAll.Append(ext);
	for (i=0;i<ext.Size;i++)
	{
		ciPdf = ext[i];
		if (!ciPdf)
			continue;
		m_api->m_data.GetAttr(ciPdf,m_api->m_prd_mgr.a_pdf_prd,ciPrd);
		if (!ciPrd)
			continue;
		aePrds.Add(ciPrd);
		m_api->m_data.GetAttr(ciPrd,m_api->m_prd_mgr.a_prd_id,sBuf);
		if (sBuf.GetLength()>0&&
			(sBuf[0]==_T('T')||sBuf[0]==_T('Т'))&&
			(sBuf[1]==_T('С')||sBuf[1]==_T('К')||sBuf[1]==_T('C')||sBuf[1]==_T('K')))
		{
			aeCurrent.Add(ciPdf);
			aeCurrentRels.Add(ciRel);
		}
	}
	while (aeCurrent.Size)
	{
		aeComplPdfs.Append(aeCurrent);
		aeComplRels.Append(aeCurrentRels);
		m_api->m_prd_mgr.LoadAllSubProduct(aeCurrent,aeChildRels,aeChilds);

		aeCurrent.Clear();
		aeCurrentRels.Clear();


		for (i=0;i<aeChilds.Size;i++)
		{
			ciPdf = aeChilds[i];
			if (!ciPdf)
				continue;
			ciRel = aeChildRels[i];
			if (!ciRel)
				continue;
			m_api->m_data.GetAttr(ciPdf,m_api->m_prd_mgr.a_pdf_prd,ciPrd);
			if (!ciPrd)
				continue;
			aePrds.Add(ciPrd);
			m_api->m_data.GetAttr(ciPrd,m_api->m_prd_mgr.a_prd_id,sBuf);
			if (sBuf.GetLength()>0&&
				(sBuf[0]==_T('T')||sBuf[0]==_T('Т'))&&
				(sBuf[1]==_T('С')||sBuf[1]==_T('К')||sBuf[1]==_T('C')||sBuf[1]==_T('K'))
				&&(aeAll.Find(ciPdf)==-1))
			{
				aeCurrent.Add(ciPdf);
				aeCurrentRels.Add(ciRel);
			}
		}
		aeAll.Append(aeChilds);
		aeAllRels.Append(aeChildRels);
	}

	aeChilds.Clear();
	aeChildRels.Clear();
	
	for (i=0;i<aeAll.Size;i++)
	{
		ciPdf = aeAll[i];
		if (!ciPdf)
			continue;
		m_api->m_data.GetAttr(ciPdf,m_api->m_prd_mgr.a_apl_pdf_parent,ciPdf);
		if (!ciPdf)
			continue;
		aeChilds.Add(ciPdf);
	}

	for (i=0;i<aeAllRels.Size;i++)
	{
		ciRel = aeAllRels[i];
		if (!ciRel)
			continue;
		m_api->m_data.GetAttr(ciRel,m_api->m_prd_mgr.a_pdr_parent_reference,ciRel);
		if (!ciRel)
			continue;
		aeChildRels.Add(ciRel);
	}

	aeAllRels.Append(aeChildRels);
	m_api->LoadExtentInfo(aeChildRels);
	for (i=0;i<aeChildRels.Size;i++)
	{
		ciRel = aeChildRels[i];
		if (!ciRel)
			continue;
		m_api->m_data.GetAttr(ciRel,m_api->m_prd_mgr.a_pdr_r_ting,ciPdf);
		if (ciPdf)
			aeChilds.Add(ciPdf);
		m_api->m_data.GetAttr(ciRel,m_api->m_prd_mgr.a_pdr_r_ted,ciPdf);
		if (ciPdf)
			aeChilds.Add(ciPdf);
	}
	aeAll.Append(aeChilds);
	m_api->m_prd_mgr.LoadPrdInfo(aeChilds);
	for (i=0;i<aeChilds.Size;i++)
	{
		ciPdf = aeChilds[i];
		if (!ciPdf)
			continue;
		m_api->m_data.GetAttr(ciPdf,m_api->m_prd_mgr.a_pdf_prd,ciPrd);
		if (!ciPrd)
			continue;
		aePrds.Add(ciPrd);
	}
	m_api->m_charact_mgr.FindAssociatedCharacteristic(aeAll,aeBufCharVals);
	aeCharVals.Append(aeBufCharVals);
	m_api->m_charact_mgr.FindAssociatedCharacteristic(aeAllRels,aeBufCharVals);
	aeCharVals.Append(aeBufCharVals);
	for (i=0;i<aeCharVals.Size;i++)
	{
		ciCharVal = aeCharVals[i];
		if (!ciCharVal)
			continue;
		m_api->m_data.GetAttr(ciCharVal,m_api->m_charact_mgr.a_apl_charact_val_charact,ciChar);
		aeChars.Add(ciChar);
		if (!ciChar)
			continue;
		m_api->m_data.GetAttr(ciChar,m_api->m_charact_mgr.a_apl_charact_val_unit,ciUnit);
		if (ciUnit)
			aeUnits.Add(ciUnit);
		m_api->m_data.GetAttr(ciChar,m_api->m_charact_mgr.a_apl_charact_unit,ciUnit);
		if (ciUnit)
			aeUnits.Add(ciUnit);
		if (m_api->m_data.IsKindOf(ciCharVal,m_api->m_charact_mgr.e_apl_reference_value))
		{
			m_api->m_data.GetAttr(ciCharVal,m_api->m_charact_mgr.a_apl_reference_val,ciOrg);
			if (ciOrg)
				m_array.Add(ciOrg);
		}
	}

	m_array.Append(aeCurrent);
	m_array.Append(aeAll);
	m_array.Append(aeChilds);
	m_array.Append(aeComplPdfs);
	m_array.Append(aeParentPdfs);
	m_array.Append(aeCurrentRels);
	m_array.Append(aeAllRels);
	m_array.Append(aeChildRels);
	m_array.Append(aeComplRels);
	m_array.Append(aeParentRels);
	m_array.Append(aeBufCharVals);
	m_array.Append(aeCharVals);
	m_array.Append(aeChars);
	m_array.Append(aeUnits);
	m_array.Append(aePrds);
	m_array.Append(aeChildComplsPdfs);

	SaveArr2File();
	aplEndWaitDlg(trd);
	return true;
}