// aplTopLevelItem.cpp


#include "stdafx.h"
#include "resource.h"
#include "PSMDoc.h"
#include "aplTopLevelItem.h"
#include "TreeProductItem.h"
#include "aplTreeCharacteristicItem.h"
#include "aplCharacteristicGroupTreeItem.h"
#include "aplTreeApprovalItem.h"
#include "aplBPTreeItem.h"
#include "aplBPInstTreeItem.h"
#include "apl_lot_item.h"
#include "apl_prd_inst_item.h"
#include "PrdRelationDlg.h"
#include "NavigatorView.h"
#include "EffDlg.h"
#include "aplDocTreeItem.h"
#include "TabView.h"
#include "Defence.h"
#include "ExportToEfDlg.h"
#include "ExportSpecificationDlg.h"
#include "aplChangeTreeItem.h"
#include "ShorPdfInstanceHistory.h"
//#include "ShowContentsDialog.h"
#include "ProgressDialog.h"
#include "aplProjectTreeItem.h"
#include "aplSubstTreeItem.h"
#include "CaplRequirementTreeItem.h"
#include "act_res_treeitem.h"

#define _APL_TREE_ITEM_CHEK_PARAM \
        if(m_tree==0) return false;\
        if(m_doc==0) return false;

#define _APL_TREE_ITEM_CHEK_PARAM1 \
        if(m_tree==0) return;\
        if(m_doc==0) return;

bool CaplProductTreeItem::m_ShowId=true;
bool CaplProductTreeItem::m_ShowName=false;
bool CaplProductTreeItem::m_ShowPosition=false;
bool CaplProductTreeItem::m_ShowCount=false;
bool CaplProductTreeItem::m_PrdNoShowPlusToPart=false;

#define ICO_ITM_PRD 1
#define ICO_ITM_ZONE	ICO_ITM_PRD+1
#define ICO_ITM_SYS		ICO_ITM_PRD+2
#define ICO_ITM_MODULE	ICO_ITM_PRD+3
#define ICO_ITM_KOMPLEX ICO_ITM_PRD+4
#define ICO_ITM_KIT		ICO_ITM_PRD+5
#define ICO_ITM_ASM		ICO_ITM_PRD+6
#define ICO_ITM_PART	ICO_ITM_PRD+7
#define ICO_ITM_MAT		ICO_ITM_PRD+8


bool bShowMultiIcon=true;

//****************************************************************
//****************************************************************
//****************************************************************
CaplProductTreeItem::CaplProductTreeItem(CTreeCtrl *tree, CPSMDoc *doc,
										 CaplInstance *prd,CaplInstance *pdf)
{ 
	m_type=APL_TREE_ITEM_PRODUCT;
	m_prd_item_type=_T("part");
	m_tree=tree;
	m_doc=doc;
	m_prd=prd;
	m_pdf=pdf;
	m_alt=0;
	m_change= 0;
	m_nauo=0;
	m_folder=0;
	m_classifier=0;
	m_project=0;
	m_subst=0;
	m_rule= 0;
	if(doc!=0) 
	{
		doc->m_items.Add(this);
		if(m_pdf!=0)
		{
			if(m_pdf->GetType() !=0)
			{
				if(m_pdf->GetAccessmode() <=aplRO)
					m_doc_data.GetAttrBN(m_pdf,S::of_product,m_prd);
			}
		}
	}

	if(m_pdf==0)m_prd_item_type=S::product;	
}
//****************************************************************
bool CaplProductTreeItem::TrackPopupMenu(CWnd *wnd, CPoint &point, UINT view_mode)
{
	if(0==m_prd) return false;
	if(m_prd->GetAccessmode()>aplRO) return false;
	if(0!=m_pdf) {if(m_pdf->GetAccessmode()>aplRO) return false;}

	CMenu std_menu;
	CMenu menu;  gSetPsmResourceHandle();
	CMenu* pPopup =0;
	if(CaplTreeItem::m_def_context_menu)
	{
		VERIFY(std_menu.LoadMenu(IDR_TREE_CONTEXT_MENU));
		pPopup = std_menu.GetSubMenu(INDEX_PRODUCT_MENU);
	}
	else
	{
		VERIFY(menu.LoadMenu(IDR_TREE_CONTEXT_MENU));
	//	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));
		//VERIFY(CaplMenu::Install(wnd, ePopupMenu ));
		pPopup = menu.GetSubMenu(INDEX_PRODUCT_MENU);
	}
    ASSERT(pPopup != NULL);
	if(pPopup==0) {AfxMessageBox( APL_T("Ошибка при создании меню"));return false;}
	CaplMenu::Install(wnd); 
	bool hide=true;

	AppendAddIn((CMenu*)pPopup);
	UpdateMenu((CMenu**)&pPopup, view_mode);

	if((m_nauo==0)&&(m_alt==0)&&(m_project==0)&&(m_subst==0)) pPopup->EnableMenuItem(ID_PRODUCT_REMOVE_RELATION,MF_BYCOMMAND|MF_GRAYED);
	if(m_alt==0) pPopup->RemoveMenu(ID_SHOW_REL_PROPERTIES, MF_BYCOMMAND);
	if(m_prd_item_type==S::product)
	{
		pPopup->EnableMenuItem(ID_EXPORT_ESI,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_SHOW_PARENT_PRODUCT,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_FIND_IN_CONTENTS,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_SUPPLIED_PART,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_WHERE_USED,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_SHOW_REFUSAL,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_SHOW_EFFECTIVITY,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_SHOW_MATER_EFFECTIVITY,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_SHOW_LIST_EFFECTIVITY,MF_BYCOMMAND|MF_GRAYED);		
		pPopup->EnableMenuItem(ID_PRODUCT_SHOW_BOM,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_SHOW_EXPLOSION,MF_BYCOMMAND|MF_GRAYED);
		
		pPopup->EnableMenuItem(ID_WFS_HISTORY,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_WFS_CHANGE,MF_BYCOMMAND|MF_GRAYED);

		pPopup->EnableMenuItem(ID_CREATE_PRODUCT,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_CREATE_PRODUCT_BY_DOT,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_SUPPLIED_PART,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_WHERE_USED_AS_RES,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_SHOW_ALL_LOT,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_SHOW_ALL_INST,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_SHOW_ALL_INST_HISTORY,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_SHOW_ALL_SUBPART,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_SHOW_ALL_ZAGOTOV,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_SUBSCRIPTION,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_CREATE_PRD_COPY, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_REPLACE_TO_PRD_COPY, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_EXPORT_ITEM, MF_BYCOMMAND | MF_GRAYED);
		

		if(m_prd->GetAccessmode()>aplRW)
		{
// 			pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC,MF_BYCOMMAND|MF_GRAYED);
// 			pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC_GROUP,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_SHOW_EXPORT_PRODUCT_DEFINITIONS, MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_CREATE_EXPORT_PRODUCT_DEFINITION, MF_BYCOMMAND|MF_GRAYED);
		}

		HTREEITEM hitem=m_tree->GetParentItem(m_item);
		CaplTreeItem *treeitem=NULL;
		if(hitem) treeitem= (CaplTreeItem *)m_tree->GetItemData(hitem);
		if(treeitem!=0)	{if(treeitem->m_type==APL_TREE_ITEM_CATEGORIES)hide=false;}
	}
	if(hide) pPopup->EnableMenuItem(ID_PRODUCT_REMOVE_FROM_CAREGORY,MF_BYCOMMAND|MF_GRAYED);
	if(m_pdf!=0)
	{
		pPopup->EnableMenuItem(ID_DELETE,MF_BYCOMMAND|MF_GRAYED);
		if(m_pdf->GetAccessmode()>aplRO)
		{
			pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_EXPORT_STRUCTE_TO_TEXT_FILE,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_EXPORT_TO_EF,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_EXPORT_TO_SPECIFIC,MF_BYCOMMAND|MF_GRAYED);
//			pPopup->EnableMenuItem(ID_CREATE_PRD_INST,MF_BYCOMMAND|MF_GRAYED);
//			pPopup->EnableMenuItem(ID_CREATE_LOT,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_SET_INST_ACCSESS_RECURSIVE,MF_BYCOMMAND|MF_GRAYED);

			pPopup->EnableMenuItem(ID_PRODUCT_SUPPLIED_PART,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_WHERE_USED,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_SHOW_EFFECTIVITY,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_SHOW_MATER_EFFECTIVITY,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_SHOW_LIST_EFFECTIVITY,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_SHOW_BOM,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_SHOW_EXPLOSION,MF_BYCOMMAND|MF_GRAYED);

			pPopup->EnableMenuItem(ID_CREATE_PRODUCT,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_CREATE_PRODUCT_BY_DOT,MF_BYCOMMAND|MF_GRAYED);
//			pPopup->EnableMenuItem(ID_PRODUCT_SHOW_EFFECTIVITY,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_SUPPLIED_PART,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_SHOW_ALL_LOT,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_SHOW_ALL_INST,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_SHOW_ALL_INST_HISTORY,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_SHOW_ALL_SUBPART,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_SHOW_ALL_ZAGOTOV,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_SHOW_ALL_CHANGES ,MF_BYCOMMAND|MF_GRAYED);	
			pPopup->EnableMenuItem(ID_PRODUCT_CHECK_IN_CATEG ,MF_BYCOMMAND|MF_GRAYED);	
			pPopup->EnableMenuItem(ID_REMOVE_CHANGE_REL, MF_BYCOMMAND | MF_GRAYED);
			pPopup->EnableMenuItem(ID_SHOW_REFUSAL, MF_BYCOMMAND | MF_GRAYED);
		}
		else if(m_pdf->GetAccessmode()==aplRO)
		{
			pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
// 			pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC,MF_BYCOMMAND|MF_GRAYED);
// 			pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC_GROUP,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_SET_INST_ACCSESS_RECURSIVE,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_CREATE_PRODUCT,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_CREATE_PRODUCT_BY_DOT,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_REMOVE_CHANGE_REL, MF_BYCOMMAND | MF_GRAYED);
		}
		else if(m_pdf->GetAccessmode()==aplRW)
		{
			pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
		}
		if(!m_nauo) pPopup->EnableMenuItem(ID_SHOW_ALL_SUBSTITUTES,MF_BYCOMMAND|MF_GRAYED);
	}
	else
	{
		
		pPopup->EnableMenuItem(ID_PRODUCT_FIND_IN_CONTENTS,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_EXPORT_STRUCTE_TO_TEXT_FILE,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_EXPORT_TO_EF,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_EXPORT_TO_SPECIFIC,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_CREATE_PRD_INST,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_CREATE_LOT,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_SET_INST_ACCSESS_RECURSIVE,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_SHOW_ALL_CHANGES ,MF_BYCOMMAND|MF_GRAYED);	
		pPopup->EnableMenuItem(ID_SHOW_ALL_INST,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_SHOW_ALL_LOT,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_REMOVE_CHANGE_REL, MF_BYCOMMAND | MF_GRAYED);
	}
	if(m_prd==0 && m_pdf==0){
		pPopup->EnableMenuItem(ID_SHOW_CONTAINED_FOLDER, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_SHOW_CONTAINED_CLASSIFIER, MF_BYCOMMAND | MF_GRAYED);
	}
	if(m_folder==0)
		pPopup->EnableMenuItem(ID_REMOVE_FROM_FOLDER, MF_BYCOMMAND | MF_GRAYED);

	if(m_classifier==0){pPopup->EnableMenuItem(ID_REMOVE_FROM_CLASSIFIER, MF_BYCOMMAND | MF_GRAYED);}


	// Проверка заменить на копию
	{
		bool bDisabled=true;
		if(0!=m_pdf)
		{
			if(0!=m_nauo && m_prd_item_type==_T("part")) bDisabled=false;
			else
			{
				HTREEITEM hitem=m_tree->GetParentItem(m_item);
				CaplTreeItem *parentTtreeIitem=NULL;
				if(hitem) parentTtreeIitem= (CaplTreeItem *)m_tree->GetItemData(hitem);
				if(parentTtreeIitem!=0)
				{
					if(parentTtreeIitem->m_type==APL_TREE_ITEM_BPRES) bDisabled=false;
				}
			}
		}
		if(bDisabled) pPopup->EnableMenuItem(ID_REPLACE_TO_PRD_COPY, MF_BYCOMMAND | MF_GRAYED);
	}


	CString sState(_T("applied"));
	CaplInstance* locker= NULL;
	if(m_pdf) 
		m_doc->m_api.m_data.GetAttr(m_pdf, m_doc->m_api.m_prd_mgr.a_apl_pdf_locker, locker);
	if(locker)
		m_doc->m_api.m_data.GetAttr(locker, m_doc->m_api.m_change_mgr.a_chng_state, sState);
	if(sState==_T("applied") || sState==_T("canceled"))
	{
		pPopup->EnableMenuItem(ID_REMOVE_CHANGE_REL, MF_BYCOMMAND | MF_GRAYED);
	}

#ifdef _DEMO
	pPopup->EnableMenuItem(ID_FREZEE_INST, MF_BYCOMMAND | MF_GRAYED);
	pPopup->EnableMenuItem(ID_SET_INST_ACCSESS, MF_BYCOMMAND | MF_GRAYED);
	pPopup->EnableMenuItem(ID_SET_INST_ACCSESS_RECURSIVE, MF_BYCOMMAND | MF_GRAYED);
	pPopup->EnableMenuItem(ID_SET_INST_OWNER, MF_BYCOMMAND | MF_GRAYED);
#endif
//---------------------------------Состояния-----------------------------------
	aplExtent instances;
	GetAccessedInstances(instances);

	if(m_doc->m_api.m_data.IsKindOf(instances[0],m_doc->m_api.m_prd_mgr.e_pdf))
	{
		CaplInstance *m_inst = instances[0];
		CStringArray states;
		CString val = m_doc->m_api.m_doc_mgr.GetPossibleWFState(m_inst,states);
		
			if(val==_T("approving"))
			{
//				pPopup->EnableMenuItem(ID_CREATE_DOC, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC_GROUP, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_BP, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_PRODUCT, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_PRODUCT_CREATE_VERSION, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_BP_INST, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_LOT, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_PRD_INST, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_PRODUCT_BY_DOT, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
			}
			else if(val==_T("approved"))
			{
//				pPopup->EnableMenuItem(ID_CREATE_APPROVAL, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_DOC, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC_GROUP, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_BP, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_PRODUCT, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_PRODUCT_CREATE_VERSION, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_BP_INST, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_LOT, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_PRD_INST, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_PRODUCT_BY_DOT, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
			}
			else if(val==_T("canceled"))
			{
				pPopup->EnableMenuItem(ID_CREATE_APPROVAL, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_DOC, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC_GROUP, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_BP, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_PRODUCT, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_CREATE_VERSION, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_BP_INST, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_LOT, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_PRD_INST, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_PRODUCT_BY_DOT, MF_BYCOMMAND | MF_GRAYED);
			}
			else if(val==_T("approving_change"))
			{
//				pPopup->EnableMenuItem(ID_CREATE_DOC, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC_GROUP, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_BP, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_PRODUCT, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_PRODUCT_CREATE_VERSION, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_BP_INST, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_LOT, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_CREATE_PRD_INST, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_PRODUCT_BY_DOT, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION,MF_BYCOMMAND|MF_GRAYED);
			}
	}
	else
	{
//		pPopup->DeleteMenu(4,MF_BYPOSITION);
//		pPopup->DeleteMenu(4,MF_BYPOSITION);
	}
//---------------------------------Состояния-----------------------------------
 
//	AppendForms((CMenu*)pPopup);


	if(m_doc->m_api.m_prd_mgr.bNoCreateAndChangePDF)
	{
		pPopup->EnableMenuItem(ID_CREATE_PRODUCT, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_CREATE_PRODUCT_BY_DOT, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_CREATE_VERSION, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_PRODUCT_DELETE_VERSION, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_CREATE_PRD_COPY, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_REPLACE_TO_PRD_COPY, MF_BYCOMMAND | MF_GRAYED);
	}

	if(!m_doc->m_api.m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие"))) 
	{
		pPopup->DeleteMenu(ID_EXPORT_ESI,MF_BYCOMMAND);
	}

	#ifdef _UNICODE
		pPopup->RemoveMenu(ID_SHOW_PARENT_CATEGORIES, MF_BYCOMMAND);
	#endif


	BOOL res=pPopup->TrackPopupMenu(TPM_LEFTALIGN|
		TPM_RIGHTBUTTON|TPM_RETURNCMD,point.x, point.y,wnd);

	switch (res)
	{
	case ID_SHOW_REL_PROPERTIES:
		ShowRelationProperties();
		break;
	case ID_SHOW_CONTAINED_PROJECTS:
		ShowContainedProjects(m_pdf);
		break;
	case ID_SHOW_CONTAINED_PROCCESS:
		ShowContainedProccess(m_pdf);
		break;
	case ID_SHOW_REFUSAL:
		ShowAllResusal(true,true);
		break;
	case ID_SHOW_PARENT_PRODUCT:
		InsertInstInTree(m_prd,m_item,m_doc,m_tree,m_all_projects,0,0);
		MyExpand(false);
		break;
	case ID_SHOW_CONTAINED_FOLDER:
		ShowContainedFolder(m_pdf==0?m_prd:m_pdf);
		break;
	case ID_SHOW_CONTAINED_CLASSIFIER:
		ShowContainedClassifier(m_pdf==0?m_prd:m_pdf);
		break;

	case ID_SHOW_CONTAINED_MESSAGE: ShowContainedMessage(m_pdf==0?m_prd:m_pdf); break;
	case ID_SHOW_CONTAINED_TASKS: ShowContainedTasks(m_pdf==0?m_prd:m_pdf); break;
	case ID_SHOW_CONTAINED_ALERT: ShowContainedAlert(m_pdf==0?m_prd:m_pdf); break;

	case ID_PRODUCT_FIND_IN_CONTENTS:FindInContents();break;
	case ID_REFRESH_ITEM: RefreshItem(); break;
	case ID_OPEN_ITEM_IN_NEW_WINDOW:
		if(m_pdf!=0) m_doc->OpenInstanceInNewWindow(m_pdf);
		else if(m_prd!=0) m_doc->OpenInstanceInNewWindow(m_prd);
		break;
	case ID_PRODUCT_WHERE_USED: ShowAllParentProduct(); break;
	case ID_PRODUCT_WHERE_USED_AS_RES: ShowAllUsesBP();break;
	case ID_PRODUCT_SUPPLIED_PART: ShowAllSupplied(); break;
	case ID_PRODUCT_SHOW_ALTERNATE: ShowAllAlternate(); break;
	case ID_PRODUCT_SHOW_ALL_ZAGOTOV: ShowAllZagotov(); break;
	case ID_PRODUCT_SHOW_ALL_SUBPART: ShowAllSubProduct(); break;
	case ID_RECURSE_FIND: ShowRecurseFind(); break;
	case ID_SHOW_ALL_BP: ShowAllBPs(true);break;
	case ID_SHOW_ALL_BP_INST: ShowAllBPInst(true);break;
	case ID_SHOW_ALL_CHANGES: ShowAllChanges(); break;
	case ID_SHOW_ALL_REQUIREMENT: ShowAllRequirement(); break;
	case ID_SHOW_PROJECTS: 
		{
		CaplInstance *inst=m_prd;
		if(m_pdf) inst=m_pdf;
		if(inst)ShowAllProjects(inst); 
		}
		break;
	case ID_CREATE_PROJECT: CreateProject(); break;
	
	case ID_CREATE_BP:
		if(m_pdf!=0)CreateBP(m_pdf);
		else CreateBP(m_prd);
		break;
	case ID_CREATE_BP_INST:	CreateBPInst();	break;
	case ID_PRODUCT_CREATE_VERSION: CreateProductVersion(); break;
	case ID_CREATE_PRODUCT: CreateSubPart();break;
	case ID_CREATE_PRD_COPY: CreateProductCopy();break;
	case ID_REPLACE_TO_PRD_COPY: ReplaceToProductCopy();break;
	case ID_CREATE_CHARACTERISTIC: CreateCharacteristic();break;
	case ID_CREATE_CHARACTERISTIC_GROUP: CreateCharacteristicGroup();break;

	case ID_PRODUCT_REMOVE_RELATION: 
		if(m_pdf==0)m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_prd);
		else m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_pdf);
		RemoveRelation();
		break;
	case ID_PRODUCT_DELETE_VERSION:
		if(m_pdf==0)m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_prd);
		else m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_pdf);
		RemoveProductVersion();
		break;
	case ID_DELETE:					 RemoveProduct(); break;
	case ID_PRODUCT_REMOVE_FROM_CAREGORY: RemoveFromCategory();break;

	case ID_DEL_PARENT_PDF:		
		if (IDYES == AfxMessageBox(APL_T("Удалить связь с исходным изделием?"), MB_YESNO | MB_ICONWARNING))
		{
			m_doc->m_api.m_data.PutAttr(m_pdf, m_doc->m_api.m_prd_mgr.a_apl_pdf_parent, (CaplInstance*)0);
			if (m_nauo)
				m_doc->m_api.m_data.PutAttr(m_nauo, m_doc->m_api.m_prd_mgr.a_pdr_parent_reference, (CaplInstance*)0);
			m_doc_data.NET_SaveChanges();
		}
		break;
	
	case ID_PRODUCT_EXPORT_STRUCTE_TO_TEXT_FILE: ExportStructureToTextFile();break;
	case ID_PRODUCT_EXPORT_TO_EF: ExportStructureToEF(); break;
	case ID_PRODUCT_SHOW_BOM: ShowBOM();break;
	case ID_PRODUCT_SHOW_EXPLOSION: ShowExplosion();break;
	case ID_PRODUCT_EXPORT_TO_SPECIFIC: EportSpecific();break;	
	
	//case : break;
	case ID_PRODUCT_SHOW_LIST_EFFECTIVITY: 
		if(m_pdf!=0)
		{
			if(m_pdf->GetAccessmode()<=aplRO)
			{
				CEffDlg dlg;
				dlg.m_pdf=m_pdf;
				dlg.m_data=&(m_doc->m_api.m_data);
				dlg.m_doc=m_doc;
				dlg.m_prd_mgr=&(m_doc->m_api.m_prd_mgr);
				dlg.DoModal();
				m_doc_data.NET_SaveChanges();
				RefreshItem();
				m_tree->SetRedraw(FALSE);
				HTREEITEM hItem,hItemNext=m_tree->GetChildItem(m_item);
				while(hItemNext!=0)
				{
					hItem=hItemNext; hItemNext=m_tree->GetNextItem(hItem, TVGN_NEXT);
					CaplTreeItem *item=(CaplTreeItem *)m_tree->GetItemData(hItem);
					if(item!=0)item->RefreshItem();
				}
				m_tree->SetRedraw(TRUE);
			}
		}
		break;
	case ID_PRODUCT_SHOW_EFFECTIVITY: 
		if(m_pdf!=0)
		{			
			if(m_pdf->GetAccessmode()<=aplRO)
			{
				if(m_doc->m_api.m_prd_mgr.StartEffectivityManager(0,m_pdf,0,m_doc->m_api.m_prd_mgr.e_acu))
				{
					m_doc_data.NET_SaveChanges();
					RefreshItem();
					m_tree->SetRedraw(FALSE);
					HTREEITEM hItem,hItemNext=m_tree->GetChildItem(m_item);
					while(hItemNext!=0)
					{
						hItem=hItemNext; hItemNext=m_tree->GetNextItem(hItem, TVGN_NEXT);
						CaplTreeItem *item=(CaplTreeItem *)m_tree->GetItemData(hItem);
						if(item!=0)item->RefreshItem();
					}
					m_tree->SetRedraw(TRUE);
				}
			}
		}
		break;
	case ID_PRODUCT_SHOW_MATER_EFFECTIVITY: 
		if(m_pdf!=0)
		{			
			if(m_pdf->GetAccessmode()<=aplRO)
			{
				aplExtent ext1, ext2;
				m_doc->m_api.m_prd_mgr.LoadAllZagotov(m_pdf, ext1, ext2);
				if(m_doc->m_api.m_prd_mgr.StartEffectivityManager(0,m_pdf,0,m_doc->m_api.m_prd_mgr.e_make_from))
				{
					m_doc_data.NET_SaveChanges();
					RefreshItem();
					m_tree->SetRedraw(FALSE);
					HTREEITEM hItem,hItemNext=m_tree->GetChildItem(m_item);
					while(hItemNext!=0)
					{
						hItem=hItemNext; hItemNext=m_tree->GetNextItem(hItem, TVGN_NEXT);
						CaplTreeItem *item=(CaplTreeItem *)m_tree->GetItemData(hItem);
						if(item!=0)item->RefreshItem();
					}
					m_tree->SetRedraw(TRUE);
				}
			}
		}
		break;
	case ID_REMOVE_FROM_FOLDER:
		if(m_folder!=0)
		{
			if(m_folder->GetAccessmode()>aplRW)	{AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return true;}
			CaplInstance *inst=m_pdf;
			if(inst==0) inst=m_prd;
			if(inst==0) break;
			if(m_doc->m_api.m_folder_mgr.RemoveFromFolder(m_folder,inst))
				m_doc->m_items.Remove(m_doc->m_items.Find(this));
		}
		break;
	case ID_REMOVE_FROM_CLASSIFIER:
		if(m_classifier!=0)
		{
			if(m_classifier->GetAccessmode()>aplRW)	{AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return true;}
			CaplInstance *inst=m_pdf;
			if(inst==0) inst=m_prd;
			if(inst==0) break;
			if(m_doc->m_api.m_classifier_mgr.DeleteClassifierAssociation(inst,m_classifier))
				m_doc->m_items.Remove(m_doc->m_items.Find(this));
		}
		break;
	case ID_REMOVE_CHANGE_REL:
		{
			CaplAPI* m_api= &m_doc->m_api;
			aplExtent chngAssms;
			CaplInstance* locker_1= NULL;
			m_api->m_data.GetAttr(m_pdf, m_api->m_prd_mgr.a_apl_pdf_locker, locker_1);
			m_api->m_data.GetAttr(locker_1, m_api->m_change_mgr.a_chng_changed_assemlies, chngAssms);
			chngAssms.Remove(chngAssms.Find(m_pdf));
			m_api->m_data.PutAttr(locker_1, m_api->m_change_mgr.a_chng_changed_assemlies, chngAssms);
			locker_1= NULL;
			m_change= NULL;
			m_api->m_data.PutAttr(m_pdf, m_api->m_prd_mgr.a_apl_pdf_locker, locker_1);
			m_api->SaveChanges();
		}
		break;
	case ID_CREATE_LOT: 
		{
			CaplInstance *lot=m_doc->m_api.m_prd_inst_mgr.CreateLot(m_pdf);
			if(lot!=0)
			{
				CaplLotTreeItem *lot_item= new CaplLotTreeItem(m_tree,m_doc,lot);
				lot_item->CreateTreeItem(m_item);
				m_all_lots.Add(lot);
				MyExpand();
			}
		}
		break;
	case ID_SHOW_ALL_LOT: ShowAllLot();
		break;
	case ID_CREATE_PRD_INST: 
		{
			CaplInstance *prd_inst=m_doc->m_api.m_prd_inst_mgr.CreatePrdInst(m_pdf);
			if(prd_inst!=0)
			{
				CaplPrdInstTreeItem *inst_item= new CaplPrdInstTreeItem(m_tree,m_doc,prd_inst);
				inst_item->CreateTreeItem(m_item);
				m_all_prd_inst.Add(prd_inst);
				MyExpand();
			}
		}
		break;
	case ID_SHOW_ALL_INST: ShowAllPrdInst();
		break;
	case ID_SHOW_ALL_INST_HISTORY:
		{
			if(m_pdf!=0)
			{
				if(m_pdf->GetAccessmode()>aplRO) AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);
				else
				{
					CShorPdfInstanceHistory dlg;
					dlg.m_pdf=m_pdf;
					dlg.m_pApi=&m_doc->m_api;
					dlg.DoModal();
				}
			}
		}
		break;
//	case ID_SET_ACCESS_PRODUCT_CONTENT: 
//		 // Запретить изменения для всех входящих
//		if(m_pdf!=0)
//		{
//			aplInstArray ext_pdf,ext_unit;
//			aplRealArray count_array;
//			aplExtent ext;
//			ext.Add(m_pdf);
//			int i;
//			if(m_doc->m_api.m_prd_mgr.DisassemblyProduct(0,0,m_pdf,ext_pdf,count_array,ext_unit,false))
//			{
//				for(i=0;i<ext_pdf.Size;i++)
//				{
//					if(ext_pdf[i]->GetAccessmode()<aplRO) 
//						ext.Add(ext_pdf[i]);	
//				}
//			}
//			//if(IDYES==AfxMessageBox(APL_T("Запретить изменение данного изделия и всех в него входящих ?"),MB_YESNO|MB_ICONQUESTION))
//			{
//				m_doc_data.NET_SetInstancesAccess(&ext);
//			}
//			if(m_doc->m_api.SetRecursiveAccess(m_pdf)){
//				AfxMessageBox(APL_T("Права доступа успешно изменены!"),MB_ICONINFORMATION | MB_OK);
//			}
//		}
//		break;
	case ID_SHOW_PARENT_CATEGORIES: 
		 // Показать категории куда входит данное изделие
		if(m_prd!=0)
		{
			aplExtent ext;
			m_doc->m_api.m_categ_mgr.GetProductCategories(m_prd,ext);
			if(ext.Size==0) AfxMessageBox( APL_T("Нет родительских категорий"));
			else
			{
				m_doc->m_api.m_categ_mgr.LoadCategoryInfo(ext);
				for(int i=0;i<ext.Size;i++)
				{
					if(m_all_category.Find(ext[i])!=-1) continue;
					CaplCategoryTreeItem *categ_item=
					new CaplCategoryTreeItem(m_tree,m_doc,0,ext[i]);
					categ_item->CreateTreeItem(m_item);
					m_all_category.Add(ext[i]);
				}
				MyExpand();
			}
		}
		break;
	case ID_PRODUCT_CHECK_IN_CATEG: 
		{
			CaplInstance *categ=m_doc->m_api.m_categ_mgr.SelectInstance(APL_MODE_SELECT_CATEGORY, APL_T("Выберите категорию"));
			if(categ!=0)
			{	
				long trd=aplStartWaitDlg( APL_T("Выполняется проверка ..."));
				m_doc->m_api.m_categ_mgr.LoadCategoryInfo(categ,true);
				
				bool b=m_doc->m_api.m_categ_mgr.FindProductInCategory(m_prd,categ,true);
				aplEndWaitDlg(trd);

				if(b)
					AfxMessageBox( APL_T("Изделие входит в данную категорию."));
				else
					AfxMessageBox( APL_T("Изделие в данную категорию не входит."),MB_OK|MB_ICONSTOP);
			}
		}
		break;
	case ID_CREATE_PRODUCT_BY_DOT:
		{
			aplExtent res;
			CaplInstance *inst = m_doc->m_api.m_prd_mgr.CreatePdfByDot(m_pdf, res);
			if(inst!=NULL) ShowAllSubProduct();
		}
		break;
	case ID_WFS_CHANGE: 
		if(m_doc->m_api.m_doc_mgr.ChangeWFState(instances[0],_T("")))
		{
			m_doc->OnRefreshAllTreeItem();
// 			Expand(1);
// 			Expand(2);
		}
			break;
	case ID_WFS_HISTORY: m_doc->m_api.m_doc_mgr.ShowWFStateHistory(instances[0]);
		break;
	case ID_SUBSCRIPTION:
		{
			CaplInstance* inst= NULL;
			if(m_pdf!=0) inst= m_pdf;
			else if(m_prd!=0) inst= m_prd; 
			m_doc->m_api.m_message_mgr.EditItemSubscribeList(inst);
		}
		break;
	case ID_SHOW_ALL_SUBSTITUTES:ShowAllSubstitutes();break;
	case ID_CREATE_EXPORT_PRODUCT_DEFINITION:
		m_doc->m_api.m_prd_mgr.CreateExportProduct(m_prd, NULL);
		break;
	case ID_SHOW_EXPORT_PRODUCT_DEFINITIONS:
		m_doc->m_api.m_prd_mgr.ShowExportProduct(m_prd);
		break;
	case ID_EXPORT_ESI:
		m_doc->m_api.m_prd_mgr.GenerateESI(m_pdf,_T(""),true);
		break;	

	case ID_EXPORT_ITEM:
		if(0!=m_pdf) m_doc->ExportItem(m_pdf);
		break;

	case ID_CREATE_WF_PROCESS:
		{
			aplExtent prots, wos;

			if(0!=m_pdf) wos.Add(m_pdf);
			else wos.Add(m_prd);

			CaplInstance* proc_tmpl= m_doc->m_wf_mgr.CreateWfProcess(_T(""), _T(""), _T(""), 
				NULL, m_doc->m_api.m_appr_mgr.GetCurrentPerson(), 
				NULL, _T(""), _T(""), _T(""), prots, wos);

			if(proc_tmpl) m_doc->m_wf_mgr.RunWfProcess(proc_tmpl);
		}
		break;
	
	default: PrepareContextMenu(res); break;
	}
	return true;
}
//****************************************************************
void CaplProductTreeItem::ShowCmd(long cmd)
{
	switch (cmd)
	{
		case ID_SHOW_ALL_BP: ShowAllBPs(true); break;
		case ID_CREATE_BP:
			if(m_pdf!=0)CreateBP(m_pdf);
			else CreateBP(m_prd);
			break;
		case ID_SHOW_ALL_LOT: ShowAllLot(); break;
		case ID_SHOW_ALL_PRD_INST: ShowAllPrdInst(); break;
		case ID_PRODUCT_SHOW_ALL_ZAGOTOV: ShowAllZagotov(); break;
		case ID_CREATE_CHARACTERISTIC: CreateCharacteristic(); break;
		case ID_CREATE_PRODUCT:
			if(m_pdf!=0) CreateSubPart(); else CreateProductVersion(); break;
		case ID_SHOW_ALL_CONTENTS:  Expand(2); MyExpand(); break;
		case ID_EXPAND_ALL: {int i=1; ExpandAll(i);} break;
		case ID_CREATE_BP_INST: CreateBPInst();	break;
		case ID_SHOW_ALL_BP_INST: ShowAllBPInst(true);	break;
		case ID_SHOW_ALL_SUBSTITUTES: ShowAllSubstitutes();	break;
			
		default: PrepareContextMenu(cmd);break;
	}
}
BOOL CaplProductTreeItem::ShowToolBarButton(CCmdUI* pCmdUI)
{
//---------------------------------Состояния-----------------------------------
	aplExtent instances;
	GetAccessedInstances(instances);

	if(pCmdUI->m_nID==ID_SET_INST_ACCSESS)
	{
		if(instances.GetSize()>0)
		{
			if(instances[0]->GetAccessmode()==aplOWN) return TRUE;
		}
		return FALSE;
	}

	if(m_doc->m_api.m_prd_mgr.bNoCreateAndChangePDF)
	{
		if(pCmdUI->m_nID==ID_CREATE_PRODUCT || pCmdUI->m_nID==ID_PRODUCT_CREATE_VERSION )
		{
			return FALSE;
		}
	}

	if(instances.GetSize()==0) return FALSE;
	if(instances[0]==0) return FALSE;
	if(instances[0]->GetType()==0) return FALSE;	

	if(m_doc->m_api.m_data.IsKindOf(instances[0],m_doc->m_api.m_prd_mgr.e_pdf))
	{
		CaplInstance *m_inst = instances[0];
		CStringArray states;
		CString val = m_doc->m_api.m_doc_mgr.GetPossibleWFState(m_inst,states);
			if(val==_T("approving"))
			{
				//if(pCmdUI->m_nID==ID_CREATE_DOC) return FALSE;
				//if(pCmdUI->m_nID==ID_CREATE_CHARACTERISTIC) return FALSE;
				//if(pCmdUI->m_nID==ID_CREATE_CHARACTERISTIC_GROUP) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_PRODUCT) return FALSE;
				//if(pCmdUI->m_nID==ID_PRODUCT_CREATE_VERSION) return FALSE;
			}
			else if(val==_T("approved"))
			{
				//if(pCmdUI->m_nID==ID_CREATE_APPROVAL) return FALSE;
				//if(pCmdUI->m_nID==ID_CREATE_DOC) return FALSE;
				//if(pCmdUI->m_nID==ID_CREATE_CHARACTERISTIC) return FALSE;
				//if(pCmdUI->m_nID==ID_CREATE_CHARACTERISTIC_GROUP) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_PRODUCT) return FALSE;
			}
			else if(val==_T("canceled"))
			{
				if(pCmdUI->m_nID==ID_CREATE_APPROVAL) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_DOC) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_CHARACTERISTIC) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_CHARACTERISTIC_GROUP) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_BP) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_PRODUCT) return FALSE;
				if(pCmdUI->m_nID==ID_PRODUCT_CREATE_VERSION) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_BP_INST) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_LOT) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_PRD_INST) return FALSE;
			}
			else if(val==_T("approving_change"))
			{
				//if(pCmdUI->m_nID==ID_CREATE_DOC) return FALSE;
				//if(pCmdUI->m_nID==ID_CREATE_CHARACTERISTIC) return FALSE;
				//if(pCmdUI->m_nID==ID_CREATE_CHARACTERISTIC_GROUP) return FALSE;
				if(pCmdUI->m_nID==ID_CREATE_PRODUCT) return FALSE;
			}
	}
//---------------------------------Состояния-----------------------------------
	switch(pCmdUI->m_nID)
	{
	case ID_SHOW_ALL_BP:
	case ID_CREATE_BP:
	case ID_SHOW_ALL_DOCS:
	case ID_SHOW_ALL_CHARACTERISTIC:
	case ID_SHOW_ALL_APPROVAL:
	case ID_CREATE_APPROVAL:
	case ID_SHOW_ALL_VERSION:
	case ID_CREATE_PRODUCT:
	case ID_CREATE_CHARACTERISTIC:
	case ID_CREATE_DOC:
	case ID_CREATE_BP_INST:
	case ID_SHOW_ALL_BP_INST:
	case ID_SHOW_NOTES:
	case ID_CREATE_NOTE:
		pCmdUI->Enable(TRUE); return TRUE; break;

	case ID_PRODUCT_SHOW_ALL_ZAGOTOV:
	case ID_SHOW_ALL_LOT:
	case ID_SHOW_ALL_PRD_INST:
		if(m_pdf!=NULL) {pCmdUI->Enable(TRUE); return TRUE; break;}
		else {pCmdUI->Enable(FALSE); return FALSE; break;}
	}
	return FALSE;
}
//****************************************************************
/*void CaplProductTreeItem::ShowToolBarButton(CToolBarCtrl *tb)
{
	if(tb==0) return;
	tb->SetState(ID_SHOW_ALL_DOCS,TBSTATE_ENABLED);
	tb->SetState(ID_SHOW_ALL_CHARACTERISTIC,TBSTATE_ENABLED);
	tb->SetState(ID_SHOW_ALL_APPROVAL,TBSTATE_ENABLED);
	tb->SetState(ID_PRODUCT_SHOW_ALL_ZAGOTOV,TBSTATE_ENABLED);
	tb->SetState(ID_SHOW_ALL_LOT,TBSTATE_ENABLED);
	tb->SetState(ID_SHOW_ALL_PRD_INST,TBSTATE_ENABLED);
	tb->SetState(ID_CREATE_APPROVAL,TBSTATE_ENABLED);
	tb->SetState(ID_SHOW_ALL_VERSION,TBSTATE_ENABLED);
	if(m_pdf!=0) tb->SetState(ID_CREATE_PRODUCT,TBSTATE_ENABLED);
	tb->SetState(ID_CREATE_CHARACTERISTIC,TBSTATE_ENABLED);
	tb->SetState(ID_CREATE_DOC,TBSTATE_ENABLED);*/

/*	tb->EnableButton(ID_SHOW_ALL_DOCS,TRUE);
	tb->EnableButton(ID_SHOW_ALL_CHARACTERISTIC,TRUE);
	tb->EnableButton(ID_SHOW_ALL_APPROVAL,TRUE);
	tb->EnableButton(ID_PRODUCT_SHOW_ALL_ZAGOTOV,TRUE);
	tb->EnableButton(ID_SHOW_ALL_LOT,TRUE);
	tb->EnableButton(ID_SHOW_ALL_PRD_INST,TRUE);
	tb->EnableButton(ID_CREATE_APPROVAL,TRUE);
	tb->EnableButton(ID_CREATE_PRODUCT,TRUE);
	tb->EnableButton(ID_CREATE_CHARACTERISTIC,TRUE);
	tb->EnableButton(ID_CREATE_DOC,TRUE);*/
//}
//****************************************************************
bool CaplProductTreeItem::GetName(CString &name)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	name=_T("");
	CString buf;
	if(m_pdf!=0)
	{
		CHECK_GET_NAME(m_pdf);
		m_doc->m_api.GetItemName(m_pdf,name);
	}
	else
	{
		CHECK_GET_NAME(m_prd);
		m_doc->m_api.GetItemName(m_prd,name);
	}

	if(0!=m_alt)
	{
		bool bIsAlt=false;
		if(m_doc_data.IsKindOf(m_alt,m_doc->m_api.m_prd_mgr.e_alt)) // старый вариант
		{
			CaplInstance *prd=0;
			m_doc_data.GetAttr(m_alt,m_doc->m_api.m_prd_mgr.a_alt_alt,prd);
			if(prd==m_prd) bIsAlt=true;
		}
		else if(m_doc_data.IsKindOf(m_alt,m_doc->m_api.m_prd_mgr.e_alt_pdf)) // новый вариант
		{
			CaplInstance *pdf=0;
			m_doc_data.GetAttr(m_alt,m_doc->m_api.m_prd_mgr.a_alt_pdf_alt,pdf);
			if(pdf==m_pdf) bIsAlt=true;
		}
		if(bIsAlt) name.Insert(0,APL_T("Заменяется на:  ")); else  name.Insert(0,APL_T("Заменяет:  "));
	}

	return true;
}
//****************************************************************
bool CaplProductTreeItem::CreateTreeItem(HTREEITEM parent_item)
{
	_APL_TREE_ITEM_CHEK_PARAM
	CString buf;
	GetName(buf);
	InsetItem(buf,ICON_PART,parent_item);
	m_fictive_item=m_tree->InsertItem(_T("fictive"),0,0,m_item);
	return 	RefreshItem();
}

//****************************************************************
void CaplProductTreeItem::GetAccessedInstances(aplExtent &ext)
{
	ext.Clear();
	if(m_pdf!=0) {if(m_pdf->GetType()!=0)ext.Add(m_pdf);return;}
	if(m_prd!=0) {if(m_prd->GetType()!=0)ext.Add(m_prd);}
}
//****************************************************************
void CaplProductTreeItem::GetMainInstances(aplExtent &ext)
{
	ext.Clear();
	if(m_pdf!=0) {if(m_pdf->GetType()!=0)ext.Add(m_pdf);}
	if(m_prd!=0) {if(m_prd->GetType()!=0)ext.Add(m_prd);}
	if(m_nauo!=0) {if(m_nauo->GetType()!=0)ext.Add(m_nauo);}
}
//****************************************************************
bool CaplProductTreeItem::Expand(UINT action)
{
	// action = 2 -> развертывание 
	// action = 1 -> свертывание
	_APL_TREE_ITEM_CHEK_PARAM
	if(action==2)
	{
		if(m_expanded) return true;
		if(m_hasSubItem)Expand(1);
		m_expanded=true;
		RefreshItem();
		if(m_fictive_item!=0)
		{
			m_tree->DeleteItem(m_fictive_item);
			m_fictive_item=0;
		}
		if(m_ShowContentsOnExpand)
		{
			UINT state = 0;
			if(m_prd_item_type==S::product)
			{
				state = m_doc->m_auto_expand_items.m_showintree_prd;
				ShowAllVersion(FALSE);
			}
			else
			{
				ShowAllSubProduct();
				state = m_doc->m_auto_expand_items.m_showintree_pdf;
			}
			
			if(state&APL_SHOW_DOC)
				ShowAllDocs(false,false);
			if(state&APL_SHOW_CHARACT)
				ShowAllCharacteristic(false);
			if(state&APL_SHOW_APPROVAL)
				ShowAllApproval(false);
			if(state&APL_SHOW_PRD_INST)
				ShowAllPrdInst();
			if(state&APL_SHOW_BP)
				ShowAllBPs(false);
			if(state&APL_SHOW_BPINST)
				ShowAllBPInst(false);
			if(state&APL_SHOW_LOT)
				ShowAllLot();
			if(state&APL_SHOW_MATERIAL)
				ShowAllZagotov();
			if(state&APL_SHOW_SUBSTITUTE)
				ShowAllSubstitutes();
			if(state&APL_SHOW_REQ)
				ShowAllRequirement();
			if(state&APL_SHOW_CHANGE)
				ShowAllChanges(true);
			if(state&APL_SHOW_REFUSAL)
				ShowAllResusal(false,false);
		}
		Sort();
	}
	else if(action==1)
	{
		CollapseItem();
		m_all_sub_product.Clear();
		m_all_parent.Clear();
		m_all_zagotov.Clear();
		m_all_supplier.Clear();
		m_all_alternate.Clear();
		m_all_lots.Clear();
		m_all_prd_inst.Clear();
		m_all_category.Clear();
		m_all_changes.Clear();
		m_all_req.Clear();
		m_all_parent_bps.Clear();
		m_all_substitutes.RemoveAll();		
	}
	return true;
}
//****************************************************************
bool CaplProductTreeItem::ShowInListCtrl(CListCtrl *list)
{
	if(list==0) return false;
	if(m_doc==0)return false;

	if(m_doc->m_BShowInListCtrl==false) return true;
	//LoadProperties();

	CString buf, buf1;
	int i;
	if(m_prd!=0)
	{
		if(m_prd->GetType()!=0)
		{
			if(m_prd->GetAccessmode()<=aplRO)
			{
				i=list->InsertItem(list->GetItemCount(), APL_T("Обозначение:"));
				m_doc_data.GetAttr(m_prd,m_doc->m_api.m_prd_mgr.a_prd_id,buf);
				list->SetItemText(i,1,buf);

				i=list->InsertItem(list->GetItemCount(), APL_T("Наименование:"));
				m_doc_data.GetAttr(m_prd,m_doc->m_api.m_prd_mgr.a_prd_name,buf);
				list->SetItemText(i,1,buf);

				i=list->InsertItem(list->GetItemCount(), APL_T("Описание:"));
				m_doc_data.GetAttr(m_prd,m_doc->m_api.m_prd_mgr.a_prd_descr,buf);
				list->SetItemText(i,1,buf);
			}
		}
	}

	if(m_pdf!=0)
	{
		if(m_pdf->GetType()!=0)
		{
			if(m_pdf->GetAccessmode()<=aplRO)
			{
				i=list->InsertItem(list->GetItemCount(), APL_T("Версия:"));
				m_doc_data.GetAttr(m_pdf,m_doc->m_api.m_prd_mgr.a_pdf_id,buf);
				list->SetItemText(i,1,buf);

				i=list->InsertItem(list->GetItemCount(), APL_T("Описание версии:"));
				m_doc_data.GetAttr(m_pdf,m_doc->m_api.m_prd_mgr.a_pdf_descr,buf);
				list->SetItemText(i,1,buf);

				CaplInstance* par_pdf= NULL;
				CaplInstance* par_prd= NULL;
				m_doc->m_api.m_data.GetAttr(m_pdf, m_doc->m_api.m_prd_mgr.a_apl_pdf_parent, par_pdf);
				if(par_pdf)
				{
					if(par_pdf->GetType()!=0)
					{
						if(par_pdf->GetAccessmode()<=aplRO)
						{
							m_doc->m_api.m_prd_mgr.LoadPrdInfo(par_pdf);
							m_doc->m_api.m_data.GetAttr(par_pdf, m_doc->m_api.m_prd_mgr.a_pdf_prd, par_prd);

							list->InsertItem(list->GetItemCount(),_T(""));
							i=list->InsertItem(list->GetItemCount(),APL_T("Родительское изделие:"));
							m_doc_data.GetAttr(par_prd, m_doc->m_api.m_prd_mgr.a_prd_id, buf);
							m_doc_data.GetAttr(par_pdf, m_doc->m_api.m_prd_mgr.a_pdf_id, buf1);
							if(!buf1.IsEmpty())buf= buf+_T("-")+buf1;
							list->SetItemText(i,1,buf);
							i=list->InsertItem(list->GetItemCount(),APL_T("Наименование:"));
							m_doc_data.GetAttr(par_prd, m_doc->m_api.m_prd_mgr.a_prd_name, buf);
							list->SetItemText(i,1,buf);
						}
					}
				}

				list->InsertItem(list->GetItemCount(),_T(""));

/*				i=list->InsertItem(list->GetItemCount(),_T("grpz_id:"));
				m_doc_data.GetAttr(m_pdf, m_doc->m_api.m_prd_mgr.a_apl_pdf_grpz_id, buf);
				list->SetItemText(i,1,buf);

				i=list->InsertItem(list->GetItemCount(),_T("grpz_name:"));
				m_doc_data.GetAttr(m_pdf, m_doc->m_api.m_prd_mgr.a_apl_pdf_grpz_name, buf);
				list->SetItemText(i,1,buf);

				i=list->InsertItem(list->GetItemCount(),_T("grpz_pdf_id:"));
				m_doc_data.GetAttr(m_pdf, m_doc->m_api.m_prd_mgr.a_apl_pdf_grpz_pdf_id, buf);
				list->SetItemText(i,1,buf);*/
			}
		}
	}
	
	if(m_nauo!=0)
	{
		if(m_nauo->GetType()!=0)
		{
			if(m_nauo->GetAccessmode()<=aplRO)
			{
				i=list->InsertItem(list->GetItemCount(), APL_T("Описание связи:"));
				m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_pdr_descr,buf);
				list->SetItemText(i,1,buf);				
			}
		}	

		if(m_rule)
		{
			CString sRule;
			m_doc->m_api.m_data.GetAttr(m_rule, m_doc->m_api.m_prd_mgr.a_rule_cont_rule, sRule);

			HINSTANCE hLibrary= NULL;
			CString (*pGetRule)(CaplAPI *pAPI, LPCTSTR sRule, bool bInit) = NULL;

#ifdef _DEBUG
#ifdef _UNICODE
			hLibrary = AfxLoadLibrary(_T("aplConfiguratorMgr_ud.dll"));
#else
			hLibrary= AfxLoadLibrary(_T("aplConfiguratorMgrd.dll"));
#endif
#else
#ifdef _UNICODE
			hLibrary = AfxLoadLibrary(_T("aplConfiguratorMgr_u.dll"));
#else
			hLibrary= AfxLoadLibrary(_T("aplConfiguratorMgr.dll"));
#endif
#endif
			if(hLibrary)
			{
				(FARPROC&)pGetRule = ::GetProcAddress(hLibrary, "GetNativeRuleStringFromRuleString");
			}

			if(pGetRule)
			{
				i=list->InsertItem(list->GetItemCount(),_T(""));
				i=list->InsertItem(list->GetItemCount(), APL_T("Вариантное правило"));
				i=list->SetItemText(i,1,pGetRule(&m_doc->m_api, sRule, false));
			}
		}
	}

	i=list->InsertItem(list->GetItemCount(),_T(""));
	if(m_pdf)
	{
		if(m_pdf->GetAccessmode()<=aplRO )
		{
			CString state;
			m_doc_data.GetAttr(m_pdf,m_doc->m_api.m_prd_mgr.a_apl_pdf_state,state);
			i=list->InsertItem(list->GetItemCount(), APL_T("Состояние"));
			i=list->SetItemText(i,1,m_doc->m_api.m_doc_mgr.GetWFStateName(state));
			i=list->InsertItem(list->GetItemCount(),_T(""));
		}
	}
	if(m_prd!=0)
	{
		if(m_prd->GetType()!=0)
		{
			i=list->InsertItem(list->GetItemCount(), APL_T("Доступ к изделию:"));
			GetAccessName(m_prd,buf);
			list->SetItemText(i,1,buf);
		}
	}
	if(m_pdf!=0)
	{
		if(m_pdf->GetType()!=0)
		{
			i=list->InsertItem(list->GetItemCount(), APL_T("Доступ к версии:"));
			GetAccessName(m_pdf,buf);
			list->SetItemText(i,1,buf);
		}
	}
	
	if(m_project)
	{
		CaplInstance *prj_item=m_prd;
		if(m_pdf) prj_item=m_pdf;
		CaplInstance *rel=m_doc->m_project_mgr->FindAssociation(m_project,prj_item);
		if(rel) 
		{
			CaplInstance *control_status=0;
			m_doc_data.GetAttr(rel,m_doc->m_project_mgr->a_project_ref_control_status,control_status);
			buf= APL_T("Рабочий объект");
			if(control_status) buf= APL_T("Контрольный объект");
			list->InsertItem(list->GetItemCount(),_T(""));
			i=list->InsertItem(list->GetItemCount(), APL_T("Тип объекта:"));
			list->SetItemText(i,1,buf);
			if(control_status) 
			{
				i=list->InsertItem(list->GetItemCount(), APL_T("Контрольный статус:"));
				m_doc_data.GetAttr(control_status,m_doc->m_api.m_appr_mgr.a_appr_status_name,buf);
				list->SetItemText(i,1,buf);
			}
		}
	}

	aplExtent ext;
	CStringArray  comment;
	
	if(m_prd!=0){
		comment.Add( APL_T("m_prd (Изделие)"));
		ext.Add(m_prd);
	}
	if(m_pdf!=0){
		comment.Add( APL_T("m_pdf (Версия изделия)"));
		ext.Add(m_pdf);
	}
	if(m_nauo!=0){
		comment.Add( APL_T("m_nauo  (Связь вхождения в сборку)"));
		ext.Add(m_nauo);
	}
	if(m_folder!=0){
		comment.Add( APL_T("m_folder (Папка)"));
		ext.Add(m_folder);
	}
	if(m_alt!=0){
		comment.Add( APL_T("m_alt (Заменяемость)"));
		ext.Add(m_alt);
	}
	if(m_subst!=0){
		comment.Add( APL_T("m_subst (Заменяемость)"));
		ext.Add(m_subst);
	}
	if(m_classifier!=0){
		CaplInstance* classif_ref;
		m_doc->m_api.m_classifier_mgr.TestClassifierAssociation(m_pdf,m_classifier,&classif_ref);
		if(classif_ref==0){
			m_doc->m_api.m_classifier_mgr.TestClassifierAssociation(m_prd,m_classifier,&classif_ref);
		}
		if(classif_ref!=0){
			comment.Add(_T("classifier association"));
			ext.Add(classif_ref);
		}
		comment.Add(_T("m_classifier"));
		ext.Add(m_classifier);
	}
	
	for(i=0;i<m_all_changes.Size;i++)
	{
		buf.Format(_T("m_all_changes[%i]"),i);
		comment.Add(buf);
		ext.Add(m_all_changes[i]);
	}
	
	CString snEffComment, snStart, snEnd;
	for(i=0;i<m_all_eff.Size;i++)
	{
		if(m_doc->m_api.m_data.IsKindOf(m_all_eff[i], m_doc->m_api.m_prd_mgr.e_sn_eff))
		{
			m_doc->m_api.m_data.GetAttr(m_all_eff[i], m_doc->m_api.m_prd_mgr.a_sn_eff_start, snStart);
			m_doc->m_api.m_data.GetAttr(m_all_eff[i], m_doc->m_api.m_prd_mgr.a_sn_eff_end, snEnd);

			if(snEffComment.IsEmpty() == false) snEffComment += _T(" ; ");
			if(snStart.IsEmpty() == false) snEffComment += (APL_T("с ") + snStart);
			if(snEnd.IsEmpty() == false) snEffComment += (APL_T(" по ") + snEnd);
		}

		buf.Format(_T("m_all_eff[%i]"),i);
		comment.Add(buf);
		ext.Add(m_all_eff[i]);
	}

	if(snEffComment.IsEmpty() == false)
	{
		i=list->InsertItem(list->GetItemCount(),_T(""));
		i=list->InsertItem(list->GetItemCount(), APL_T("Ограничение по серии"));
		i=list->SetItemText(i,1,snEffComment);		
	}
	
	ShowInstanceInfoInListCtrl(ext,list,&comment);

	return true;

}
bool CaplProductTreeItem::RefreshAllThisPrdItem()
{
	int i;
	for(i=0;i<m_doc->m_items.Size;i++)
	{
		if(m_doc->m_items[i]!=this)
		{
			if(m_doc->m_items[i]->m_type==APL_TREE_ITEM_PRODUCT)
			{
				CaplProductTreeItem *item=(CaplProductTreeItem*)m_doc->m_items[i];
				if(item->m_prd==m_prd) item->RefreshItem();
			}
		}
	}
	RefreshItem();
	return true;
}
//****************************************************************
bool CaplProductTreeItem::RefreshItem()
{
	if(m_doc==0)return false;
	if(m_prd==0 && m_pdf==0)return false;
	if(m_prd)
		if(m_prd->GetType()==0)return false;
//	if(m_prd->GetAccessmode()>aplRO) return false;

	color=0;
	
	font_style&=~APL_FONT_STRIKEOUT;

	if(m_pdf!=0)
	{
		if(m_pdf->GetType()==0)return false;
//		if(m_pdf->GetAccessmode()>aplRO) return false;
	}

	// Определение иконки
	// Комбинированные иконки
	int ItemIco = -1;
	if(m_prd_item_type==S::product)
	{
		if(m_alt!=0) 
			SetItemImage(ICO_REL_ALTERNATE,IDX_IL_TREE_REL_TYPE,false);
		ItemIco = m_doc->m_api.GetInstIco(m_prd);
	}
	else
	{
		ItemIco = m_doc->m_api.GetInstIco(m_pdf);
		
		int ico_rel=-1;
		// Тип связи
		if(m_prd_item_type==_T("version"))ico_rel=ICO_REL_VER;
		else if(m_prd_item_type==S::alternate)ico_rel=ICO_REL_ALTERNATE;
		else if(m_prd_item_type==_T("supplier_id"))ico_rel=ICO_REL_SUPLIED;
		else if(m_prd_item_type==_T("parent"))ico_rel=ICO_REL_WHERE_USED;
		else if(m_prd_item_type==_T("zagotov"))ico_rel=ICO_REL_MAKE;
		else if(m_prd_item_type==_T("mater"))ico_rel=ICO_REL_MATER;
		else if(m_prd_item_type==_T("dependent"))ico_rel=ICO_REL_DEPEND;
		//else if(m_prd_item_type==_T("substitute"))ico_rel=ICO_REL_ALTERNATE;
		
		SetItemImage(ico_rel,IDX_IL_TREE_REL_TYPE,false);

		if(m_alt!=0) 
			SetItemImage(ICO_REL_ALTERNATE,IDX_IL_TREE_REL_TYPE,false);

		
		//int ico_eff=-1;
		int ico_eff=ICO_EFF_NO;
		if(m_prd_item_type==_T("version")) ico_eff=-1;
		else if(m_nauo!=0)
		{
			// Определение контекстов
			CaplAggr aggr0;
			m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_pdr_frames_of_reference,aggr0);
			if(aggr0.GetSize()>0) ico_eff=ICO_EFF_CON;
			
			
			// Определение наличия применяемости
			aplExtent ext2;
			CaplInstance *inst0;
			bool bHide= false;
			
			m_doc_data.GetEntityExtent(m_doc->m_api.m_prd_mgr.e_pd_eff, ext2);
			bool bFictiveSnEff= false;
			bool bFictiveDateEff= false;
			bool bHasActiveEff= false;
			bool bHasActiveSNEff= false;
			bool bHasActiveDateEff= true;
			CString sStr, sEnd, sCurTime;
			m_all_eff.Clear();
			
			enum EBoolState { Undefined, TrueState, FalseState } bErrorByDateEffectivity = Undefined, bErrorBySnEffectivity = Undefined;
			
			COleDateTime odt=COleDateTime::GetCurrentTime();;
			aplDate2String(odt, sCurTime);

			bool bSomeRuleExist = false;
			bool bEmptyEndSn = false;

			for(int j=0;j<ext2.Size; j++)
			{
				m_doc_data.GetAttr(ext2[j], m_doc->m_api.m_prd_mgr.a_pde_usage, inst0);
				m_doc_data.GetAttr(ext2[j], m_doc->m_api.m_prd_mgr.a_pde_not_active, bHide);				

				if(bHide && sStr!=_T("fictive")) continue;
				if(inst0==m_nauo)
				{	

					if(inst0->GetId() == 12974137)
						int h = 0;

					bSomeRuleExist = true;

					/*какое-то правило есть*/
					if(!bHasActiveEff)
					{
						bHasActiveEff= false;
						bHasActiveSNEff= false;
						bHasActiveDateEff= false;
					}

					m_all_eff.Add(ext2[j]);
										
					if(m_doc_data.IsKindOf(ext2[j], m_doc->m_api.m_prd_mgr.e_dat_eff))
					{						
						m_doc_data.GetAttr(ext2[j], m_doc->m_api.m_prd_mgr.a_dat_eff_start_s, sStr);
						m_doc_data.GetAttr(ext2[j], m_doc->m_api.m_prd_mgr.a_dat_eff_end_s, sEnd);
						if(sStr==_T("19000101000000") && sEnd==_T("19010101000000")) 
						{
							bFictiveDateEff= true;//фиктивное правило по дате
						}
						else
						{
							if((sStr.IsEmpty()||sStr<sCurTime) && (sEnd.IsEmpty()||sEnd>sCurTime))
							{
								bHasActiveEff= true;//попало в текущую дату	
								bErrorByDateEffectivity = FalseState;
							}
							else
							{								
								if(bErrorByDateEffectivity != FalseState)
									bErrorByDateEffectivity = TrueState;
							}
						}
					}
					else if(m_doc_data.IsKindOf(ext2[j], m_doc->m_api.m_prd_mgr.e_sn_eff))
					{
						bHasActiveSNEff= false;
						m_doc_data.GetAttr(ext2[j], m_doc->m_api.m_prd_mgr.a_sn_eff_start, sStr);
						m_doc_data.GetAttr(ext2[j], m_doc->m_api.m_prd_mgr.a_sn_eff_end, sEnd);
						if((!sStr.IsEmpty() || sStr==_T(" ")) && (!sEnd.IsEmpty() || sEnd==_T(" ")))
						{
							bFictiveSnEff= true;//фиктивное правило по серии
						}
						else if(sStr.IsEmpty() && sEnd.IsEmpty())
						{
							bFictiveSnEff= true;//фиктивное правило по серии
						}
						else
						{
							// Акуленко. Раньше было true. Но по-моему все-таки false =))
							bHasActiveEff = false;

							if(sEnd.IsEmpty() == false)
							{
								bErrorBySnEffectivity = TrueState;
							}
							else
							{
								bEmptyEndSn = true;								
							}
						}
					}
				}
			}

			// если был серийный номер с пустым "по", то считаем, что по такому правилу проходит
			if(bEmptyEndSn)
			{
				bErrorByDateEffectivity = FalseState;
				bErrorBySnEffectivity = FalseState;

				if(m_nauo->GetId() == 12974137)
					int h = 0;
			}

			if(bSomeRuleExist)
			{
				ico_eff++;
				if(!bHasActiveEff)
				{
					if(bErrorByDateEffectivity == TrueState || bErrorBySnEffectivity == TrueState)
					{
						color=RGB(128,128,128);
						font_style|=APL_FONT_STRIKEOUT;
					}
					else
					// если фиктивное правило одно, а по дате правил нет
					if((bFictiveSnEff || bFictiveDateEff) && bErrorByDateEffectivity == Undefined && bErrorBySnEffectivity == Undefined )
					{
						color=RGB(128,128,128);
						font_style|=APL_FONT_STRIKEOUT;
					}
				}
			}

			/*Отрисовка вариантных правил*/
			aplExtent rul_ext;
			CaplAttrValue find_val[2];
			find_val[0].attr= m_doc->m_api.m_prd_mgr.a_rule_rels_item;
			find_val[0].value.Set(m_nauo);

			m_doc->m_api.m_data.FindInstancesWithAttrValuesInLocalCache(m_doc->m_api.m_prd_mgr.e_rule_rels, NULL, 1, &find_val[0], rul_ext, false, false, false);
			
			if(rul_ext.GetSize())
				m_doc->m_api.m_data.GetAttr(rul_ext[0], m_doc->m_api.m_prd_mgr.a_rule_rels_rule, m_rule);

			if(m_rule)
			{
				CString ruleContainer;
				m_doc->m_api.m_data.GetAttr(m_rule, m_doc->m_api.m_prd_mgr.a_rule_cont_rule, ruleContainer);

				if(ruleContainer.IsEmpty() == false)
					ico_eff+=15;/*Определение иконки для отрисовки вариантного правила*/
			}
		}

		SetItemImage(ico_eff,IDX_IL_TREE_EFF,false);
/*
	#define ICO_EFF_EFF		1
	#define ICO_EFF_CON		2
	#define ICO_EFF_EFFCON	3
*/
	}
	SetItemImage(ItemIco,IDX_IL_TREE_ITEM,false);

	if(m_bWOForNote)
		SetItemImage(ICO_REL_WO_4NOTE, IDX_IL_TREE_REL_TYPE);

	if(m_pdf!=0 && m_pdf->GetAccessmode()<aplNO)
	{
		CString state;
		int state_ico=-1;
		m_doc_data.GetAttr(m_pdf, m_doc->m_api.m_prd_mgr.a_apl_pdf_state, state);

		SetItemImage(aplState2Ico(state,-1), IDX_IL_TREE_STATE);
	}


	// Определение текста
	if(m_tree!=0)
	{
		CString name,buf,buf1;
		GetName(name);
		if(m_doc->m_api.m_show.m_prd_position==TRUE)
		{
			if(m_nauo!=0)
			{
				m_doc_data.GetAttrBN(m_nauo,S::id,buf);
				buf1.Format(_T("(%3s) "),LPCTSTR(buf));
				buf1+=name;
				name=buf1;
			}
			else if(m_subst)
			{

				m_doc_data.GetAttr(m_subst,m_doc->m_api.m_prd_mgr.a_pdf_subst_id,buf);
				buf1.Format(_T("(%2s) "),LPCTSTR(buf));
				buf1+=name;
				name=buf1;
			}
		}
		if(m_doc->m_api.m_show.m_prd_count==TRUE)
		{
			CaplInstance *inst1;
			double count;
			if(m_nauo!=0)
			{
				if(m_doc_data.IsKindOf(m_nauo,m_doc->m_api.m_prd_mgr.e_apl_qacu))
				{
					m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_apl_qacu_value,count);
					m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_apl_qacu_unit,inst1);
					m_doc->m_api.m_charact_mgr.GetUnitName(inst1,buf);
					buf1 = _T(" [")+Double2Str(count)+_T(" ")+buf+_T("]");
//					buf1.Format(_T(" [%g %s]"),count,buf);
					name+=buf1;
				}
				else if(m_doc_data.IsKindOf(m_nauo,m_doc->m_api.m_prd_mgr.e_make_from))
				{
					int ranking=0;
					m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_make_from_ranking,ranking);
					m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_make_from_value,count);
					m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_make_from_unit,inst1);
					m_doc->m_api.m_charact_mgr.GetUnitName(inst1,buf);
//					buf1.Format(_T(" :%i[%g %s]"),ranking,count,buf);
					buf1.Format(_T(" :%i["),ranking);
					buf1+=Double2Str(count)+ _T(" ")+buf+_T("]");
					name+=buf1;
					// отображение сортамента
					m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_make_from_assortment,inst1);
					if(inst1!=0)
					{
						m_doc_data.GetAttr(inst1,m_doc->m_api.m_prd_mgr.a_assortment_name,buf);
						if(buf==_T("")) m_doc_data.GetAttr(inst1,m_doc->m_api.m_prd_mgr.a_assortment_id,buf);
						buf+=_T(" ");
						m_doc_data.GetAttr(inst1,m_doc->m_api.m_prd_mgr.a_assortment_std,buf1);
						buf+=buf1;
						buf1=_T(" {");buf1+=buf;buf1+=_T("}");
						name+=buf1;
					}
				}
				m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_acu_ref_des,buf1);
				if(buf1!=_T("")) {name+=_T(" {"); name+=buf1; name+=_T("}");}

			}
			else if(m_subst)
			{
				m_doc_data.GetAttr(m_subst,m_doc->m_api.m_prd_mgr.a_pdf_subst_value,count);
				m_doc_data.GetAttr(m_subst,m_doc->m_api.m_prd_mgr.a_pdf_subst_unit,inst1);
				m_doc->m_api.m_charact_mgr.GetUnitName(inst1,buf);
				buf1 = _T(" [")+Double2Str(count)+_T(" ")+buf+_T("]");
//				buf1.Format(_T(" [%g %s]"),count,buf);
				name+=buf1;
			}
		}
//		SetItemImage(ItemIco,);
		m_tree->SetItemText(m_item,name);
		
		if(m_doc->m_api.m_show.m_PrdNoShowPlusToPart==FALSE)
		{
			if(m_pdf!=0)
			{
				m_doc_data.GetAttrBN(m_pdf,S::formation_type,buf);
				if((buf!=_T("assembly"))&&(buf!=_T("kit"))&&(buf!=_T("komplex")))
				{
					if(m_fictive_item!=0)
					{
						m_tree->DeleteItem(m_fictive_item);
						m_fictive_item=0;
					}
				}
			}
		}
		Sort();
		m_tree->RedrawWindow();
	}
	if(m_doc->m_tab_view!=0)
	{
		if(m_doc->m_tab_view->m_item_old==this)m_doc->ChangeItem(this);
	}
	return true;
}
//****************************************************************
void CaplProductTreeItem::LoadProperties()
{
	if(m_doc==0) return;
	if(m_prd==0) return;
	
	if(m_pdf!=0) m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_pdf);
	else m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_prd);

	SetStatusString(_T(""));
	m_PropertiesLoaded=true;
}
void CaplProductTreeItem::ShowProperties()
{
	if(m_doc==0) return;
	if(m_prd==0) return;
	LoadProperties();
	CString old_subst_name,old_subst_descr,subst_name,subst_descr;
	if(m_subst)
	{
		m_doc_data.GetAttr(m_subst,m_doc->m_api.m_prd_mgr.a_pdf_subst_name,old_subst_name);
		m_doc_data.GetAttr(m_subst,m_doc->m_api.m_prd_mgr.a_pdf_subst_description,old_subst_descr);
	}
	if(m_doc->m_api.m_prd_mgr.ShowProperties(m_pdf!=NULL?m_pdf:m_prd, aplModeEdit, m_nauo, m_subst))
	{
		RefreshAllThisPrdItem();
		if(m_subst)
		{
			m_doc_data.GetAttr(m_subst,m_doc->m_api.m_prd_mgr.a_pdf_subst_name,subst_name);
			m_doc_data.GetAttr(m_subst,m_doc->m_api.m_prd_mgr.a_pdf_subst_description,subst_descr);
			if(subst_name!=old_subst_name) //нужно обновлять группу заменяющих
			{
				CaplSubstTreeItem *sitem=(CaplSubstTreeItem*)GetParentItem(this);
				CaplProductTreeItem *pitem=0;
				if(sitem) pitem=(CaplProductTreeItem*)GetParentItem(sitem);
				RemoveSubst();
				if(pitem) pitem->InsertSubstItem(m_subst);
				m_doc->m_items.Remove(m_doc->m_items.Find(this));
			}
			else if(old_subst_descr!=subst_descr)
			{
				CaplSubstTreeItem *sitem=(CaplSubstTreeItem*)GetParentItem(this);
				if(sitem) sitem->RefreshItem();
			}
		}
	}
}
//****************************************************************
void CaplProductTreeItem::CreateProductVersion()
{
	if(m_doc->m_api.m_prd_mgr.bNoCreateAndChangePDF)
	{
		AfxMessageBox(IDS_NO_CREATE_PDF,MB_OK|MB_ICONSTOP);
		return;
	}

	_APL_TREE_ITEM_CHEK_PARAM1
	if(m_doc==0) return;	
	if(m_prd==0) return;
	if(0!=m_pdf) m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_pdf);
	else m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_prd);
	
	if(m_prd->GetType()==0)
	{
		AfxMessageBox( APL_T("Изделие удалено другим пользователем"),MB_OK|MB_ICONSTOP);
		for(int i=0;i<m_doc->m_items.Size;i++)
		{
			if(m_doc->m_items[i]!=this)
			{
				if(m_doc->m_items[i]->m_type==APL_TREE_ITEM_PRODUCT)
				{
					CaplProductTreeItem *item=(CaplProductTreeItem*)m_doc->m_items[i];
					if(item->m_prd==m_prd) 
					{
						m_doc->m_items.Remove(i); i--;
					}
				}
			}
		}
		m_doc->m_items.Remove(m_doc->m_items.Find(this));	
		return;
	}
	if(m_prd->GetAccessmode()>aplRW)	{AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}
	
	
	CString buf;
	CaplInstance* tmp_pdf;
	if(m_pdf==0) tmp_pdf= m_doc->m_api.m_prd_mgr.CreateProduct(m_prd, aplModeCreateVersion);
	else tmp_pdf= m_doc->m_api.m_prd_mgr.CreateProduct(m_pdf, aplModeCreateVersion);
	if(0!=tmp_pdf)
	{
		if(m_pdf!=0)
			CopyRelations(m_pdf, tmp_pdf, true);
		
	
		CaplProductTreeItem *product_item=
			new CaplProductTreeItem(m_tree, m_doc, m_prd, tmp_pdf);
		product_item->m_prd_item_type=_T("version");
		product_item->CreateTreeItem(m_item);
		m_all_version.Add(tmp_pdf);
		product_item->RefreshItem();
		m_doc_data.NET_SaveChanges();
		MyExpand();
		m_doc->ChangeItem(0);m_doc->ChangeItem(this);
	}
}
//****************************************************************
void CaplProductTreeItem::ShowAllVersion(bool showMsg)
{
	if(m_prd==0) return;
	_APL_TREE_ITEM_CHEK_PARAM1
	aplExtent ext0;
	int i;
	if(m_prd->GetAccessmode()>aplRO) return;

	StartBusy();
	// чтение из базы
	SetStatusString( APL_T("Чтение из базы"));
	m_doc->m_api.m_prd_mgr.GetAllProductVersion(m_prd,ext0);
	SetStatusString(_T(""));
	StopBusy();
	if(ext0.Size<=0) {if(showMsg)AfxMessageBox( APL_T("Нет версий !")); return;}
	else if(ext0.Size==1)
	{
		if(m_pdf!=0 && showMsg){ AfxMessageBox( APL_T("Эта версия единственная !")); return;}
	}
	// отображение версий
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	
	for(i=0;i<ext0.Size;i++)
	{
		bool flag=true;
		for(int j=0;j<m_all_version.Size;j++)
		{
			if(m_all_version[j]==ext0[i])
			{
				flag=false;
				break;
			}
		}
		if(flag)
		{
			CaplProductTreeItem *product_item=
				new CaplProductTreeItem(m_tree,m_doc,m_prd,ext0[i]);
			product_item->m_prd_item_type=_T("version");
			product_item->CreateTreeItem(m_item);
			m_all_version.Add(ext0[i]);
			product_item->RefreshItem();
		}
	}
	if(m_ExecMyExpand)
		MyExpand(false);

	StopBusy();
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}
//****************************************************************
void CaplProductTreeItem::ShowRecurseFind()
{
	if(m_prd==0) return;
	if(m_pdf==0) return;
	if(m_tree==0)return;

	m_dlg.SetTreeItem(this, m_pdf);	
}

void CaplProductTreeItem::ShowAllSubProduct()
{
	// Чтение всех входящих
	if(m_prd==0) return;
	if(m_pdf==0) return;
	if(m_tree==0)return;

	aplExtent ext0,ext1;
	int i;
	SetStatusString( APL_T("Чтение из базы"));
	StartBusy();
	m_doc->m_api.m_prd_mgr.LoadAllSubProduct(0,m_doc->m_cur_context,m_pdf,ext0, ext1);
	SetStatusString(_T(""));
	if(m_bShowNoFoundMessage) 
		m_tree->SetRedraw(FALSE);

	// если задана конфигурация, то отфильтруем по ней
	aplExtent filteredRelations;
	CaplInstance *pConfiguration = m_doc->GetCurrentConfiguration();
	if(pConfiguration)
	{
		long dID = aplStartWaitDlg(APL_T("Фильтр по конфигурации..."));

		{
			bool (*funcFilterByComplectation)(CaplAPI*, aplExtent&, CaplInstance*, aplExtent&, bool, CaplInstance*) = NULL;
			if(m_doc->m_hConfigMgrLib != NULL)
			{
				(FARPROC&)funcFilterByComplectation = ::GetProcAddress(m_doc->m_hConfigMgrLib, "add_FilterByComplectation");
				if(funcFilterByComplectation)
					funcFilterByComplectation(&m_doc->m_api, ext0, pConfiguration, filteredRelations, true, NULL);
			}			
		}		

		aplEndWaitDlg(dID);
	}
	//////////////////////////////////////////////////////////////////////////
	
	for(i=0;i<ext0.Size;i++)
	{
		CaplInstance *inst1;
		m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_pdr_r_ted,inst1);
		if(inst1!=0)
		{
			if(inst1->GetType()!=0)
			{
				if(m_all_sub_product.Find(ext0[i])==-1)
				{
					//not_found=false;
					CaplProductTreeItem *product_item=
						new CaplProductTreeItem(m_tree,m_doc,0,inst1);
					product_item->m_nauo=ext0[i];
					product_item->CreateTreeItem(m_item);
					m_all_sub_product.Add(ext0[i]);

					product_item->RefreshItem();

					if( (0!=(product_item->font_style &= APL_FONT_STRIKEOUT))
						&&  m_doc->m_api.m_show.m_PrdNoShowReplacedPart)
					{
						m_doc->m_items.Remove(m_doc->m_items.Find(product_item));
						continue;;
					}

					// если в выбранной конфигурации связи нет, то зачеркиваем и делаем серым
					if(pConfiguration && -1 == filteredRelations.Find(ext0[i]))
					{
						product_item->font_style |= APL_FONT_STRIKEOUT;
						product_item->color = RGB(128, 128, 128);
					}
				}
			}
		}
	}


	if(m_ExecMyExpand)
		MyExpand();
	StopBusy();
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}

//****************************************************************
void CaplProductTreeItem::ShowAllSubstitutes()
{
	// Чтение всех входящих
	if(m_prd==0) return;
	if(m_pdf==0) return;

	if(m_tree==0)return;

	aplExtent ext_rel,ext_pdf;
	int i, j;
	SetStatusString( APL_T("Чтение из базы"));
	StartBusy();
	
	m_doc->m_api.m_prd_mgr.LoadAllSubstitutes(m_nauo, ext_rel, ext_pdf,true);
	SetStatusString(_T(""));
	if(m_bShowNoFoundMessage) 
		m_tree->SetRedraw(FALSE);
	
	for(i=0;i<ext_rel.GetSize();i++)
	{
		CString subst_name,buf;
		m_doc_data.GetAttr(ext_rel[i],m_doc->m_api.m_prd_mgr.a_pdf_subst_name,subst_name);
		bool already_shown=false;
		for(j=0;j<m_all_substitutes.GetSize();j++)
		{
			if(m_all_substitutes[j]->m_subst_name==subst_name) {already_shown=true;break;}
		}
		if(already_shown) continue;

		CaplSubstTreeItem *subst_item=
			new CaplSubstTreeItem(m_tree,m_doc,subst_name);
		subst_item->CreateTreeItem(m_item);
		subst_item->m_pdr=m_nauo;
		m_all_substitutes.Add(subst_item);
		subst_item->m_substitutes.Add(ext_rel[i]);
		for(j=i+1;j<ext_rel.GetSize();j++)
		{
			m_doc_data.GetAttr(ext_rel[j],m_doc->m_api.m_prd_mgr.a_pdf_subst_name,buf);
			if(buf==subst_name) subst_item->m_substitutes.Add(ext_rel[j]);
		}

		subst_item->RefreshItem();
		subst_item->m_bReloadContentOnExpand=false;
		subst_item->Expand(TVE_EXPAND);
		subst_item->m_bReloadContentOnExpand=true;
		m_tree->Expand(subst_item->m_item,TVE_EXPAND);
	}	
	MyExpand(false);
	StopBusy();
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}

//****************************************************************
void CaplProductTreeItem::ShowAllZagotov()
{
	// Чтение всех входящих
	if(m_prd==0) return;
	if(m_pdf==0) return;
	if(m_tree==0)return;

	aplExtent ext_rel,ext0;;
	int i;

	SetStatusString( APL_T("Чтение из базы"));
	StartBusy();
	m_doc->m_api.m_prd_mgr.LoadAllZagotov(m_pdf,ext_rel,ext0,true,true);

	SetStatusString(_T(""));
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	bool not_found=true;
	
	for(i=0;i<ext_rel.Size;i++)
	{
		CaplInstance *inst1;

		m_doc_data.GetAttrBN(ext_rel[i],S::related_pd,inst1);
		if(inst1!=0)
		{
			if(inst1->GetType()!=0)
			{
				if(m_all_zagotov.Find(ext_rel[i])==-1)
				{
					not_found=false;
					CaplProductTreeItem *product_item=
						new CaplProductTreeItem(m_tree,m_doc,0,inst1);
					product_item->m_prd_item_type=_T("zagotov");
					if(m_doc_data.IsKindOf(ext_rel[i],m_doc->m_api.m_prd_mgr.e_design_make_from))
						product_item->m_prd_item_type=_T("mater");
					product_item->m_nauo=ext_rel[i];
					product_item->CreateTreeItem(m_item);
					m_all_zagotov.Add(ext_rel[i]);
					product_item->RefreshItem();
				}
			}
		}
	}
	if(m_ExecMyExpand)
		MyExpand(false);
	StopBusy();
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}
//****************************************************************
void CaplProductTreeItem::ShowAllUsesBP()
{
	int i;
	CaplInstance *inst=m_prd;
	if(m_pdf) inst=m_pdf;

	if(inst==0) return;
	if(inst->GetType()==0) return;
	if(inst->GetAccessmode()>aplRO)	{AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}

	aplExtent ext_bp,ext_bp_inst;
	m_doc->m_api.m_bp_mgr.ItemWhereUsedAsResource(inst,ext_bp,ext_bp_inst);
	m_doc->m_api.m_bp_mgr.LoadBPInfo(ext_bp);
	m_doc->m_api.m_bp_mgr.LoadBPInstInfo(ext_bp_inst);
	for(i=0;i<ext_bp.GetSize();i++)
	{
		if(m_all_parent_bps.Find(ext_bp[i])>=0) continue;
		CaplBPTreeItem *act_item= new CaplBPTreeItem(m_tree,m_doc,ext_bp[i]);
		act_item->m_subitem=inst;
		act_item->CreateTreeItem(m_item);
		act_item->RefreshItem();
		m_all_parent_bps.Add(ext_bp[i]);
	}
	for(i=0;i<ext_bp_inst.GetSize();i++)
	{
		if(m_all_parent_bps.Find(ext_bp_inst[i])>=0) continue;
		CaplBPInstTreeItem *act_item= new CaplBPInstTreeItem(m_tree,m_doc,ext_bp_inst[i]);
		act_item->m_subitem=inst;
		act_item->CreateTreeItem(m_item);
		act_item->RefreshItem();
		m_all_parent_bps.Add(ext_bp_inst[i]);
	}
	if(m_ExecMyExpand)
		MyExpand(false);
}
//****************************************************************
void CaplProductTreeItem::ShowAllParentProduct()
{
	// Чтение всех входящих
	if(m_prd==0) return;
	if(m_pdf==0) return;	
	aplExtent ext_rel,ext0;
	int i;
	CaplInstance *pd=0;

	StartBusy();
	m_doc->m_api.m_prd_mgr.WhereUsedProduct(m_pdf,ext_rel,ext0,true);

	SetStatusString(_T(""));	
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	CaplInstance *inst2,*inst1;
	
	//[Колесников 07.07.2011, по согласованию с Нахимовичем, сделал так, чтобы показывались родительские элементы с применяемостями]
	for(i=0;i<ext_rel.Size;i++)
	{
		m_doc_data.GetAttr(ext_rel[i],m_doc->m_api.m_prd_mgr.a_pdr_r_ting,inst1);
		if(inst1!=0)
		{
			if(inst1->GetType()!=0)
			{
				if(m_all_parent.Find(ext_rel[i])==-1)
				{
					CaplProductTreeItem *product_item=
						new CaplProductTreeItem(m_tree,m_doc,0,inst1);
					product_item->m_nauo=ext_rel[i];
					product_item->m_prd_item_type=_T("parent");
					product_item->CreateTreeItem(m_item);
					m_all_parent.Add(ext_rel[i]);
				}
			}
		}
	}
	//Проекты
	ShowAllProjects(m_pdf,false);
	
	m_doc->m_api.m_prd_mgr.WhereUsedAsSubstitute(m_pdf,ext_rel,ext0,true);

	for(i=0;i<ext_rel.GetSize();i++)
	{
		inst1= NULL;inst2= NULL;

//		CString subst_name,buf;
//		m_doc_data.GetAttr(ext_rel[i],m_doc->m_api.m_prd_mgr.a_pdf_subst_name,subst_name);
//		bool already_shown=false;
//		for(int j=0;j<m_all_substitutes.GetSize();j++)
//		{
//			if(m_all_substitutes[j]->m_subst_name==subst_name) {already_shown=true;break;}
//		}
//		if(already_shown) continue;
//
//		CaplSubstTreeItem *subst_item=
//			new CaplSubstTreeItem(m_tree,m_doc,subst_name);
//		subst_item->CreateTreeItem(m_item);
//		subst_item->m_pdr=m_nauo;
//		m_all_parent.Add(subst_item);
//		subst_item->m_substitutes.Add(ext_rel[i]);
//		for(j=i+1;j<ext_rel.GetSize();j++)
//		{
//			m_doc_data.GetAttr(ext_rel[j],m_doc->m_api.m_prd_mgr.a_pdf_subst_name,buf);
//			if(buf==subst_name) subst_item->m_substitutes.Add(ext_rel[j]);
//		}
//
//		subst_item->RefreshItem();
//		subst_item->m_bReloadContentOnExpand=false;
//		subst_item->Expand(TVE_EXPAND);
//		subst_item->m_bReloadContentOnExpand=true;
//		m_tree->Expand(subst_item->m_item,TVE_EXPAND);
		//[Колесников 07.07.2011, по согласованию с Нахимовичем, сделал так, чтобы показывались родительские элементы с применяемостями]
		m_doc_data.GetAttr(ext_rel[i],m_doc->m_api.m_prd_mgr.a_pdf_subst_pdr,inst2);
		if(inst2)m_doc_data.GetAttr(inst2,m_doc->m_api.m_prd_mgr.a_pdr_r_ted,inst1);

		if(inst1 && m_all_parent.Find(inst2)==-1)
		{
			CaplProductTreeItem *product_item=
				new CaplProductTreeItem(m_tree,m_doc,0,inst1);
			product_item->m_prd_item_type=S::alternate;
			product_item->CreateTreeItem(m_item);
			m_all_parent.Add(inst2);
		}
	}	


	if(m_ExecMyExpand)
		MyExpand(false);

	StopBusy();
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}
//****************************************************************
void CaplProductTreeItem::ShowAllSupplied()
{
	// Чтение всех обозначений
	if(m_prd==0) return;
	if(m_pdf==0) return;	
	aplExtent ext0,ext1;
	int i;

	StartBusy();
	SetStatusString( APL_T("Чтение из базы"));
	m_doc->m_api.m_prd_mgr.LoadSupliedProduct(m_pdf,ext0,ext1);
	SetStatusString(_T(""));

	bool not_found=true;
	for(i=0;i<ext0.Size;i++)
	{
		CaplInstance *inst1;
		m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_pdr_r_ting,inst1);
		if(inst1==m_pdf)
		{
			m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_pdr_r_ted,inst1);
			if(inst1!=0)
			{
				if(m_all_supplier.Find(inst1)==-1)
				{
					not_found=false;
					CaplProductTreeItem *product_item=
						new CaplProductTreeItem(m_tree,m_doc,0,inst1);
						product_item->m_prd_item_type=_T("supplier_id");
					product_item->m_nauo=ext0[i];
					product_item->CreateTreeItem(m_item);
					m_all_supplier.Add(inst1);
					product_item->RefreshItem();
				}
			}
		}
		else
		{
			m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_pdr_r_ted,inst1);
			if(inst1==m_pdf)
			{
				m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_pdr_r_ting,inst1);
				if(inst1!=0)
				{
					if(m_all_supplier.Find(inst1)==-1)
					{
						not_found=false;
						CaplProductTreeItem *product_item=
							new CaplProductTreeItem(m_tree,m_doc,0,inst1);
							product_item->m_prd_item_type=_T("supplier_id");
						product_item->CreateTreeItem(m_item);
						m_all_supplier.Add(inst1);
						product_item->RefreshItem();
					}
				}
			}
		}
	}
	if(not_found && m_bShowNoFoundMessage) AfxMessageBox( APL_T("Новые внешние обозначения не найдены !"));
	if(m_ExecMyExpand)
		MyExpand(false);
	StopBusy();
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}

void CaplProductTreeItem::CopyRelations(CaplInstance* from, CaplInstance* to, bool bAskBeforCopy)
{
	if(!from) return;
	if(!to) return;
	
	StartBusy();	
	
	CaplAPI* m_api= &m_doc->m_api;

	aplExtent ext0,ext_rel, characts, groups, ext_rel_from, ext_rel_to;
	CaplInstance *c_context=0;
	CString c_sn=_T("");
	COleDateTime c_time;
	int i,j;
	
	CaplInstance* rel;
	CaplInstance* inst0;
	CaplInstance* inst1;

	double rVal0;
	double rVal1;
	CString sPos0;
	CString sKey;
	
	CaplMap map;
	CaplStrMap check_map;
	CaplInstance* new_val, *old_item, *new_item;

	m_doc->m_api.m_prd_mgr.LoadAllSubProduct(0,0,from,ext_rel_from,ext0);
	m_doc->m_api.m_prd_mgr.LoadAllSubProduct(0,0,to,ext_rel_to,ext0);

	// или не копировать, что уже есть
	// или сложить количесиво
	// или переписать
	if(ext_rel_to.GetSize())
	{
		for(i= 0; i<ext_rel_to.GetSize(); i++)
		{
			m_api->m_data.GetAttr(ext_rel_to[i], m_api->m_prd_mgr.a_pdr_r_ted, inst0);
			m_api->m_data.GetAttr(ext_rel_to[i], m_api->m_prd_mgr.a_pdr_id, sPos0);

			sKey.Format(_T("%s_%i"), sPos0, inst0->GetId());
			check_map.Add(sKey, (long) ext_rel_to[i]);
		}
		
		check_map.Sort();

		for(i= 0; i<ext_rel_from.GetSize(); i++)
		{
			m_api->m_data.GetAttr(ext_rel_from[i], m_api->m_prd_mgr.a_pdr_r_ted, inst0);
			m_api->m_data.GetAttr(ext_rel_from[i], m_api->m_prd_mgr.a_pdr_id, sPos0);

			sKey.Format(_T("%s_%i"), sPos0, inst0->GetId());
			rel= (CaplInstance*)check_map.GetP(sKey);
			
			if(rel)
			{				
				m_api->m_data.GetAttr(ext_rel_from[i], m_doc->m_api.m_prd_mgr.a_apl_qacu_value, rVal0);
				m_api->m_data.GetAttr(ext_rel_from[i], m_doc->m_api.m_prd_mgr.a_apl_qacu_unit, inst0);
				
				m_api->m_data.GetAttr(rel, m_doc->m_api.m_prd_mgr.a_apl_qacu_value, rVal1);
				m_api->m_data.GetAttr(rel, m_doc->m_api.m_prd_mgr.a_apl_qacu_unit, inst1);

				if(inst0!=inst1)
				{
					m_api->m_data.PutAttr(rel, m_doc->m_api.m_prd_mgr.a_apl_qacu_unit, inst0);	
					m_api->m_data.PutAttr(rel, m_doc->m_api.m_prd_mgr.a_apl_qacu_value, rVal0);
				}
				else //if(rVal0!=rVal1) 
				{
					rVal0+=rVal1;//если убрать комент  if и закомент эту строку не будет складываться кол-во
					m_api->m_data.PutAttr(rel, m_doc->m_api.m_prd_mgr.a_apl_qacu_value, rVal0);
				}
				continue;
			}
			
			ext_rel.Add(ext_rel_from[i]);
		}
	}
	else
		ext_rel.Append(ext_rel_from);

	if(!ext_rel.GetSize())
	{
		StopBusy();
		return;
	}

	if(bAskBeforCopy)
	{
		if(IDNO==AfxMessageBox( APL_T("Скопировать состав ?"), MB_ICONQUESTION|MB_YESNO)){
			StopBusy();
			return;
		}
	}
	/*Фильтрация на дату для КВЗ по умолчанию*/
	CString sVal;
	m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Код установки"), sVal, _T(""));
	if(sVal==_T("KVZ"))
		c_time= COleDateTime::GetCurrentTime();
	else
		c_time.SetStatus(COleDateTime::null);

	if(m_doc->m_api.m_prd_mgr.SelectDateSN(c_sn,c_time,0,&c_context))
	{
		ext0.Clear();
		CString m_time_s=_T("");
		if(c_time.GetStatus()==COleDateTime::valid)//фильтруем состав изделия по дате
		{
			m_doc->m_api.m_prd_mgr.FilterlByDate(ext_rel, c_time, ext0);
			ext_rel.Clear(); 
			for(int i= 0; i<ext0.GetSize(); i++) ext_rel.Add(ext0[i]);
			ext0.Clear();
		}
		if(c_sn!=_T(""))//фильтруем состав изделия по серийному номеру
		{
			m_doc->m_api.m_prd_mgr.FilterlBySN(ext_rel, c_sn, ext0);
			ext_rel.Clear(); 
			for(int i= 0; i<ext0.GetSize(); i++) ext_rel.Add(ext0[i]);
			ext0.Clear();
		}
		if(c_context)
		{
			ext0.Append(ext_rel);
			ext_rel.Clear();
			for(int i=0;i<ext0.GetSize();i++)
			{
				if(m_doc->m_api.m_prd_mgr.IsItemInContext(ext0[i],c_context,m_doc->m_api.m_prd_mgr.a_pdr_frames_of_reference)) ext_rel.Add(ext0[i]);
			}
		}
	}



	m_doc->m_api.m_charact_mgr.FindAssociatedCharacteristic(ext_rel, characts);


	bool bOldMode= m_api->m_ModeInteractive;
	m_api->SetModeInteractive(false);

	bool bOldAutoSave= m_api->m_AutoSave;
	m_api->SetAutoSave(false);

	map.bAutoSort= true;

	CString buf;
	aplExtent ext_rel_subst, ext_rel_subst_pdf;


	// Чтение замен в контексте сборки

	{
		CaplLoadData ld(&m_doc_data,DEF_SOURCE);
		for(i=0;i<ext_rel.Size;i++)
		{
			inst0=ext_rel[i];
			ld.AddQuery(0, inst0);
		}

		int i1=	ld.AddQuery(_T('r'), 0, m_doc->m_api.m_prd_mgr.e_pdf_subst, m_doc->m_api.m_prd_mgr.a_pdf_subst_pdr, true,true);

		if (!ld.LoadEx())
		{
			if(m_doc_data.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
				if(m_api->m_ModeInteractive)AfxMessageBox( APL_T("Ошибка чтения замен в контексте сборки"),MB_OK|MB_ICONSTOP);
			}
		}
	}

	m_doc_data.GetEntityExtent(m_doc->m_api.m_prd_mgr.e_pdf_subst,ext_rel_subst);


	bool bCopySubst=false;

	// Определяем наличие замен в контексте сборки
	for(j=0;j<ext_rel_subst.GetSize();j++)
	{
		CaplInstance *subst_old=ext_rel_subst[j];
		CaplInstance *subst_pdr;
		m_doc_data.GetAttr(subst_old,m_doc->m_api.m_prd_mgr.a_pdf_subst_pdr,subst_pdr);

		for(i=0;i<ext_rel.Size;i++)
		{
			if(ext_rel[i]==subst_pdr) 
			{
				bCopySubst=true;
				break;
			}

		}
		if(bCopySubst) break;
	}

	if(bCopySubst)
	{
		if(IDYES!=AfxMessageBox( APL_T("В сборке, состав которой копируется, есть замены в контексте сборки!\n\nСкопировать их ?"),
			MB_YESNO|MB_ICONQUESTION))
		{
			bCopySubst=false;
		}
	}



	for(i=0;i<ext_rel.Size;i++)
	{
		inst0=ext_rel[i];
		if(inst0->attrs==0)continue;
		if(inst0->GetType()==0)continue;
		inst1=m_doc_data.CreateInstance(inst0->GetType());
		for(j=0;j<inst0->GetType()->all_attrs.GetSize();j++)
		{
			m_doc_data.PutAttr(inst1,inst0->GetType()->all_attrs[j],inst0->attrs[j].value);
		}		
		m_doc_data.PutAttr(inst1,m_doc->m_api.m_prd_mgr.a_pdr_r_ting,to);
		map.Add((long)inst0,(long)inst1);



		// Копирование замен в контексте сборки (уже прочитано)
		if(bCopySubst)
		{
			for(j=0;j<ext_rel_subst.GetSize();j++)
			{
				CaplInstance *subst_old=ext_rel_subst[j];
				CaplInstance *subst_pdr;
				m_doc_data.GetAttr(subst_old,m_doc->m_api.m_prd_mgr.a_pdf_subst_pdr,subst_pdr);
				
				if(subst_pdr!=inst0) continue;
			
				CaplInstance *subst_new=m_doc->m_api.m_data.CreateInstance(subst_old->GetType());

				int j1;
				for(j1=0;j1<subst_old->GetType()->all_attrs.GetSize();j1++)
				{
					m_doc_data.PutAttr(subst_new,subst_old->GetType()->all_attrs[j1],subst_old->attrs[j1].value);
				}		
				m_doc_data.PutAttr(subst_new,m_doc->m_api.m_prd_mgr.a_pdf_subst_pdr,inst1);
			}
		}	
	}



	//map.SortIn();

	for(i= 0; i<characts.GetSize(); i++)
	{
		new_val= m_doc->m_api.m_charact_mgr.CreateCopyCharacteristicVal(characts[i], NULL, &map);
		m_api->m_data.GetAttr(characts[i], m_api->m_charact_mgr.a_apl_charact_val_item, old_item);
		new_item= (CaplInstance*)map.QGetPointerByIn((long)old_item);
		
		if(new_item)
			m_api->m_data.PutAttr(new_val, m_api->m_charact_mgr.a_apl_charact_val_item, new_item);
	}

	m_api->SetModeInteractive(bOldMode);
	m_api->SetAutoSave(bOldAutoSave);

	if(m_api->m_AutoSave)
		m_api->SaveChanges();	
	
	StopBusy();
}

//****************************************************************
bool CaplProductTreeItem::PasteItem(CaplTreeItem *item, CPoint *point)
{
	if(item==0) return false;
	if(item->m_type!=APL_TREE_ITEM_PRODUCT)
		if (item->m_type != APL_TREE_ITEM_DOCUMENT)
			if (item->m_type != APL_TREE_ITEM_CHARACTERISTIC)
				if (item->m_type != APL_TREE_ITEM_CHARACTERISTICGROUP)
					if (item->m_type != APL_TREE_ITEM_BP)
						if (item->m_type != APL_TREE_ITEM_BPINST)
							if (item->m_type != APL_TREE_ITEM_PROJECT)
								if (item->m_type != APL_TREE_ITEM_REQUIREMENT)
								return false;
	if(m_tree==0) return false;
	if(m_doc==0) return false;

	if (item->m_type == APL_TREE_ITEM_BPINST)
	{
/*  	CaplInstance *inst;
		CaplInstance *i_act=((CaplBPInstTreeItem *)item)->m_inst;

		if(m_pdf!=0) inst=m_pdf; else inst=m_prd;

		CaplInstance *rel=m_doc->m_api.m_bp_mgr.CreateInstanceAssociation(inst,i_act);
		if(rel==0) return false;

		CaplBPInstTreeItem *new_item=0;
		InsertInstInTree(i_act,m_item,m_doc,m_tree,m_all_bp_inst,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0)new_item->m_rel=rel;
		MyExpand();
		return true;*/
	}
	else if(item->m_type == APL_TREE_ITEM_PROJECT)
	{
		CaplInstance *obj=0,*rel=0;
		CaplInstance *project=((CaplProjectTreeItem*)item)->m_inst;
		obj=m_prd;
		if(m_pdf) obj=m_pdf;
		if(obj) rel=m_doc->m_project_mgr->CreateAssociation(project,obj);
		if(rel)
		{
			CaplProjectTreeItem *new_item=0;
			InsertInstInTree(project,m_item,m_doc,m_tree,m_all_projects,0,(CaplTreeItem **)(&new_item));
			if(new_item!=0) new_item->m_rel=obj;
			MyExpand(false);
		}
		return true;
	}
	else if(item->m_type==APL_TREE_ITEM_REQUIREMENT && m_prd_item_type==S::product)
	{
		return false;
	}

	CMenu menu;  gSetPsmResourceHandle();
	CMenu *pPopup;
	VERIFY(menu.LoadMenu(IDR_PASTE_ITEM_MENU));
// 	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));
	CaplMenu::Install(m_tree); // 	VERIFY(CaplMenu::Install(m_tree, ePopupMenu ));
	
	// (Для ВНИИС)
	bool bEnableSetMaterial=false;
	CString sRoleName;
	m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Роли\\Роль для редактирования норм расхода у утвержденных изделий"), sRoleName, _T(""));
	if(sRoleName!=_T(""))
	{
		if(m_doc->m_api.m_appr_mgr.CheckPersonRole(0,sRoleName)) bEnableSetMaterial=true;
	}


	CaplProductTreeItem *pitem= NULL;	
	if(item->m_type == APL_TREE_ITEM_PRODUCT)
	{
		pitem=(CaplProductTreeItem*)item;
		if(m_pdf==pitem->m_pdf) if(m_pdf!=0) return false;
		if(m_pdf!=0)
		{
			if(m_pdf->GetAccessmode()>aplRO)
			{
				aplErrorMessage(S::NoAccessRight(),m_pdf);
				return false;
			}
		}
		else if(m_prd!=0)
		{
			if(m_prd->GetAccessmode()>aplRO)
			{
				aplErrorMessage(S::NoAccessRight(),m_prd);
				return false;
			}
		}
		else return false;

		pPopup = menu.GetSubMenu(INDEX_PRODUCT_MENU);

		if(m_pdf)
		{
			CString state;
			m_doc_data.GetAttr(m_pdf,m_doc->m_api.m_prd_mgr.a_apl_pdf_state,state);
			if(state!=_T("working") && state!=_T("changing") && state!=_T(""))
			{
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUBPART,MF_BYCOMMAND|MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_COPY_CONTENTS,MF_BYCOMMAND|MF_GRAYED);
				//pPopup->EnableMenuItem(ID_PRODUCT_ITEM_REPLACE,MF_BYCOMMAND|MF_GRAYED);  
				//pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUPPLIED_ID,MF_BYCOMMAND|MF_GRAYED);

				if(!bEnableSetMaterial)
				{
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_ZAGOTOV,MF_BYCOMMAND|MF_GRAYED);
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INS_MATERIAL,MF_BYCOMMAND|MF_GRAYED);
				}

				//pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_ALTERNATE,MF_BYCOMMAND|MF_GRAYED);
				//pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUBSTITUTE,MF_BYCOMMAND|MF_GRAYED);

				//AfxMessageBox("Иделие находится в состоянии \""+m_doc->m_api.m_bp_mgr.GetWFStateName(state)+"\" и не может быть изменено");
				//return false;
			}
			aplExtent ext;
			item->GetAccessedInstances(ext);
			m_doc_data.GetAttr(ext[0],m_doc->m_api.m_prd_mgr.a_apl_pdf_state,state);
			if(state==_T("canceled"))
			{
				CString sRole;
				m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Роли\\Роль для использования аннулированных изделий"), sRole, _T(""));
				if(sRole==_T("") || (!m_doc->m_api.m_appr_mgr.CheckPersonRole(0,sRole)))
				{
					AfxMessageBox( APL_T("Иделие находится в состоянии \"")+m_doc->m_api.m_bp_mgr.GetWFStateName(state)+ APL_T("\" и не может быть использовано"));
					return false;
				}

				if(IDYES!=AfxMessageBox( APL_T("Иделие находится в состоянии \"")+m_doc->m_api.m_bp_mgr.GetWFStateName(state)+ APL_T("\" и не должно быть использовано.\n\nИспользовать?"),MB_YESNO|MB_ICONSTOP))
					return false;
			}
			if(m_pdf->GetAccessmode()==aplRO)
			{
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUBPART,MF_BYCOMMAND|MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_COPY_CONTENTS,MF_BYCOMMAND|MF_GRAYED);
				//pPopup->EnableMenuItem(ID_PRODUCT_ITEM_REPLACE,MF_BYCOMMAND|MF_GRAYED);  * Проверять надо сборку
				//pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUPPLIED_ID,MF_BYCOMMAND|MF_GRAYED);
				if(!bEnableSetMaterial)
				{
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_ZAGOTOV,MF_BYCOMMAND|MF_GRAYED);
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INS_MATERIAL,MF_BYCOMMAND|MF_GRAYED);
				}
				
				//pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_ALTERNATE,MF_BYCOMMAND|MF_GRAYED);
				//pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUBSTITUTE,MF_BYCOMMAND|MF_GRAYED);
			}
		}
	}
	else if(item->m_type == APL_TREE_ITEM_DOCUMENT)
	{
		if(m_pdf)
		{
			CString state;
			m_doc_data.GetAttr(m_pdf,m_doc->m_api.m_prd_mgr.a_apl_pdf_state,state);
			if(state!=_T("working") && state!=_T("changing") && state!=_T(""))
			{
				// ayatsk добавить документ скорее можно
				//AfxMessageBox("Изделие находится в состоянии \""+m_doc->m_api.m_bp_mgr.GetWFStateName(state)+"\" и не может быть изменено");
				//return false;
			}
		}
		aplExtent ext;
		item->GetAccessedInstances(ext);
		CString state; 
		m_doc_data.GetAttr(ext[0],m_doc->m_api.m_doc_mgr.a_apl_doc_wf_state,state);
		if(state==_T("canceled"))
		{
			AfxMessageBox( APL_T("Документ находится в состоянии \"")+m_doc->m_api.m_bp_mgr.GetWFStateName(state)+ APL_T("\" и не может быть изменен"));
			return false;
		}
		pPopup = menu.GetSubMenu(INDEX_DOCUMENT_MENU);
		pPopup->DeleteMenu(ID_DOCUMENT_INITIAL, MF_BYCOMMAND);
	}
	else if(item->m_type == APL_TREE_ITEM_CHARACTERISTIC)
		pPopup = menu.GetSubMenu(INDEX_CHARACTERISTIC_MENU);
	else if(item->m_type == APL_TREE_ITEM_CHARACTERISTICGROUP)
		pPopup = menu.GetSubMenu(INDEX_CHARACTERISTIC_MENU);
	else if (item->m_type == APL_TREE_ITEM_BP)
		pPopup = menu.GetSubMenu(INDEX_BP_MENU);
	else if (item->m_type == APL_TREE_ITEM_BPINST)
		pPopup = menu.GetSubMenu(INDEX_BP_INST_PASTE_MENU);
	else if (item->m_type == APL_TREE_ITEM_REQUIREMENT)
		pPopup = menu.GetSubMenu(INDEX_REQ_PDF_PASTE_MENU);
	
	if(pPopup!=0)
	{
		POINT pnt;
		if(point==0)
		{
			RECT rect;
			m_tree->GetItemRect(m_item,&rect,TRUE);
			m_tree->ClientToScreen(&rect);
			pnt.x=rect.right;
			pnt.y=rect.bottom;
		}
		else
		{
			pnt.x=point->x;
			pnt.y=point->y;
		}

		if(item->m_type == APL_TREE_ITEM_PRODUCT && pitem)
		{
			if((pitem->m_pdf==0)||(m_pdf==0))
			{
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUBPART,MF_BYCOMMAND|MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_COPY_CONTENTS,MF_BYCOMMAND|MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUPPLIED_ID,MF_BYCOMMAND|MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_ZAGOTOV,MF_BYCOMMAND|MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INS_MATERIAL,MF_BYCOMMAND|MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUBSTITUTE,MF_BYCOMMAND|MF_GRAYED);
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_ALTERNATE,MF_BYCOMMAND|MF_GRAYED);
			}
			if(pitem->m_pdf==m_pdf)
			{
				pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_ALTERNATE,MF_BYCOMMAND|MF_GRAYED);
			}
			if(pitem->m_pdf!=0)
			{
				if(pitem->m_pdf->GetAccessmode()>aplRO)
				{
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUBPART,MF_BYCOMMAND|MF_GRAYED);
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_COPY_CONTENTS,MF_BYCOMMAND|MF_GRAYED);
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUPPLIED_ID,MF_BYCOMMAND|MF_GRAYED);
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_ZAGOTOV,MF_BYCOMMAND|MF_GRAYED);
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INS_MATERIAL,MF_BYCOMMAND|MF_GRAYED);
					
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_ALTERNATE,MF_BYCOMMAND|MF_GRAYED);
					pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUBSTITUTE,MF_BYCOMMAND|MF_GRAYED);
				}
			}		
		}

		HTREEITEM parent = m_tree->GetNextItem(item->m_item,TVGN_PARENT);
		if(parent)
		{
			CaplTreeItem *parent_item = (CaplTreeItem*)m_tree->GetItemData(parent);
			if(parent_item)
			{
				if(parent_item->m_type==APL_TREE_ITEM_QUERY)
				{
					pPopup->EnableMenuItem(ID_DOCUMENT_MOVE, MF_BYCOMMAND|MF_GRAYED);
				}
			}
		}
		if(!m_nauo)
		{
			pPopup->EnableMenuItem(ID_PRODUCT_ITEM_INSERT_SUBSTITUTE,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_PRODUCT_ITEM_REPLACE, MF_BYCOMMAND|MF_GRAYED);

		}
		pPopup->RemoveMenu(ID_PRODUCT_ITEM_CHANGE, MF_BYCOMMAND);

		BOOL res=pPopup->TrackPopupMenu(TPM_LEFTALIGN|
			TPM_RIGHTBUTTON|TPM_RETURNCMD,pnt.x,pnt.y,m_tree);

		if(res==ID_PRODUCT_ITEM_INSERT_SUBPART)
		{

			if(!m_doc->m_api.m_appr_mgr.CheckPersonRoleByOption(0,APL_NO_T("Роли\\Роль для редактирования структуры изделия"),true))return false;

			if(!m_doc->m_api.m_classifier_mgr.CheckItemInClassifierByOption(pitem->m_pdf,APL_NO_T("Справочники\\Справочники изделий для вхождения в сборку"),true))return false;

			int NoMultipleIns=0;
			m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Изделия\\Запретить многократное вхождение в сборку"),NoMultipleIns,0);

			CaplAttrValue tst_values[5];
			tst_values[0].value.Set(m_pdf);
			tst_values[0].attr=m_doc->m_api.m_prd_mgr.a_pdr_r_ting;
			tst_values[1].value.Set(pitem->m_pdf);
			tst_values[1].attr=m_doc->m_api.m_prd_mgr.a_pdr_r_ted;
			int rule_count=2;
			
			aplExtent ext_rel;
			CaplInstance *old_rel=0;

			if(0 < m_doc->m_api.m_data.NET_FindInstancesWithAttrValues(m_doc->m_api.m_prd_mgr.e_pdr,2,&tst_values[0],ext_rel,true))
			{
				if(1==NoMultipleIns) // Для ГРПЗ
				{
					if(IDYES!=AfxMessageBox( APL_T("Связь данных изделий уже есть в БД !!!\n\nРедактировать существующую связь?"),MB_YESNO|MB_ICONWARNING)) return false;
					old_rel=ext_rel[0];
				}
				else
				{
					int rez=AfxMessageBox( APL_T("Связь данных изделий уже есть в БД !!!\n\n Редактировать существующую связь?\n\n(Нажатие \"нет\" приведет к созданию новой свзяи."),MB_YESNOCANCEL|MB_ICONWARNING);
					if(rez==IDCANCEL) return false;
					if(rez==IDYES) old_rel=ext_rel[0];
				}
			}

			// создание связи сборки
			CPrdRelationDlg dlg;
			dlg.m_prd_mgr=&(m_doc->m_api.m_prd_mgr);
			dlg.m_charact_mgr=&(m_doc->m_api.m_charact_mgr);
			dlg.m_mode=_T("Create Assembly");
			dlg.m_data=&(m_doc->m_api.m_data);
			dlg.m_pdr=old_rel;
			dlg.m_in_pdf=m_pdf;
			dlg.m_in_prd=m_prd;
			dlg.m_out_pdf=pitem->m_pdf;
			dlg.m_out_prd=pitem->m_prd;

			if(m_pdf!=0)
			{
				if(m_pdf->GetAccessmode()>aplRO)	AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);
				else if(dlg.DoModal()==IDOK)
				{
					if(0==old_rel)
					{
						CaplProductTreeItem *product_item=
							new CaplProductTreeItem(m_tree,m_doc,0,dlg.m_out_pdf);
						product_item->m_nauo=dlg.m_pdr;
						product_item->CreateTreeItem(m_item);
						m_all_sub_product.Add(dlg.m_pdr);
						product_item->RefreshItem();
						m_tree->RedrawWindow();

						if(pitem->m_nauo && pitem && dlg.m_pdr)
						{
							m_doc->m_api.m_data.PutAttr(dlg.m_pdr, m_doc->m_api.m_prd_mgr.a_pdr_parent_reference, pitem->m_nauo);
							m_doc->m_api.SaveChanges();
						}
					}
					else 
					{
						Expand(1);
						MyExpand();
					}
				}
			}
			return true;
		}
		else if (res == ID_DEL_PARENT_PDF)
		{
			int h = 0;
		}
		else if(res == ID_SET_PARENT_PDF)
		{
			if(m_pdf && pitem && pitem->m_pdf)
				m_doc->m_api.m_data.PutAttr(pitem->m_pdf, m_doc->m_api.m_prd_mgr.a_apl_pdf_parent, m_pdf);

			if(m_nauo && pitem && pitem->m_nauo)
				m_doc->m_api.m_data.PutAttr(m_nauo, m_doc->m_api.m_prd_mgr.a_pdr_parent_reference, pitem->m_nauo);

		}
		else if(res==ID_PRODUCT_ITEM_INSERT_COPY_CONTENTS)
		{
			if(!m_doc->m_api.m_appr_mgr.CheckPersonRoleByOption(0,APL_NO_T("Роли\\Роль для редактирования структуры изделия"),true))return false;

			//CycleTest
			if(m_pdf)
			{
				aplExtent ext;
				item->GetAccessedInstances(ext);
				if(ext[0]==0) return false;;
				CaplInstance *inst = ext[0];
				if(!m_doc->m_api.m_data.TestCycleInRelation(m_doc->m_api.m_prd_mgr.e_pdr,m_doc->m_api.m_prd_mgr.a_pdr_r_ting,m_doc->m_api.m_prd_mgr.a_pdr_r_ted,m_pdf,inst)) 
				{
					AfxMessageBox( APL_T("Цикл в структуре."),MB_OK|MB_ICONWARNING);
					return false;
				}
			}

			if(IDYES!=AfxMessageBox( APL_T("Вы действительно хотите скопировать состав изделия ?"), MB_YESNO|MB_ICONQUESTION)) return false;
			{
				CopyRelations(pitem->m_pdf, m_pdf);
				Expand(1);
				MyExpand();
			}
		}
		else if(res==ID_PRODUCT_ITEM_INSERT_ZAGOTOV)
		{

			if(!m_doc->m_api.m_appr_mgr.CheckPersonRoleByOption(0,APL_NO_T("Роли\\Роль для редактирования норм расхода"),true))return false;

			if(!m_doc->m_api.m_classifier_mgr.CheckItemInClassifierByOption(pitem->m_pdf,APL_NO_T("Справочники\\Справочники изделий для задания норм расхода"),true))return false;

			// создание связи "изготовляется из"
			CPrdRelationDlg dlg;
			dlg.m_prd_mgr=&(m_doc->m_api.m_prd_mgr);
			dlg.m_charact_mgr=&(m_doc->m_api.m_charact_mgr);
			dlg.m_mode=_T("Create MakeFrom");
			dlg.m_data=&(m_doc->m_api.m_data);
			dlg.m_in_pdf=m_pdf;
			dlg.m_in_prd=m_prd;
			dlg.m_out_pdf=pitem->m_pdf;
			dlg.m_out_prd=pitem->m_prd;

			if(dlg.DoModal()==IDOK)
			{
				CaplProductTreeItem *product_item=
					new CaplProductTreeItem(m_tree,m_doc,0,dlg.m_out_pdf);
				product_item->m_prd_item_type=_T("zagotov");
				product_item->m_nauo=dlg.m_pdr;
				product_item->CreateTreeItem(m_item);
				m_all_zagotov.Add(dlg.m_pdr);
				product_item->RefreshItem();
				m_tree->RedrawWindow();
			}
		}
		else if(res==ID_PRODUCT_ITEM_INS_MATERIAL)
		{
			if(!m_doc->m_api.m_appr_mgr.CheckPersonRoleByOption(0,APL_NO_T("Роли\\Роль для редактирования материала изделия"),true))return false;

			if(!m_doc->m_api.m_classifier_mgr.CheckItemInClassifierByOption(pitem->m_pdf,APL_NO_T("Справочники\\Справочники изделий для задания материалов"),true))return false;

			// создание связи "изготовляется из"
			CPrdRelationDlg dlg;
			dlg.m_prd_mgr=&(m_doc->m_api.m_prd_mgr);
			dlg.m_charact_mgr=&(m_doc->m_api.m_charact_mgr);
			dlg.m_mode=_T("Create Zagotov");
			dlg.m_data=&(m_doc->m_api.m_data);
			dlg.m_in_pdf=m_pdf;
			dlg.m_in_prd=m_prd;
			dlg.m_out_pdf=pitem->m_pdf;
			dlg.m_out_prd=pitem->m_prd;

			if(dlg.DoModal()==IDOK)
			{
				CaplProductTreeItem *product_item=
					new CaplProductTreeItem(m_tree,m_doc,0,dlg.m_out_pdf);
				product_item->m_prd_item_type=_T("mater");
				product_item->m_nauo=dlg.m_pdr;
				product_item->CreateTreeItem(m_item);
				m_all_zagotov.Add(dlg.m_pdr);
				product_item->RefreshItem();
				m_tree->RedrawWindow();
			}
		}
		else if(res==ID_PRODUCT_ITEM_CHANGE)
		{
			
		}
		else if(res==ID_PRODUCT_ITEM_REPLACE)
		{
			if(!m_doc->m_api.m_appr_mgr.CheckPersonRoleByOption(0,APL_NO_T("Роли\\Роль для редактирования структуры изделия"),true))return false;

			if(!m_doc->m_api.m_classifier_mgr.CheckItemInClassifierByOption(((CaplProductTreeItem*)item)->m_pdf,APL_NO_T("Справочники\\Справочники изделий для вхождения в сборку"),true))return false;
			
			CaplInstance *par_pdf;
			m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_pdr_r_ting,par_pdf);
			bool b_NoPaste=false; 
			if(par_pdf==0) b_NoPaste=true;
			else if(par_pdf->GetType()==0) b_NoPaste=true;
			else if(par_pdf->GetAccessmode()>=aplRO) b_NoPaste=true;

			if(b_NoPaste)
			{
				aplErrorMessage(S::NoAccessRight(),par_pdf);
				return false;
			}

			CString state;
			m_doc_data.GetAttr(par_pdf,m_doc->m_api.m_prd_mgr.a_apl_pdf_state,state);
			if(state!=_T("working") && state!=_T("changing") && state!=_T(""))
			{
				AfxMessageBox(APL_T("Сборочная единица не находится в состоянии \"В разработке\" или \"На изменении\"!\n\nЗамена невозможна!"),MB_ICONSTOP|MB_OK);
				return false;
			}
			
			if(IDYES==AfxMessageBox( APL_T("Вы действительно хотите заменить изделие?"), MB_ICONQUESTION|MB_YESNO))
			{
				m_doc_data.PutAttr(m_nauo, m_doc->m_api.m_prd_mgr.a_pdr_r_ted, 
					((CaplProductTreeItem*)item)->m_pdf);
				m_doc->m_api.SaveChanges();

				CollapseItem();
				
				m_pdf= ((CaplProductTreeItem*)item)->m_pdf;
				m_prd= ((CaplProductTreeItem*)item)->m_prd;
				
				RefreshItem();
			}
		}
		else if(res==ID_PRODUCT_ITEM_INSERT_SUPPLIED_ID)
		{
			// создание связи "внешнее обозначение"
			CPrdRelationDlg dlg;
			dlg.m_prd_mgr=&(m_doc->m_api.m_prd_mgr);
			dlg.m_charact_mgr=&(m_doc->m_api.m_charact_mgr);
			dlg.m_mode=_T("Create Supplied");
			dlg.m_data=&(m_doc->m_api.m_data);
			dlg.m_in_pdf=m_pdf;
			dlg.m_in_prd=m_prd;
			dlg.m_out_pdf=pitem->m_pdf;
			dlg.m_out_prd=pitem->m_prd;

			if(dlg.DoModal()==IDOK)
			{
				CaplProductTreeItem *product_item=
					new CaplProductTreeItem(m_tree,m_doc,0,dlg.m_out_pdf);
				product_item->m_prd_item_type=_T("supplier_id");
				product_item->m_nauo=dlg.m_pdr;
				product_item->CreateTreeItem(m_item);
				m_all_supplier.Add(dlg.m_out_pdf);
				product_item->RefreshItem();
			}
		}
		else if(res==ID_PRODUCT_ITEM_INSERT_ALTERNATE)
		{
			// Проверка взаимозаменяемости (аналогов)
			/*CaplAttrValue tst_values[2];
			tst_values[0].value.Set(m_prd);
			tst_values[0].attr=m_doc->m_api.m_prd_mgr.a_alt_base;
			tst_values[1].value.Set(pitem->m_prd);
			tst_values[1].attr=m_doc->m_api.m_prd_mgr.a_alt_alt;
			if(!m_doc_data.TestUniqueAttrValues(m_doc->m_api.m_prd_mgr.e_alt,0,2,&tst_values[0]))
			{
				AfxMessageBox( APL_T("Такая связь уже есть в базе !!!"));return false;
			}*/

			if(!m_doc->m_api.m_appr_mgr.CheckPersonRoleByOption(0,APL_NO_T("Роли\\Роль для редактирования аналогов"),true))return false;


			CaplAttrValue tst_values[2];
			tst_values[0].value.Set(m_pdf);
			tst_values[0].attr=m_doc->m_api.m_prd_mgr.a_alt_pdf_base;
			tst_values[1].value.Set(pitem->m_pdf);
			tst_values[1].attr=m_doc->m_api.m_prd_mgr.a_alt_pdf_alt;
			if(!m_doc_data.TestUniqueAttrValues(m_doc->m_api.m_prd_mgr.e_alt_pdf,0,2,&tst_values[0]))
			{
				AfxMessageBox( APL_T("Такая связь уже есть в базе !!!"));return false;
			}

			// создание связи "аналог"
			CPrdRelationDlg dlg;
			dlg.m_prd_mgr=&(m_doc->m_api.m_prd_mgr);
			dlg.m_charact_mgr=&(m_doc->m_api.m_charact_mgr);
			dlg.m_mode=_T("Create Alternate");
			dlg.m_data=&(m_doc->m_api.m_data);
			dlg.m_in_prd=m_prd;
			dlg.m_out_prd=pitem->m_prd;
			dlg.m_in_pdf=m_pdf;
			dlg.m_out_pdf=pitem->m_pdf;

			if(dlg.DoModal()==IDOK)
			{
				CaplProductTreeItem *product_item=
					new CaplProductTreeItem(m_tree,m_doc,pitem->m_prd,0);
				//product_item->m_prd_item_type=S::alternate;
				product_item->m_alt=dlg.m_prd_r;
				product_item->CreateTreeItem(m_item);
				m_all_alternate.Add(dlg.m_prd_r);
				product_item->RefreshItem();
			}
		}
		// Вставка документа
		else if (res == ID_DOCUMENT_COPY)
		{
			CaplInstance *inst;
			CaplInstance *i_doc=((CaplDocTreeItem *)item)->m_inst;
			if(m_pdf!=0) inst=m_pdf; else inst=m_prd;
			
			HTREEITEM ht = m_tree->GetNextItem(item->m_item,TVGN_PARENT);
			CaplTreeItem *Item = (CaplTreeItem*)m_tree->GetItemData(ht);
			aplAccessModeType access =aplOWN;
			if(Item)
			{
				aplExtent instances;
				Item->GetAccessedInstances(instances);
				if(instances.GetSize()>0)
					access = instances.GetAt(0)->GetAccessmode();
				else
					access = aplOWN;
			}
			
			if(inst->GetAccessmode()>aplRO || access>aplRO)
			{
				AfxMessageBox( APL_T("Нет доступа к объекту"));
				return false;
			}

			if(CaplDocTreeItem::InsertDoc(m_doc,this,&m_all_documents,i_doc,inst, false))
				ShowCmd(ID_SHOW_ALL_DOCS);
		}
		//создание по образцу
		else if(res == ID_DOCUMENT_BYDOT)
		{
			CaplInstance *inst;
			CaplInstance *i_doc = ((CaplDocTreeItem *)item)->m_inst;
			inst = m_pdf!=0 ? m_pdf : m_prd;

			aplExtent instances;
			GetAccessedInstances(instances);
			if(m_doc->m_api.m_doc_mgr.CreateDocumentByDot(i_doc,instances[0]))
				ShowCmd(ID_SHOW_ALL_DOCS);
		}
		//премещение документа
		else if(res == ID_DOCUMENT_MOVE)
		{
			CaplDocTreeItem *d_item = (CaplDocTreeItem*)item;
			HTREEITEM parent = m_tree->GetNextItem(d_item->m_item,TVGN_PARENT);
			CaplTreeItem *parent_item = (CaplTreeItem*)m_tree->GetItemData(parent);
			
			CaplDocTreeItem::MoveDocument(m_doc, d_item, parent_item, this);
		}
		// Вставка характеристики
		else if (res == ID_CHARACTERISTIC_COPY)
		{
			if(item->m_type == APL_TREE_ITEM_CHARACTERISTIC)
			{
				CaplInstance *i_val=((CaplCharacteristicTreeItem *)item)->m_val;
				CreateCharacteristic(i_val);
			}
			else if(item->m_type == APL_TREE_ITEM_CHARACTERISTICGROUP)
			{
				CreateCharacteristicGroup(((CaplCharacteristicGroupTreeItem*)item)->m_group);

			}
		}
		//заменяющее в контесте сборки
		else if(res== ID_PRODUCT_ITEM_INSERT_SUBSTITUTE)
		{
			// создание связи 
			CreateSubstitute(pitem);
		}
		else if(res== ID_ASSOCIATE_BP)
		{
			CaplInstance *inst;
			CaplInstance *i_act=((CaplBPTreeItem *)item)->m_inst;

			if(m_pdf!=0) inst=m_pdf; else inst=m_prd;

			CaplInstance *rel=m_doc->m_api.m_bp_mgr.CreateAssociation(inst,i_act);
			if(rel==0) return false;

			CaplBPTreeItem *new_item=0;
			InsertInstInTree(i_act,m_item,m_doc,m_tree,m_all_bp,0,(CaplTreeItem **)(&new_item));
			if(new_item!=0)new_item->m_rel=rel;
			MyExpand();
			return true;
		}
		else if(res== ID_BP_COPY)
		{
			if(IDYES!=AfxMessageBox( APL_T("Вы действительно хотите скопировать бизнес-процесс?"),MB_YESNO)) return false;
			CaplInstance *i_act=((CaplBPTreeItem *)item)->m_inst;
			if(i_act) 
			{
				CreateBPCopy(i_act);
				MyExpand();
				return true;
			}
			return false;
		}
		else if(res== ID_ASSOCIATE_BP_INST)
		{
			CaplInstance *inst;
			CaplInstance *i_act=((CaplBPInstTreeItem *)item)->m_inst;

			if(m_pdf!=0) inst=m_pdf; else inst=m_prd;

			CaplInstance *rel=m_doc->m_api.m_bp_mgr.CreateInstanceAssociation(inst,i_act);
			if(rel==0) return false;

			CaplBPInstTreeItem *new_item=0;
			InsertInstInTree(i_act,m_item,m_doc,m_tree,m_all_bp_inst,0,(CaplTreeItem **)(&new_item));
			if(new_item!=0)new_item->m_rel=rel;
			MyExpand();
			return true;
		}
		else if(res== ID_BP_INST_COPY)
		{
			CaplInstance *i_act=((CaplBPInstTreeItem *)item)->m_inst;
			if(i_act) CreateBPInstCopy(i_act);
		}
		else if(res == ID_REQUIREMENT_MOVE_PDF)
		{			
			CaplInstance *ciReq = ((CaplRequirementTreeItem*)item)->m_ciReq;
			if(!ciReq) return false;

			// может связь уже есть
			CaplAttrValue val[2];
			aplExtent aeAssoc;
			val[0].attr = m_doc->m_api.m_req_mgr.a_req_assoc_item;
			val[0].value.Set(m_pdf);
			val[1].attr = m_doc->m_api.m_req_mgr.a_req_assoc_req;
			val[1].value.Set(ciReq);
			if(m_doc->m_api.m_data.NET_FindInstancesWithAttrValues(m_doc->m_api.m_req_mgr.e_requirement_association, 2, &val[0], aeAssoc, true))
			{
				MessageBox(0,  APL_T("Связь уже существует."),  APL_T("Дублирование связи"), MB_ICONINFORMATION);
				return false;
			}

			CaplInstance *ciItem = m_prd;
			if(m_pdf) ciItem = m_pdf;

			CaplInstance *ciAssoc = m_doc->m_api.m_req_mgr.CreateAssociation(ciReq, ciItem);
			if(!ciAssoc) return false;

			CaplRequirementTreeItem *pItem = new CaplRequirementTreeItem(m_tree, m_doc, ciReq, 0, 0, ciAssoc);
			pItem->CreateTreeItem(m_item);		
			MyExpand(false);
		}
		else if(res == ID_REQUIREMENT_COPY_PDF && m_prd_item_type==S::pdf)
		{
			CaplInstance *ciReq = ((CaplRequirementTreeItem*)item)->m_ciReq;
			if(!ciReq) return false;

			// создаем копию
			CaplInstance *ciReqCopy = m_doc->m_api.m_req_mgr.CreateRequirementCopy(ciReq);
			if(!ciReqCopy) return false;

			// копируем рекурсивно содержание
			long dID = aplStartWaitDlg( APL_T("Копирование дочерних требований..."));
			m_doc->m_api.m_req_mgr.CopyRequirementsRecursive(ciReq, ciReqCopy, ciReq);	
			aplEndWaitDlg(dID);

			CaplInstance *ciItem = m_prd;
			if(m_pdf) ciItem = m_pdf;

			// создаем связь
			CaplInstance *ciAssoc = m_doc->m_api.m_req_mgr.CreateAssociation(ciReqCopy, ciItem);
			if(!ciAssoc) return false;

			CaplRequirementTreeItem *pItem = new CaplRequirementTreeItem(m_tree, m_doc, ciReqCopy, 0, 0, ciAssoc);
			pItem->CreateTreeItem(m_item);		
			MyExpand(false);
		}
	}

	m_tree->RedrawWindow();
	return true;
}

//****************************************************************
void CaplProductTreeItem::CreateSubPart()
{
	if(m_doc==0) return;
	if(m_tree==0) return;
	if(m_pdf==0) return;
	if(m_pdf->GetType()==0) return;

	if(m_doc->m_api.m_prd_mgr.bNoCreateAndChangePDF)
	{
		AfxMessageBox(IDS_NO_CREATE_PDF,MB_OK|MB_ICONSTOP);
		return;
	}

	if(m_pdf==0)m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_prd);
	if(m_pdf!=0)
	{
		m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_pdf);
		if(m_pdf->GetAccessmode()>aplRW)	{AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}
	}

	CString buf;

	bool add_mode=true;
	CaplInstance *base_pdf=m_pdf;
	CaplInstance *base_prd=m_prd;
	CaplInstance *base_nauo=0;


	while(add_mode)
	{
		base_nauo=0;
		add_mode = m_doc->m_api.m_prd_mgr.CreateSubProduct(m_pdf, &base_pdf, &base_nauo);
		if(base_nauo)
		{
			m_doc_data.GetAttr(base_pdf, m_doc->m_api.m_prd_mgr.a_pdf_prd, base_prd);
			
			CaplProductTreeItem *product_item=
				new CaplProductTreeItem(m_tree, m_doc, 0, base_pdf);
			product_item->m_nauo=base_nauo;
			product_item->CreateTreeItem(m_item);
			m_all_sub_product.Add(base_nauo);
			product_item->RefreshItem();
			MyExpand();
			m_doc->ChangeItem(0);m_doc->ChangeItem(this);
		}
		else
			add_mode=false;
	}
}
//****************************************************************
void CaplProductTreeItem::CreateProductCopy()
{
	if(m_doc==0) return;
	if(m_tree==0) return;
	if(m_pdf==0) return;
	if(m_pdf->GetType()==0) return;

	if(m_doc->m_api.m_prd_mgr.bNoCreateAndChangePDF)
	{
		AfxMessageBox(IDS_NO_CREATE_PDF,MB_OK|MB_ICONSTOP);
		return;
	}

	if(m_pdf==0)m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_prd);
	if(m_pdf!=0)
	{
		m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_pdf);
		if(m_pdf->GetAccessmode()>aplRW)	{AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}
	}

	CString buf;

	bool add_mode=true;
	CaplInstance *base_pdf=m_pdf;
	CaplInstance *base_prd=m_prd;
	CaplInstance *base_nauo=0;


	while(add_mode)
	{
		base_nauo=0;
		add_mode = m_doc->m_api.m_prd_mgr.CreateProductCopy(m_pdf, &base_pdf, &base_nauo);
		if(base_nauo)
		{
			if(IDYES == AfxMessageBox( APL_T("Скопировать состав ?"), MB_YESNO|MB_ICONQUESTION))
			{
				CopyRelations(m_pdf, base_pdf);
			}

			m_doc_data.GetAttr(base_pdf, m_doc->m_api.m_prd_mgr.a_pdf_prd, base_prd);
			
			CaplProductTreeItem *product_item=
				new CaplProductTreeItem(m_tree, m_doc, 0, base_pdf);
			product_item->m_nauo=base_nauo;
			product_item->CreateTreeItem(m_item);
			m_all_sub_product.Add(base_nauo);
			product_item->RefreshItem();
			MyExpand();
			m_doc->ChangeItem(0);m_doc->ChangeItem(this);
		}
		else
			add_mode=false;
	}
}

//****************************************************************
void CaplProductTreeItem::ReplaceToProductCopy()
{
	if(m_doc==0) return;
	if(m_tree==0) return;
	if(m_pdf==0) return;
	if(m_pdf->GetType()==0) return;

	if(m_doc->m_api.m_prd_mgr.bNoCreateAndChangePDF)
	{
		AfxMessageBox(IDS_NO_CREATE_PDF,MB_OK|MB_ICONSTOP);
		return;
	}

	if(m_pdf==0)m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_prd);
	if(m_pdf!=0)
	{
		m_doc->m_api.m_prd_mgr.LoadPrdInfo(m_pdf);
		if(m_pdf->GetAccessmode()>aplRO)	{AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}
	}

	CaplInstance *nauo4Change=0, *bpres4change=0;
	CaplBPResourceTreeItem *parentTreeItem=0;

	if(0!=m_nauo && m_prd_item_type==_T("part"))
	{
		CaplInstance *parentPdf=0;
		m_doc_data.GetAttr(m_nauo, m_doc->m_api.m_prd_mgr.a_pdr_r_ting, parentPdf);
		if(0==parentPdf) {AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}
		if(parentPdf->GetAccessmode()>aplRW) {AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}

		CString state;
		m_doc_data.GetAttr(parentPdf, m_doc->m_api.m_prd_mgr.a_apl_pdf_state, state);

		if(state!=_T("working") && state!=_T("changing") && state!=_T(""))
		{
			CString buf;
			buf.Format(APL_T("Родительское иделие находится в состоянии \"%s\" и не может быть изменено!"),m_doc->m_api.m_prd_mgr.GetWFStateName(state));
			AfxMessageBox(buf,MB_OK|MB_ICONSTOP);
			return ;
		}
		nauo4Change=m_nauo;
	}
	else
	{
		HTREEITEM hitem=m_tree->GetParentItem(m_item);
		CaplTreeItem *parentTtreeIitem=NULL;
		if(hitem) parentTtreeIitem= (CaplTreeItem *)m_tree->GetItemData(hitem);
		if(parentTtreeIitem!=0)
		{
			if(parentTtreeIitem->m_type==APL_TREE_ITEM_BPRES)
			{

				CaplBPResourceTreeItem *bpresTreeItem=(CaplBPResourceTreeItem*)parentTtreeIitem;
				bpres4change=bpresTreeItem->m_inst;
				parentTreeItem=bpresTreeItem;

				if(bpres4change->GetAccessmode()>aplRW)	{AfxMessageBox(APL_T("Недостаточно прав для изменения ресурса"),MB_OK|MB_ICONSTOP); return;}

				CaplInstance *bp=0;
				m_doc_data.GetAttr(bpres4change, m_doc->m_api.m_bp_mgr.a_bp_res_process, bp);
				if(0==bp) {AfxMessageBox(APL_T("Ошибка в данных!"),MB_OK|MB_ICONSTOP); return;}
				if(bp->GetAccessmode()>aplRW)	{AfxMessageBox(APL_T("Недостаточно прав для изменения бизнес-процесса"),MB_OK|MB_ICONSTOP); return;}

				CString state;
				m_doc_data.GetAttr(bp, m_doc->m_api.m_bp_mgr.a_bp_state, state);

				if(state!=_T("working") && state!=_T("changing") && state!=_T(""))
				{
					CString buf;
					buf.Format(APL_T("Бизнес-процесс находится в состоянии \"%s\" и не может быть изменен!"),m_doc->m_api.m_prd_mgr.GetWFStateName(state));
					AfxMessageBox(buf,MB_OK|MB_ICONSTOP);
					return ;
				}
			}
		}
	}

	if(0==nauo4Change && 0==bpres4change) {AfxMessageBox(APL_T("Выполнение невозможно - негде заменить!"),MB_OK|MB_ICONSTOP); return; }

	CaplInstance *newPdf=m_doc->m_api.m_prd_mgr.CreateProduct(m_pdf, aplModeCreateProductIfNew);

	if(0==newPdf) return;

	CopyRelations(m_pdf, newPdf, true);

	if(0!=nauo4Change)	m_doc_data.PutAttr(nauo4Change, m_doc->m_api.m_prd_mgr.a_pdr_r_ted, newPdf);
	else if(0!=bpres4change) m_doc_data.PutAttr(bpres4change, m_doc->m_api.m_bp_mgr.a_bp_res_object, newPdf);

	m_doc->m_api.SaveChanges();
	Expand(TVE_COLLAPSE);

	m_pdf=newPdf;
	m_doc_data.GetAttr(m_pdf,m_doc->m_api.m_prd_mgr.a_pdf_prd,m_prd);

	if(0==parentTreeItem) RefreshItem();
	else
	{
		parentTreeItem->Expand(TVE_COLLAPSE);
		parentTreeItem->RefreshItem();
		parentTreeItem->MyExpand();
	}
}


//****************************************************************
void CaplProductTreeItem::CreateBPInst()
{
	if(m_doc==0) return;
	if(m_tree==0) return;
	if(m_prd==0) return;
	if(m_prd->GetType()==0) return;

	CaplInstance *inst=m_prd;
	if(m_pdf!=0)
	{
		if(m_pdf->GetType()==0) return;
		inst=m_pdf;
	}

	if(inst==0) return;
	if(inst->GetType()==0) return;
	if(inst->GetAccessmode()>aplRO){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}

	m_doc->m_api.m_prd_mgr.LoadPrdInfo(inst);
	
	CString str_id=_T("");
	if(m_pdf!=0)
	{
		CaplInstance *pdf_prd=0;
		m_doc_data.GetAttr(inst,m_doc->m_api.m_prd_mgr.a_pdf_prd,pdf_prd);
		if(pdf_prd) m_doc_data.GetAttr(pdf_prd,m_doc->m_api.m_prd_mgr.a_prd_id,str_id);
		CString buf=_T("");
		m_doc_data.GetAttr(inst,m_doc->m_api.m_prd_mgr.a_pdf_id,buf);
		if(buf!=_T("")) str_id+=_T("-")+buf;
	}
	else
		m_doc_data.GetAttr(inst,m_doc->m_api.m_prd_mgr.a_prd_id,str_id);
	
	CaplInstance *rel=0;
	CaplInstance *i_act=m_doc->m_api.m_bp_mgr.CreateBPInst(0,str_id,0,0,0,inst,0,&rel);
	if(i_act && rel)
	{
		CaplBPInstTreeItem *new_item=0;
		InsertInstInTree(i_act,m_item,m_doc,m_tree,m_all_bp_inst,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0)new_item->m_rel=rel;
		MyExpand();
	}
}

void CaplProductTreeItem::ShowAllAlternate()
{
	if(m_prd==0) return;
	if(m_doc==0) return;
	if(!m_doc_data.IsConnected()) return;
	if(m_prd->GetAccessmode()>aplRO)
	{
		aplErrorMessage(S::NoAccessRight(),m_prd);
		return ;
	}
	if(0==m_pdf) return;
	if(m_pdf->GetAccessmode()>aplRO)
	{
		aplErrorMessage(S::NoAccessRight(),m_pdf);
		return ;
	}
	StartBusy();

	int i;
	aplExtent ext0,ext1;
	SetStatusString( APL_T("Чтение из базы"));
	//m_doc->m_api.m_prd_mgr.LoadProductAlternates(m_prd,ext0,ext1);
	m_doc->m_api.m_prd_mgr.LoadPdfAlternates(m_pdf,ext0,ext1);

	aplExtent ext01,ext11;
	m_doc->m_api.m_prd_mgr.LoadPdfAlternateReady(m_pdf,ext01,ext11);

	ext0.Append(ext01);

	SetStatusString(_T(""));
	
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);	
	for(i=0;i<ext0.Size;i++)
	{
		if(m_all_alternate.Find(ext0[i])==-1)
		{
			CaplInstance *prd=0, *pdf=0;
			if(m_doc_data.IsKindOf(ext0[i],m_doc->m_api.m_prd_mgr.e_alt)) // старый вариант
			{
				m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_alt_alt,prd);
				if(prd==m_prd ) m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_alt_base,prd);
			}
			else if(m_doc_data.IsKindOf(ext0[i],m_doc->m_api.m_prd_mgr.e_alt_pdf)) // новый вариант
			{
				m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_alt_pdf_alt,pdf);
				if(pdf==m_pdf)  m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_alt_pdf_base,pdf);

				if(0!=pdf) m_doc_data.GetAttr(pdf,m_doc->m_api.m_prd_mgr.a_pdf_prd,prd);
			}

			if(0!=prd)
			{
				CaplProductTreeItem *product_item=
					new CaplProductTreeItem(m_tree,m_doc,prd,pdf);
				//product_item->m_prd_item_type=S::alternate;
				product_item->m_alt=ext0[i];
				product_item->CreateTreeItem(m_item);
				m_all_alternate.Add(ext0[i]);
				product_item->RefreshItem();
			}
		}
	}
	MyExpand(false);
	StopBusy();
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}
//****************************************************************
void CaplProductTreeItem::CreateCharacteristic(CaplInstance *val)
{
	CaplInstance *item, *new_val=0;
	if(m_pdf!=0) item=m_pdf; else item=m_prd;
	CaplTreeItem::CreateCharacteristic(item, val);
	/*
	if(m_doc->m_api.m_charact_mgr.CreateCharacteristic(item,val, &new_val,0,0,true))
	{

		if(CaplTreeItem::m_AutoUzurpireCharacteristic)
		{
			aplExtent ext; ext.Add(new_val);
			m_doc_data.NET_BecomeInstancesOwner(&ext);
		}

		CaplCharacteristicTreeItem *characteristic_item=
			new CaplCharacteristicTreeItem(m_tree,m_doc,new_val);
		characteristic_item->CreateTreeItem(m_item);
		m_all_caracteristic.Add(new_val);
		MyExpand();
		m_doc->ChangeItem(0);m_doc->ChangeItem(this);
	}*/
}
//****************************************************************
void CaplProductTreeItem::CreateCharacteristicGroup(CaplInstance *group)
{
	CaplInstance *item, *new_val=0;
	if(m_pdf!=0) item=m_pdf; else item=m_prd;

	CaplTreeItem::CreateCharacteristicGroup(item, group);
	/*
	CaplInstance *group_new=0;
	if(m_doc->m_api.m_charact_mgr.CreateCharacteristicGroup(item,&group_new,group))
	{
		if(group!=0)
		{
			if(CaplTreeItem::m_AutoUzurpireCharacteristic)
			{
				aplExtent ext; ext.Add(group);
				m_doc_data.NET_BecomeInstancesOwner(&ext);
			}
		}
		CaplCharacteristicGroupTreeItem *characteristic_group_item=
			new CaplCharacteristicGroupTreeItem(m_tree,m_doc,group_new);
		characteristic_group_item->CreateTreeItem(m_item);
		m_all_caracteristic.Add(group_new);
		MyExpand();
		m_doc->ChangeItem(0);m_doc->ChangeItem(this);
	}*/
}
//****************************************************************
void CaplProductTreeItem::ShowAllLot()
{
	if(m_doc==0) return;
	StartBusy();
	aplExtent ext;
	m_doc->m_api.m_prd_inst_mgr.FindAllPdfLoot(m_pdf,ext);
	if(ext.GetSize()>0)m_doc->m_api.m_prd_inst_mgr.LoadExtentInfo(ext);
	for(int i=0; i<ext.Size;i++)
	{
		if(m_all_lots.Find(ext[i])==-1)
		{
			CaplLotTreeItem *lot_item= new CaplLotTreeItem(m_tree,m_doc,ext[i]);
			lot_item->CreateTreeItem(m_item);
			m_all_lots.Add(ext[i]);
		}
	}
	MyExpand(false);
	StopBusy();
	m_tree->SetRedraw(TRUE);
}
//****************************************************************

void CaplProductTreeItem::ShowAllPrdInst()
{
	if(m_doc==0) return;
	StartBusy();
	aplExtent ext;
	m_doc->m_api.m_prd_inst_mgr.FindAllPdfInstances(m_pdf,ext);
	if(ext.Size<=0) 
	{
		StopBusy();
		//AfxMessageBox(APL_T("Такие экземпляры не найдены!")); при рекурсивном раскрытии дерева это сообщение просто убивает. ДИВ
	}
	for(int i=0; i<ext.Size;i++)
	{
		if(m_all_prd_inst.Find(ext[i])==-1)
		{
			CaplPrdInstTreeItem *inst_item= new CaplPrdInstTreeItem(m_tree,m_doc,ext[i]);
			inst_item->CreateTreeItem(m_item);
			m_all_prd_inst.Add(ext[i]);
		}
	}
	if(ext.Size>0) MyExpand(false);
	StopBusy();
	m_tree->SetRedraw(TRUE);
}

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

void CaplProductTreeItem::ShowAllChanges(bool bFromExpand)
{
	if(m_pdf == 0) return;
	int k= 	m_all_changes.GetSize();
	aplExtent ext;
	StartBusy();
	bool bRes= m_doc->m_api.m_change_mgr.GetAllChanges(m_pdf, ext);
	for(int i= 0; i<ext.GetSize(); i++)
	{
		if(-1==m_all_changes.Find(ext[i]))
		{
			CaplChangeTreeItem *chng_item=
				new CaplChangeTreeItem(m_tree, m_doc, ext[i]);
			chng_item->CreateTreeItem(m_item);
			m_all_changes.Add(ext[i]);
		}
	}
	if(m_doc->m_api.m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие")))
	{
		// Отображаем измеения, в которых PDF является зависимым
		CString sQuery;
		sQuery.Format(_T("SELECT Ext_ FROM Ext_{apl_change(.dependent_items   LIKE  #%i)}	END_SELECT"),m_pdf->GetId());
		if(m_doc->m_api.m_data.NET_QueryEditParse(sQuery))
		{
			aplExtent ext_changes;
			m_doc->m_api.m_data.NET_QueryExecute(ext_changes);	
			if(ext_changes.GetSize()>0)
			{
				m_doc->m_api.m_change_mgr.LoadChangeInfo(ext_changes);
				for(int i= 0; i<ext_changes.GetSize(); i++)
				{
					if(-1==m_all_changes.Find(ext_changes[i]))
					{
						CaplChangeTreeItem *chng_item=
							new CaplChangeTreeItem(m_tree, m_doc, ext_changes[i]);
						chng_item->CreateTreeItem(m_item);
						m_all_changes.Add(ext_changes[i]);
					}
				}
			}
		}
	}

	StopBusy();
	if(!bFromExpand)
	{
		if(k>=m_all_changes.Size) AfxMessageBox( APL_T("Новые изменения не найдены!"));
		MyExpand();
	}
}

//****************************************************************
void CaplProductTreeItem::ShowRelationProperties(CaplInstance *rel)
{
	if(0==rel) rel=m_alt;
	if(0==rel) return;


	CaplAPI *api = &m_doc->m_api;
	CPrdRelationDlg dlg;
	dlg.m_prd_mgr=&(m_doc->m_api.m_prd_mgr);
	dlg.m_charact_mgr=&(m_doc->m_api.m_charact_mgr);
	dlg.m_mode=_T("Create Alternate");
	dlg.m_data=&(m_doc->m_api.m_data);
	dlg.m_prd_r=rel;

	CaplInstance *prd,*prd1,*pdf=0, *pdf1=0;

	if(api->m_data.IsKindOf(rel,api->m_prd_mgr.e_alt)) // старый вариант
	{
		CaplInstance *prd,*prd1;
		api->m_data.GetAttr(rel, api->m_prd_mgr.a_alt_alt,prd);
		api->m_data.GetAttr(rel, api->m_prd_mgr.a_alt_base, prd1);
	}
	else if(api->m_data.IsKindOf(rel,api->m_prd_mgr.e_alt_pdf))  //  Новый вариант
	{
		api->m_data.GetAttr(rel, api->m_prd_mgr.a_alt_pdf_alt,pdf);
		api->m_data.GetAttr(rel, api->m_prd_mgr.a_alt_pdf_base, pdf1);
		api->m_data.GetAttr(pdf, api->m_prd_mgr.a_pdf_prd,prd);
		api->m_data.GetAttr(pdf1, api->m_prd_mgr.a_pdf_prd,prd1);
	}
	else return;

	dlg.m_out_prd=prd;
	dlg.m_out_pdf=pdf;
	dlg.m_in_prd=prd1;
	dlg.m_in_pdf=pdf1;

	if(dlg.DoModal()==IDOK)RefreshItem();
}
//****************************************************************

void CaplProductTreeItem::ShowAllRequirement()
{
	if(m_pdf == 0) return;
	int k= 	m_all_req.GetSize();
	aplExtent ext, extAssoc;
	CaplInstance *ciReq;
	CaplAPI *api = &m_doc->m_api;
	StartBusy();

	bool bRes = api->m_req_mgr.FindAssociatedReqs(m_pdf, ext, extAssoc);
	for(int i= 0; i<extAssoc.GetSize(); i++)
	{
		api->m_data.GetAttr(extAssoc[i], api->m_req_mgr.a_req_assoc_req, ciReq);
		if(ciReq->GetType() == 0) continue;

		if(-1==m_all_req.Find(ciReq))
		{
			CaplRequirementTreeItem *req_item=
				new CaplRequirementTreeItem(m_tree, m_doc, ciReq, 0, 0, extAssoc[i]);

			req_item->CreateTreeItem(m_item);
			m_all_req.Add(ciReq);
		}
	}

	StopBusy();
	MyExpand();
}

//****************************************************************
void CaplProductTreeItem::ShowAllBPs(bool showMsg)
{
	if(m_doc==0) return;
	if(m_item==0) return;
	if(m_prd==0) return;
	if(m_prd->GetType()==0) return;
	if(m_prd->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight(),m_prd);return;};
	
	CaplInstance *inst=m_prd;
	if(m_pdf!=0)
	{
		if(m_pdf->GetType()==0) return;
		if(m_pdf->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight(),m_pdf);return;};
		inst=m_pdf;
	}

	int i,k=m_all_bp.Size;
	CaplInstance *inst0;
	aplExtent ext, ext_rel;
	StartBusy();
	m_doc->m_api.m_bp_mgr.FindAssociatedBP(inst,ext,ext_rel,m_doc->m_cur_context);
	StopBusy();
	
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	for(i=0;i<ext_rel.Size;i++)
	{
		m_doc_data.GetAttr(ext_rel[i],m_doc->m_api.m_bp_mgr.a_bp_ref_process,inst0);
		if(inst0==0) continue;
		CaplBPTreeItem *new_item=0;
		InsertInstInTree(inst0,m_item,m_doc,m_tree,m_all_bp,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0) new_item->m_rel=ext_rel[i];
	}
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
		
	if(k>=m_all_bp.Size) if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Новые бизнес-процессы не найдены"));
	MyExpand(false);
	return;
}
//****************************************************************
void CaplProductTreeItem::ShowAllBPInst(bool showMsg)
{
	if(m_doc==0) return;
	if(m_item==0) return;
	if(m_prd==0) return;
	if(m_prd->GetType()==0) return;
	if(m_prd->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight(),m_prd);return;};
	
	CaplInstance *inst=m_prd;
	if(m_pdf!=0)
	{
		if(m_pdf->GetType()==0) return;
		if(m_pdf->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight(),m_pdf);return;};
		inst=m_pdf;
	}
	
	int i,k=m_all_bp_inst.Size;
	CaplInstance *inst0;
	aplExtent ext, ext_rel;
	StartBusy();
	m_doc->m_api.m_bp_mgr.FindAssociatedBPInst(inst,ext,ext_rel,m_doc->m_cur_context);
	StopBusy();
	
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	for(i=0;i<ext_rel.Size;i++)
	{
		m_doc_data.GetAttr(ext_rel[i],m_doc->m_api.m_bp_mgr.a_bp_inst_ref_process,inst0);
		if(inst0==0) continue;
		CaplBPInstTreeItem *new_item=0;
		InsertInstInTree(inst0,m_item,m_doc,m_tree,m_all_bp_inst,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0) new_item->m_rel=ext_rel[i];
	}
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
		
	if(k>=m_all_bp_inst.Size) if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Новые экземпляры бизнес-процессы не найдены"));
	if(ext_rel.Size >0) MyExpand(false);
	return;
}
//****************************************************************
bool CaplProductTreeItem::PasteFile(LPCTSTR file, CPoint *point)
{
	if(file==0) return false;
	if(m_pdf!=0) CreateDoc(m_pdf,file);
	else CreateDoc(m_prd,file);
	return true;
}
//****************************************************************
void CaplProductTreeItem::CreateBP(CaplInstance *inst_for_id)
{
	if(m_doc==0) return;
	if(m_tree==0) return;
	if(m_prd==0) return;
	if(m_prd->GetType()==0) return;
	
	CaplInstance *inst=m_prd;
	if(m_pdf!=0)
	{
		if(m_pdf->GetType()==0) return;
		inst=m_pdf;
	}

	m_doc->m_api.m_prd_mgr.LoadPrdInfo(inst);

	CString str_id;
	TCHAR *id=0;
	if(inst_for_id!=0)
	{
		GetInstID(inst_for_id,str_id);
		id=(TCHAR*)LPCTSTR(str_id);
	}

	if(inst==0) return;
	if(inst->GetType()==0) return;
	if(inst->GetAccessmode()>aplRO){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}
	CaplInstance *rel=0;
	//CaplInstance *i_act=m_doc->m_api.m_bp_mgr.CreateBP(0,inst,id,0,0,APL_MODE_CREATE_BP,&rel,m_doc->m_cur_context);
	CaplInstance *i_act=m_doc->m_api.m_bp_mgr.CreateBP(0,inst,id,0,0,APL_MODE_CREATE_BP,&rel,0);
	if(i_act && rel)
	{
		CaplBPTreeItem *new_item=0;
		InsertInstInTree(i_act,m_item,m_doc,m_tree,m_all_bp,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0)new_item->m_rel=rel;
		MyExpand();
	}
}

//****************************************************************
void CaplProductTreeItem::CreateBPCopy(CaplInstance *base_bp)
{
	if(m_doc==0) return;
	if(m_tree==0) return;
	if(m_prd==0) return;
	if(m_prd->GetType()==0) return;
	
	CaplInstance *inst=m_prd;
	if(m_pdf!=0)
	{
		if(m_pdf->GetType()==0) return;
		inst=m_pdf;
	}

	//m_doc->m_api.m_prd_mgr.LoadPrdInfo(inst);

	if(inst==0) return;
	if(inst->GetType()==0) return;
	if(inst->GetAccessmode()>aplRO){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}
	CaplInstance *rel=0;


	CString buf;
	m_doc_data.GetAttr(m_prd,m_doc->m_api.m_prd_mgr.a_prd_id,buf);
	if(!buf.IsEmpty())
	{
		m_doc->m_api.m_bp_mgr.m_sIdPostfixForCreateBPCopy=_T("___");
		m_doc->m_api.m_bp_mgr.m_sIdPostfixForCreateBPCopy+=buf;
	
		if(m_pdf!=0)
		{
			m_doc_data.GetAttr(m_pdf,m_doc->m_api.m_prd_mgr.a_pdf_id,buf);
			if(!buf.IsEmpty())
			{
				m_doc->m_api.m_bp_mgr.m_sIdPostfixForCreateBPCopy+=_T("-");
				m_doc->m_api.m_bp_mgr.m_sIdPostfixForCreateBPCopy+=buf;
			}
		}
	}

	CaplInstance *i_act=m_doc->m_api.m_bp_mgr.CreateBPCopy(base_bp,0,0,0,inst,0,&rel);
	m_doc->m_api.m_bp_mgr.m_sIdPostfixForCreateBPCopy.Empty();
	if(i_act)m_doc->m_api.m_bp_mgr.CheckIn(i_act,true,true);
	m_doc->m_api.SaveChanges();
	if(i_act && rel)
	{
		CaplBPTreeItem *new_item=0;
		InsertInstInTree(i_act,m_item,m_doc,m_tree,m_all_bp,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0)new_item->m_rel=rel;
		MyExpand();
	}
}

//****************************************************************
void CaplProductTreeItem::CreateBPInstCopy(CaplInstance *base_bp_inst)
{
	if(m_doc==0) return;
	if(m_tree==0) return;
	if(m_prd==0) return;
	if(m_prd->GetType()==0) return;
	
	CaplInstance *inst=m_prd;
	if(m_pdf!=0)
	{
		if(m_pdf->GetType()==0) return;
		inst=m_pdf;
	}

	//m_doc->m_api.m_prd_mgr.LoadPrdInstInfo(inst);

	if(inst==0) return;
	if(inst->GetType()==0) return;
	if(inst->GetAccessmode()>aplRO){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}
	CaplInstance *rel=0;
	CaplInstance *i_act=m_doc->m_api.m_bp_mgr.CreateBPInstCopy(base_bp_inst,0,0,0,0,inst,0,&rel);
	if(i_act && rel)
	{
		CaplBPInstTreeItem *new_item=0;
		InsertInstInTree(i_act,m_item,m_doc,m_tree,m_all_bp_inst,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0)new_item->m_rel=rel;
		MyExpand();
	}
}
//****************************************************************
void CaplProductTreeItem::RemoveRelation()
{
	if(m_prd==0) return;
	if((m_nauo==0)&&(m_alt==0)&&(m_project==0)&&(m_subst==0)) return;

	int i;
	// проверка на alternate
	if(m_alt!=0)
	{
		if(m_alt->GetAccessmode()>aplOWN)
		{
			AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);
			return;
		}

		if(!m_doc->m_api.m_appr_mgr.CheckPersonRoleByOption(0,APL_NO_T("Роли\\Роль для редактирования аналогов"),true))return;

		if(AfxMessageBox( APL_T("Вы уверены ?"),MB_YESNO|MB_DEFBUTTON2)!=IDYES) return;
		m_doc_data.DeleteInstance(m_alt);
		m_doc_data.NET_SaveChanges();
		
		for(i=0;i<m_doc->m_items.Size;i++)
		{
			if(m_doc->m_items[i]!=this)
			{
				if(m_doc->m_items[i]->m_type==APL_TREE_ITEM_PRODUCT)
				{
					CaplProductTreeItem *item=(CaplProductTreeItem*)m_doc->m_items[i];
					if(item->m_alt==m_alt) 
					{
						m_doc->m_items.Remove(i); i--;
					}
				}
			}
		}
	}
	else if(m_nauo)
	{
		if(m_doc->m_api.m_data.IsKindOf(m_nauo,m_doc->m_api.m_prd_mgr.e_nauo))
		{
			if(!m_doc->m_api.m_appr_mgr.CheckPersonRoleByOption(0,APL_NO_T("Роли\\Роль для редактирования структуры изделия"),true))
				return;
		}
		else  if(m_doc->m_api.m_data.IsKindOf(m_nauo,m_doc->m_api.m_prd_mgr.e_make_from))
		{
			if(!m_doc->m_api.m_appr_mgr.CheckPersonRoleByOption(0,APL_NO_T("Роли\\Роль для редактирования норм расхода для изделия"),true))
				return;
		}
		else if(m_doc->m_api.m_data.IsKindOf(m_nauo,m_doc->m_api.m_prd_mgr.e_design_make_from))
		{
			if(!m_doc->m_api.m_appr_mgr.CheckPersonRoleByOption(0,APL_NO_T("Роли\\Роль для редактирования материала изделия"),true))
				return;
		}

		CaplInstance *pdf1;
		m_doc_data.GetAttr(m_nauo, m_doc->m_api.m_prd_mgr.a_pdr_r_ting, pdf1);
		CStringArray sa;
		CString state = m_doc->m_api.m_appr_mgr.GetPossibleWFState(pdf1,sa);
		if(state!=_T("working") && state!= _T("changing") && state!=_T("")) 
		{
			bool bExit=true;

			// (Для ВНИИС)
			if(m_doc_data.IsKindOf(m_nauo,m_doc->m_api.m_prd_mgr.e_make_from))
			{
				CString sRoleName;
				m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Роли\\Роль для редактирования норм расхода у утвержденных изделий"), sRoleName, _T(""));
				if(sRoleName!=_T(""))
				{
					if(m_doc->m_api.m_appr_mgr.CheckPersonRole(0,sRoleName)) bExit=false;
				}
			}

			if(bExit)
			{
				AfxMessageBox( APL_T("Изделие находится в состоянии ")+m_doc->m_api.m_appr_mgr.GetWFStateName(state)+ APL_T(" и не может быть изменено!"));
				return;
			}
		}
		if(pdf1!=0)
		{
			if(pdf1->GetAccessmode()>aplRW)
			{
				bool bExit=true;
				CString sRoleName;
				m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Роли\\Роль для редактирования норм расхода у утвержденных изделий"), sRoleName, _T(""));
				if(sRoleName!=_T(""))
				{
					if(m_doc->m_api.m_appr_mgr.CheckPersonRole(0,sRoleName)) bExit=false;
				}

				if(bExit)
				{
					AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);
					return;
				}
			}
		}

		if(AfxMessageBox( APL_T("Вы уверены ?"),MB_YESNO|MB_DEFBUTTON2)!=IDYES) return;

		for(i=0;i<m_doc->m_items.Size;i++)
		{
			if(m_doc->m_items[i]!=this)
			{
				if(m_doc->m_items[i]->m_type==APL_TREE_ITEM_PRODUCT)
				{
					CaplProductTreeItem *item=(CaplProductTreeItem*)m_doc->m_items[i];
					if(item->m_nauo==m_nauo) 
					{
						m_doc->m_items.Remove(i); i--;
					}
				}
			}
		}
		
		m_doc_data.DeleteInstance(m_nauo);
		m_doc_data.NET_SaveChanges();
	}
	else if(m_project)
	{
		CaplInstance *obj=m_prd;
		if(m_pdf) obj=m_pdf;
		if(!obj) return;
		if(AfxMessageBox( APL_T("Вы уверены ?"),MB_YESNO|MB_DEFBUTTON2)!=IDYES) return;
		if(!m_doc->m_project_mgr->DeleteAssociation(m_project,obj)) return;
		CaplProjectTreeItem *prj_item=(CaplProjectTreeItem*)GetParentItem(this);
		if(prj_item) prj_item->m_all_items.Remove(prj_item->m_all_items.Find(obj));
	}
	else if(m_subst)
	{
		CaplInstance *pdr,*pdf1;
		m_doc_data.GetAttr(m_subst, m_doc->m_api.m_prd_mgr.a_pdf_subst_pdr, pdr);
		if(!pdr) return;
		m_doc_data.GetAttr(pdr, m_doc->m_api.m_prd_mgr.a_pdr_r_ting, pdf1);
		if(!pdf1) return;
		CStringArray sa;
		CString state = m_doc->m_api.m_appr_mgr.GetPossibleWFState(pdf1,sa);
		if(state!=_T("working") && state!= _T("changing") && state!=_T("")) 
		{
			CString buf;
			m_doc->m_api.GetItemName(pdf1,buf);
			AfxMessageBox( APL_T("Изделие ")+buf+ APL_T(" находится в состоянии ")+m_doc->m_api.m_appr_mgr.GetWFStateName(state)+ APL_T(" и не может быть изменено!"));
			return;
		}
		if(pdf1->GetAccessmode()>aplRW)
		{
			AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);
			return;
		}

		if(AfxMessageBox( APL_T("Вы уверены ?"),MB_YESNO|MB_DEFBUTTON2)!=IDYES) return;

		RemoveSubst(true);
	}
	m_doc->m_items.Remove(m_doc->m_items.Find(this));		
}
//****************************************************************
void CaplProductTreeItem::RemoveProductVersion()
{
	if(m_prd==0) return;
	if(m_pdf==0) return;

	if(m_pdf->GetAccessmode()>aplOWN){ AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);return;}
	if(AfxMessageBox( APL_T("Вы уверены ?"),MB_YESNO|MB_DEFBUTTON2)!=IDYES) return;
	if(!m_doc->m_api.m_prd_mgr.DeleteProductVersion(m_pdf,false)) return;

	m_doc_data.NET_SaveChanges();

	m_doc->ChangeItem(0);
	m_tree->DeleteItem(m_item);
	
    HTREEITEM item;
    while(1)
    {
        item=m_tree->GetChildItem(m_item);
        if(item==0) break;
        CaplTreeItem *treeitem=(CaplTreeItem*)m_tree->GetItemData(item);
		if(treeitem==this) continue;
        if(treeitem!=0) 
                m_doc->m_items.Remove(m_doc->m_items.Find(treeitem));
        else m_tree->DeleteItem(item);
    }
	
	m_item=0;
	for(int i=0;i<m_doc->m_items.Size;i++)
	{
		if(m_doc->m_items[i]!=this)
		{
			if(m_doc->m_items[i]->m_type==APL_TREE_ITEM_PRODUCT)
			{
				CaplProductTreeItem *item=(CaplProductTreeItem*)m_doc->m_items[i];
				if(item->m_pdf==m_pdf) 
				{
					m_doc->m_items.Remove(i); i--;
				}
				else if(item->m_prd==m_prd)
				{
					if(m_prd->GetType()==0) {m_doc->m_items.Remove(i); i--;}
				}
			}
		}
	}
	m_doc->m_items.Remove(m_doc->m_items.Find(this));	
	return;
}
//****************************************************************
void CaplProductTreeItem::RemoveProduct()
{
	if(m_prd==0) return;
	if(m_pdf!=0) {AfxMessageBox( APL_T("Сначала удалите все версии !")); return;}

	if(m_prd->GetAccessmode()>aplOWN)
	{
		AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);
		return;
	}
	// поиск версий
	SetStatusString( APL_T("Чтение из базы"));

	CaplAttrValue val[1];
	aplExtent ext;

	val[0].value.Set(m_prd);
	val[0].attr= m_doc->m_api.m_prd_mgr.a_pdf_prd;

	//исполнитель задания не подтвердил получение задания
	m_doc_data.NET_FindInstancesWithAttrValues(m_doc->m_api.m_prd_mgr.e_pdf, 1, 
		&val[0], ext, false);

	SetStatusString(_T(""));

	if(ext.GetSize()>0) {AfxMessageBox( APL_T("Изделие имеет версии -> его нельзя удалить !\n\nУдалите сначала версии.")); return;}

	if(AfxMessageBox( APL_T("Вы уверены ?"),MB_YESNO|MB_DEFBUTTON2)!=IDYES) return;

	m_doc_data.DeleteInstance(m_prd);
	m_doc_data.NET_SaveChanges();

	for(int i=0;i<m_doc->m_items.Size;i++)
	{
		if(m_doc->m_items[i]!=this)
		{
			if(m_doc->m_items[i]->m_type==APL_TREE_ITEM_PRODUCT)
			{
				CaplProductTreeItem *item=(CaplProductTreeItem*)m_doc->m_items[i];
				if(item->m_prd==m_prd) 
				{
					m_doc->m_items.Remove(i); i--;
				}
			}
		}
	}
	m_doc_data.NET_SaveChanges();
	m_doc->m_items.Remove(m_doc->m_items.Find(this));	
}
//****************************************************************
void CaplProductTreeItem::RemoveFromCategory()
{
	if(m_prd==0) return;
	if(m_pdf!=0) return;

	HTREEITEM hitem=m_tree->GetParentItem(m_item);
	CaplTreeItem *treeitem=(CaplTreeItem *)m_tree->GetItemData(hitem);
	if(treeitem==0) return;
	if(treeitem->m_type!=APL_TREE_ITEM_CATEGORIES)return;

	if(m_prd->GetAccessmode()>aplOWN)
	{
		AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);
		return;
	}
	
	int i;
	CaplInstance *inst0;
	CaplAggr aggr;
	if(AfxMessageBox( APL_T("Вы уверены ?"),MB_YESNO|MB_DEFBUTTON2)!=IDYES) return;

	CaplInstance *instcateg=((CaplCategoryTreeItem*)treeitem)->m_inst;
	if(instcateg==0) return;
	if(instcateg->GetType()==0) return;

	if(!m_doc->m_api.m_categ_mgr.RemovePrdFromCategory(m_prd,instcateg)) return;

	for(i=0;i<m_doc->m_items.Size;i++)
	{
		if(m_doc->m_items[i]->m_type==APL_TREE_ITEM_PRODUCT)
		{
			if(((CaplProductTreeItem*)m_doc->m_items[i])->m_prd==m_prd)
			{
				if(((CaplProductTreeItem*)m_doc->m_items[i])->m_pdf==0)
				{
					hitem=m_tree->GetParentItem(((CaplProductTreeItem*)m_doc->m_items[i])->m_item);
					treeitem=(CaplTreeItem *)m_tree->GetItemData(hitem);
					if(treeitem!=0)
					{
						if(treeitem->m_type==APL_TREE_ITEM_CATEGORIES)
						{
							inst0=((CaplCategoryTreeItem*)treeitem)->m_inst;
							if(instcateg==inst0)
							{
								if(m_doc->m_items[i]!=this){m_doc->m_items.Remove(i);i--;}
							}
						}
					}
				}
			}
		}
	}
	m_doc->m_items.Remove(m_doc->m_items.Find(this));
}
//****************************************************************
bool CaplProductTreeItem::RemoveDocument(CaplInstance * pDocument)
{
	int nIndex;
	nIndex = m_all_documents.Find(pDocument);
	if (nIndex != -1)
	{
		m_all_documents.Remove(nIndex);
		m_doc->ChangeItem(0);m_doc->ChangeItem(this);
		return true;
	}
	return false;
}
//****************************************************************
void CaplProductTreeItem::ExportStructureToTextFile()
{
	if(m_prd==0) return;
	if(m_pdf==0) return;

	CString FileName,buf;
	CString id,name,ver,s_count,pos,type,has_eff,sUnit;

	aplExtent ext0,ext1;
	CaplInstance *inst0,*inst1,*i_pdf,*i_prd;
	int i,j;

	TCHAR*  lpszDefExt=_T("");
	TCHAR* szFilter = _T("Text Files (*.txt)|*.txt|CSV Files (*.csv)|*.csv|All Files (*.*)|*.*||");
	m_doc_data.GetAttr(m_prd,m_doc->m_api.m_prd_mgr.a_prd_id,id);
	m_doc_data.GetAttr(m_prd,m_doc->m_api.m_prd_mgr.a_prd_name,name);
	buf=id;buf+=_T("-");
	m_doc_data.GetAttr(m_pdf,m_doc->m_api.m_prd_mgr.a_pdf_id,ver);
	buf+=ver;
	
	CFileDialog dlgFile(FALSE, _T("txt"),LPCTSTR(buf),
		OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT|OFN_EXTENSIONDIFFERENT,szFilter);
	if(dlgFile.DoModal() != IDOK) return;

	FileName=dlgFile.GetPathName();
	if(FileName==_T("")) return;

	bool isCSV=false;
	CString fext;
	i=FileName.ReverseFind(_T('.'));
	if(i>0)fext=FileName.Right(FileName.GetLength()-(i+1));
	fext.MakeLower();
	if(fext==_T("csv"))isCSV=true;


	CStdioFile file;
	if(FALSE==file.Open(FileName,CFile::modeWrite|CFile::modeCreate|CFile::typeText))
	{
		AfxMessageBox ( APL_T("Ошибка создани файла"));
		return;
	}
	buf.Format( APL_T("Структура изделия %s ( %s ) - %s\n\n"),id,name,ver);
	file.WriteString(buf);
	if(isCSV)APL_T("\"Позиция\";\"Тип\";\"Обозначение\";\"Наименование\";\"Версия\";\"Количество\";\"Ед. Изм.\";\"Применяемость\"\n\n");
	else buf= APL_T("Позиция\tТип\tОбозначение\tНаименование\tВерсия\tКоличество\tЕд. Изм.\tПрименяемость\n\n");
	file.WriteString(buf);

	StartBusy();	
	m_doc->m_api.m_prd_mgr.LoadAllSubProduct(0,0,m_pdf,ext0,ext1,true);
	StopBusy();

	// Экспорт структуры изделия
	for(i=0;i<ext0.Size;i++)
	{
		id=_T(""); name=_T(""); ver=_T(""); s_count=_T("");pos=_T("");type=_T("");has_eff=_T("");

		m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_pdr_r_ted,i_pdf);
		m_doc_data.GetAttr(i_pdf,m_doc->m_api.m_prd_mgr.a_pdf_prd,i_prd);
		if(i_prd!=0)
		{
			m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_pdr_id,pos);
			m_doc_data.GetAttr(i_prd,m_doc->m_api.m_prd_mgr.a_prd_id,id);
			m_doc_data.GetAttr(i_prd,m_doc->m_api.m_prd_mgr.a_prd_name,name);
			m_doc_data.GetAttr(i_pdf,m_doc->m_api.m_prd_mgr.a_pdf_id,ver);
			
			m_doc_data.GetAttr(i_pdf,m_doc->m_api.m_prd_mgr.a_apl_pdf_type,buf);
			
			type=m_doc->m_api.m_prd_mgr.StrConvertPdfType2Rus(buf);

			sUnit=_T("");
			double count=1;
			if(m_doc_data.IsKindOf(ext0[i],m_doc->m_api.m_prd_mgr.e_apl_qacu))
			{
				m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_apl_qacu_value,count);
				m_doc_data.GetAttr(ext0[i],m_doc->m_api.m_prd_mgr.a_apl_qacu_unit,inst1);
				m_doc->m_api.m_charact_mgr.GetUnitName(inst1,sUnit);
			}
			s_count=Double2Str(count);
//			s_count.Format(_T("%g %s"),count,buf);

			aplExtent ext2;
			has_eff= APL_T("Нет");
			m_doc_data.GetEntityExtent(m_doc->m_api.m_prd_mgr.e_pd_eff,ext2);
			for(j=0;j<ext2.Size;j++)
			{
				m_doc_data.GetAttr(ext2[j],m_doc->m_api.m_prd_mgr.a_pde_usage,inst0);
				if(inst0==ext0[i]){has_eff= APL_T("Есть");break;}
			}
			if(isCSV)
			{
				buf.Format(_T("\n\"%s\";\"%s\";\"%s\";\"%s\";\"%s\";\"%s\";\"%s\";\"%s\""),pos,type,id,name,ver,s_count,sUnit,has_eff);
			}
			else buf.Format(_T("\n%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s"),pos,type,id,name,ver,s_count,sUnit,has_eff);
			file.WriteString(buf);
		}
	}
	file.Flush();
	file.Close();
}
//****************************************************************
// функция чтения структуры на один уровень вниз
void GetSubProducts(CPSMDoc *doc, CaplInstance *pdf, aplExtent &a_pdf,
					aplExtent &a_nauo)
{
	if(doc==0) return;
	if(pdf==0) return;
	if(a_pdf.Find(pdf)!=-1) return;
	a_pdf.Add(pdf);

	int i;
	aplExtent ext_rel,ext_pdf;

	doc->m_api.m_prd_mgr.LoadAllSubProduct(0,0,pdf,ext_rel,ext_pdf);

	for(i=0;i<ext_rel.Size;i++) a_nauo.Add(ext_rel[i]);
	
	for(i=0;i<ext_pdf.Size;i++)
		GetSubProducts(doc,ext_pdf[i],a_pdf,a_nauo);
}
//****************************************************************
void CaplProductTreeItem::ExportStructureToEF()
{
	if(m_doc==0) return;
	if(m_prd==0) return;
	if(m_pdf==0) return;

	int i,j,k;
	MSG msg;
	CString id,buf,buf1,f_ext,f_name, f_path;
	CExportToEfDlg dlg;
	m_doc_data.GetAttrBN(m_prd,S::id,dlg.m_prd_id);
	m_doc_data.GetAttrBN(m_prd,S::name,dlg.m_prd_name);
	m_doc_data.GetAttrBN(m_pdf,S::id,dlg.m_prd_ver);
	
	buf=dlg.m_prd_id;
	if(dlg.m_prd_ver!=_T(""))
	{
		buf+=_T("_");
		buf+=dlg.m_prd_ver;
	}
	buf+=_T(".stp");
	dlg.m_FileName=buf;
	if(dlg.DoModal()!=IDOK)	return;

	i=dlg.m_FileName.ReverseFind(_T('\\'));
	j=dlg.m_FileName.ReverseFind(_T('/'));
	if(j>i) i=j;
	f_path=dlg.m_FileName.Left(i+1);
		
	aplExtent a_pd, a_c_pdf,a_c_nauo,new_nauo_ext;
	aplExtent ext0,aReferences;
	CaplInstance *pd=0;
	CaplInstance *inst0=0,*inst1=0,*inst2=0,*inst3=0, *i_pd=0,*i_pdf=0,*i_prd=0;
	CaplInstance *i_unit1=0,*i_unit2=0,*i_de=0,*i_doc=0,*pInstance=0;
	CaplAggr aItems;
	CaplMap pdf_map,prd_map,nauo_map,doc_map;
	
	//составление списка экспортируемых PD и NAUO
	StartBusy();
	GetSubProducts(m_doc,m_pdf,a_c_pdf,a_c_nauo);

	CaplStepData newdata;
	if(!newdata.LoadDictionary(_T("config_control_design"))) {AfxMessageBox( APL_T("Не найден словарь для экспорта")); return;}

	//экспорт изделий
	for(i=0;i<a_c_pdf.Size;i++)
	{
		inst0=a_c_pdf[i];
		i_pdf=(CaplInstance*)pdf_map.GetByIn((long)inst0);
		if((i_pdf==0)||(i_pdf==(void*)-1)) 
		{
			i_pdf=newdata.CreateInstanceBN(S::pdf);
			if(dlg.m_exp_doc==TRUE)
				 i_pd=newdata.CreateInstanceBN(_T("product_definition_with_associated_documents"));
			else i_pd=newdata.CreateInstanceBN(S::pd);

			newdata.PutAttrBN(i_pd,S::formation,i_pdf);
			pdf_map.Add((long)inst0,(long)i_pd);
		}
		if(i_pdf!=0)
		{
			m_doc_data.GetAttrBN(inst0,S::id,buf);
			newdata.PutAttrBN(i_pdf,S::id,buf);
			m_doc_data.GetAttrBN(inst0,S::description,buf);
			newdata.PutAttrBN(i_pdf,S::description,buf);

			//prd
			m_doc_data.GetAttrBN(inst0,S::of_product,inst1);
			i_prd=(CaplInstance*)prd_map.GetByIn((long)inst1);
			if((i_prd==0)||(i_prd==(void*)-1)) 
			{
				i_prd=newdata.CreateInstanceBN(S::product);
				newdata.PutAttrBN(i_pdf,S::of_product,i_prd);
				prd_map.Add((long)inst1,(long)i_prd);
			}
			if(i_prd!=0)
			{
				m_doc_data.GetAttrBN(inst1,S::id,buf);
				newdata.PutAttrBN(i_prd,S::id,buf);
				m_doc_data.GetAttrBN(inst1,S::name,buf);
				newdata.PutAttrBN(i_prd,S::name,buf);
				m_doc_data.GetAttrBN(inst1,S::description,buf);
				newdata.PutAttrBN(i_prd,S::description,buf);
			}
		}
	}
	//экспорт структуры
	CStringArray str_ar;
	str_ar.Add(S::qacu);
	str_ar.Add(_T("next_assembly_usage_occurrence"));
	CaplEntity *e_apl_qauo=m_doc_data.GetEntityBN(S::apl_qacu);
	CaplEntity *e_nauo=newdata.GetEntityBN(_T("next_assembly_usage_occurrence"));
	CaplEntity *e_nauo_qauo=newdata.GetComplexEntityBN(str_ar);

	for(i=0;i<a_c_nauo.Size;i++)
	{
		inst0=a_c_nauo[i];
		bool has_meas=false;
		if(m_doc_data.IsKindOf(inst0,e_apl_qauo))
		{
			double rval,r1,r2,r3,r4,r5,r6,r7;
			m_doc_data.GetAttrBN(inst0,S::unit_component,i_unit1);
			m_doc_data.GetAttrBN(inst0,S::value_component,rval);
			if(dlg.m_map_qacu_to_nauo)
			{
				for(int i_mwu=0; i_mwu<rval; i_mwu++)
				{
					inst1=newdata.CreateInstance(e_nauo);
					new_nauo_ext.Add(inst1);

					m_doc_data.GetAttrBN(inst0,S::id,buf);
					newdata.PutAttrBN(inst1,S::id,buf);
					m_doc_data.GetAttrBN(inst0,S::name,buf);
					newdata.PutAttrBN(inst1,S::name,buf);
					m_doc_data.GetAttrBN(inst0,S::description,buf);
					newdata.PutAttrBN(inst1,S::description,buf);

					m_doc_data.GetAttrBN(inst0,S::relating_pd,inst2);
					inst2=(CaplInstance*)pdf_map.GetByIn((long)inst2);
					if(inst2==(CaplInstance*)-1)inst2=0;
					if(inst2!=0) newdata.PutAttrBN(inst1,S::relating_pd,inst2);

					m_doc_data.GetAttrBN(inst0,S::related_pd,inst2);
					inst2=(CaplInstance*)pdf_map.GetByIn((long)inst2);
					if(inst2==(CaplInstance*)-1)inst2=0;
					if(inst2!=0) newdata.PutAttrBN(inst1,S::related_pd,inst2);
				}
			}
			else
			{
				inst3=newdata.CreateInstanceBN(S::measure_with_unit);
				inst1=newdata.CreateInstance(e_nauo_qauo);
				has_meas=true;
				new_nauo_ext.Add(inst1);
				
				// Запись количества
				newdata.PutAttrBN(inst1,S::quantity,inst3);
				newdata.PutAttrBN(inst3,S::value_component,rval);
				
				// чтение размерности
				i_de=0;r1=r2=r3=r4=r5=r6=r7=0;
				if(i_unit1!=0)
				{
					m_doc_data.GetAttrBN(i_unit1,_T("dimensions"),i_de);
					if(i_de!=0)
					{
						m_doc_data.GetAttrBN(i_de,_T("length_exponent"),r1);
						m_doc_data.GetAttrBN(i_de,_T("mass_exponent"),r2);
						m_doc_data.GetAttrBN(i_de,_T("time_exponent"),r3);
						m_doc_data.GetAttrBN(i_de,_T("electric_current_exponent"),r4);
						m_doc_data.GetAttrBN(i_de,_T("thermodynamic_temperature_exponent"),r5);
						m_doc_data.GetAttrBN(i_de,_T("amount_of_substance_exponent"),r6);
						m_doc_data.GetAttrBN(i_de,_T("luminous_intensity_exponent"),r7);
					} 
				}
				i_unit2=0;
				// создание ед. измерения
				if(i_unit1!=0)
				{
					if(m_doc_data.IsKindOfBN(i_unit1,S::si_unit))
					{
						i_unit2=newdata.CreateInstanceBN(S::si_unit);
						m_doc_data.GetAttrBN(i_unit1,S::prefix,buf);
						if(buf!=_T("")) m_doc_data.PutAttrBN(i_unit2,S::prefix,buf);
					}
				}
				if(i_unit2==0) i_unit2=newdata.CreateInstanceBN(_T("context_dependent_unit"));
				m_doc_data.PutAttrBN(inst3,S::unit_component,i_unit2);
				if(i_unit1!=0) m_doc_data.GetAttrBN(i_unit1,S::name,buf);
				else buf= APL_T("шт.");
				m_doc_data.PutAttrBN(i_unit2,S::name,buf);
				
				i_de=newdata.CreateInstanceBN(_T("dimensional_exponents"));
				newdata.PutAttrBN(i_unit2,_T("dimensions"),i_de);
				m_doc_data.PutAttrBN(i_de,_T("length_exponent"),r1);
				m_doc_data.PutAttrBN(i_de,_T("mass_exponent"),r2);
				m_doc_data.PutAttrBN(i_de,_T("time_exponent"),r3);
				m_doc_data.PutAttrBN(i_de,_T("electric_current_exponent"),r4);
				m_doc_data.PutAttrBN(i_de,_T("thermodynamic_temperature_exponent"),r5);
				m_doc_data.PutAttrBN(i_de,_T("amount_of_substance_exponent"),r6);
				m_doc_data.PutAttrBN(i_de,_T("luminous_intensity_exponent"),r7);
			}
		}
		else 
		{
			inst1=newdata.CreateInstance(e_nauo);
			new_nauo_ext.Add(inst1);
		}

		m_doc_data.GetAttrBN(inst0,S::id,buf);
		newdata.PutAttrBN(inst1,S::id,buf);
		m_doc_data.GetAttrBN(inst0,S::name,buf);
		newdata.PutAttrBN(inst1,S::name,buf);
		m_doc_data.GetAttrBN(inst0,S::description,buf);
		newdata.PutAttrBN(inst1,S::description,buf);

		m_doc_data.GetAttrBN(inst0,S::relating_pd,inst2);
		inst2=(CaplInstance*)pdf_map.GetByIn((long)inst2);
		if(inst2==(CaplInstance*)-1)inst2=0;
		if(inst2!=0) newdata.PutAttrBN(inst1,S::relating_pd,inst2);

		m_doc_data.GetAttrBN(inst0,S::related_pd,inst2);
		inst2=(CaplInstance*)pdf_map.GetByIn((long)inst2);
		if(inst2==(CaplInstance*)-1)inst2=0;
		if(inst2!=0) newdata.PutAttrBN(inst1,S::related_pd,inst2);
	}

	CProgressDialog prgdlg;
	prgdlg.Create(IDD_PROGRESS_DLG);
	prgdlg.m_name.SetWindowText( APL_T("Экспорт документов"));
	prgdlg.ShowWindow(TRUE);

	if(dlg.m_exp_doc==TRUE)
	{
		prgdlg.m_progress.SetRange32(0,a_c_pdf.Size-1);
	
		//копирование документов
		for(k=0;k<a_c_pdf.Size;k++)
		{
			prgdlg.m_progress.SetPos(k);
			while (::PeekMessage(&msg, NULL, WM_PAINT,WM_PAINT, PM_REMOVE|PM_NOYIELD))DispatchMessage(&msg);

			CaplAggr docs;
			i_pdf=a_c_pdf[k];
			m_doc_data.GetAttrBN(i_pdf,S::of_product,i_prd);

			pd=(CaplInstance*)pdf_map.GetByIn((long)i_pdf);

			if(i_pdf==0 ||i_prd==0) continue;

			aplExtent ext0,ext1,ext_rel;
			// Чтение из базы
			m_doc->m_api.m_doc_mgr.FindAssociatedDocuments(i_pdf,ext0,ext_rel);
			m_doc->m_api.m_doc_mgr.FindAssociatedDocuments(i_prd,ext1,ext_rel);
			ext0.Append(ext1);

			for (i = 0; i < ext0.Size; i++)
			{
				pInstance=ext0[i];
				i_doc=(CaplInstance*)pdf_map.GetByIn((long)pInstance);
				if(i_doc==0 || i_doc==(CaplInstance*)-1)
				{
					// Создание описания документа
					i_doc=newdata.CreateInstanceBN(_T("document"));
					m_doc_data.GetAttrBN(pInstance,S::id,buf);
					newdata.PutAttrBN(i_doc,S::id,buf);
					m_doc_data.GetAttrBN(pInstance,S::name,buf);
					newdata.PutAttrBN(i_doc,S::name,buf);
					m_doc_data.GetAttrBN(pInstance,S::description,buf);
					newdata.PutAttrBN(i_doc,S::description,buf);
					
					m_doc_data.GetAttrBN(pInstance,_T("kind"),inst2);
					if(inst2!=0)
					{
						inst3=newdata.CreateInstanceBN(_T("document_type"));
						newdata.PutAttrBN(i_doc,_T("kind"),inst3);
						m_doc_data.GetAttrBN(inst2,_T("product_data_type"),buf);
						newdata.PutAttrBN(inst3,_T("product_data_type"),buf);
					}
					// выгрузка файла
					m_doc_data.GetAttrBN(pInstance,_T("active"),inst2);
					m_doc_data.GetAttrBN(inst2,_T("access_form"),inst3);
					if(m_doc_data.IsKindOfBN(inst3,_T("apl_stored_document")))
					{
						f_ext=_T("");
						m_doc_data.GetAttrBN(inst3,_T("file_name"),buf);
						int pnt_pos=buf.ReverseFind(_T('.'));
						if (pnt_pos!=-1) f_ext=buf.Right(buf.GetLength()-pnt_pos);
						m_doc_data.GetAttrBN(pInstance,S::id,f_name);
						f_name+=f_ext;
						if(f_path!=_T("")) buf=f_path+f_name; else buf=f_name;
						if(m_doc_data.NET_LoadBlobBN(inst3,_T("source"),(TCHAR*)LPCTSTR(buf)))
							newdata.PutAttrBN(i_doc,S::id,f_name);
					}
					else if(m_doc_data.IsKindOfBN(inst3,_T("apl_assigned_document")))
					{
						m_doc_data.GetAttrBN(inst3,_T("location_path"),buf);
						buf1=buf;
						f_ext=_T("");
						int pnt_pos=buf.ReverseFind(_T('.'));
						if (pnt_pos!=-1) f_ext=buf.Right(buf.GetLength()-pnt_pos);
						m_doc_data.GetAttrBN(pInstance,S::id,f_name);
						f_name+=f_ext;
						if(f_path!=_T("")) buf=f_path+f_name; else buf=f_name;
						if(CopyFile(buf1,buf,0))
							newdata.PutAttrBN(i_doc,S::id,f_name);
					}
				}
				if(i_doc!=0) docs.Add(i_doc);
			}
			newdata.PutAttrBN(pd,_T("documentation_ids"),docs);
		}
		prgdlg.ShowWindow(FALSE);
	}
	if(dlg.m_exp_geom==TRUE)
	{		
		prgdlg.m_name.SetWindowText( APL_T("Экспорт геометрии"));
		prgdlg.m_progress.SetRange32(0,a_c_pdf.Size-1);
		prgdlg.ShowWindow(TRUE);
		
		//Экспорт геометрии
		CaplStepData tmp_stdata;
		CaplDataBuf tmp_dbuf;
		CaplMap sr_pd_map;
		aplP21Header header;
		CString tmp; aplGetTempPath(tmp);
		tmp+=_T("step_out.stp");

		//newdata.ClearData();
		// Поиск и объединение документов
		for(k=0;k<a_c_pdf.Size;k++)
		{
			prgdlg.m_progress.SetPos(k);
			while (::PeekMessage(&msg, NULL, WM_PAINT,WM_PAINT, PM_REMOVE|PM_NOYIELD))DispatchMessage(&msg);

			CaplAggr docs;
			tmp_dbuf.Clear();
			tmp_stdata.ClearData();
			i_pdf=a_c_pdf[k];
			m_doc_data.GetAttrBN(i_pdf,S::of_product,i_prd);

			pd=(CaplInstance*)pdf_map.GetByIn((long)i_pd);
			// Поиск документа 
			buf.Format(_T("%i"),i_pdf->GetId());
			
			CaplInstance *doc=m_doc->m_api.m_doc_mgr.FindDocById(buf);
			CaplInstance *doc_rev,*doc_af;
			if(doc!=0)
			{
				// Слияние документа
				m_doc_data.GetAttrBN(doc,S::active,doc_rev);
				m_doc_data.GetAttrBN(doc_rev,S::access_form,doc_af);
				if(m_doc_data.NET_LoadBlobBN(doc_af,S::source,(TCHAR*)LPCTSTR(tmp)))
				{
					//if(tmp_stdata.LoadP21(tmp,header))
					if(tmp_stdata.LoadFromFile(tmp))
					{
						for(i=0;i<tmp_stdata.instances.Size;i++)
							tmp_stdata.instances[i]->SetId(0);
						tmp_stdata.SaveToDataBuf(tmp_dbuf);
						newdata.ApploadFromDataBuf(tmp_dbuf);
					}
					CFile::Remove(tmp);
				}
			}
		}

				
		// Удаление лишних SR и создание связей с PD
		aplExtent ext_rr,ext_sr,ext_sdr,ext_del;
		newdata.GetEntityExtentBN(_T("representation_relationship"),ext_rr);
		newdata.GetEntityExtentBN(_T("shape_representation"),ext_sr);
		newdata.GetEntityExtentBN(_T("shape_definition_representation"),ext_sdr);
		CaplInstance *sr,*pds,*inst01,*inst02;
		CaplMap sr_del_map;
		prgdlg.m_name.SetWindowText( APL_T("Оптимизация файла"));
		prgdlg.m_progress.SetRange32(0,ext_sdr.Size-1);
		for(i=0;i<ext_sdr.Size;i++)
		{
			prgdlg.m_progress.SetPos(i);

			newdata.GetAttrBN(ext_sdr[i],_T("used_representation"),sr);
			newdata.GetAttrBN(sr,S::name,id);

			// Удаление лишних SR
			for(j=0;j<ext_sr.Size;j++)
			{
				if(sr!=ext_sr[j])
				{
					newdata.GetAttrBN(ext_sr[j],S::name,buf);
					if(buf==id)
					{
						// Объединение SR
						sr_del_map.Add((long)ext_sr[j],(long)sr);
						ext_del.Add(ext_sr[j]);
						ext_sr.Remove(j);
						break;
					}
				}
			}
			// создание связей с PD
			k=_atoi(id);
			for(j=0;j<pdf_map.Size;j++)
			{
				if(((CaplInstance*)(pdf_map[j].in))->GetId()==k)
				{
					pds=newdata.CreateInstanceBN(_T("product_definition_shape"));
					newdata.PutAttrBN(ext_sdr[i],_T("definition"),pds);
					newdata.PutAttrBN(pds,_T("definition"),(CaplInstance*)(pdf_map[j].out));
					sr_pd_map.Add((long)sr,pdf_map[j].out);
					break;
				}
			}
		}
		// Замена атрибутов у RR
		for(i=0;i<ext_rr.Size;i++)
		{
			newdata.GetAttrBN(ext_rr[i],_T("rep_1"),inst0);
			inst01=(CaplInstance*)sr_del_map.GetByIn((long)inst0);
			if((inst01!=0)&&((long)inst01!=-1))
				newdata.PutAttrBN(ext_rr[i],_T("rep_1"),inst01);
			
			newdata.GetAttrBN(ext_rr[i],_T("rep_2"),inst0);
			inst01=(CaplInstance*)sr_del_map.GetByIn((long)inst0);
			if((inst01!=0)&&((long)inst01!=-1))
				newdata.PutAttrBN(ext_rr[i],_T("rep_2"),inst01);

			if(dlg.m_add_ass_axis_to_part==TRUE)
			{
				// Копирование системы координат сборки в деталь
				CaplInstance *idt,*axis;
				CaplAggr aggr0,aggr1;
				newdata.GetAttrBN(ext_rr[i],_T("transformation_operator"),idt);
				newdata.GetAttrBN(idt,_T("transform_item_1"),axis);
				newdata.GetAttrBN(ext_rr[i],_T("rep_1"),inst01);
				newdata.GetAttrBN(inst01,_T("items"),aggr0);
				aggr1.Add(axis);
				aggr1.Append(aggr0);
				newdata.PutAttrBN(inst01,_T("items"),aggr1);
			}
		}
		// Удаление лишних SR
		for(i=0;i<ext_del.Size;i++) newdata.DeleteInstance(ext_del[i]);

		// Создание связок cdsr
		prgdlg.m_progress.SetRange32(0,ext_rr.Size-1);
		
		aplExtent ext_acu;
		newdata.GetEntityExtentBN(S::assembly_component_usage,ext_acu);
		for(i=0;i<ext_rr.Size;i++)
		{
			prgdlg.m_progress.SetPos(i);

			newdata.GetAttrBN(ext_rr[i],_T("rep_1"),inst1);
			newdata.GetAttrBN(ext_rr[i],_T("rep_2"),inst2);
			inst1=(CaplInstance*)sr_pd_map.GetByIn((long)inst1);
			inst2=(CaplInstance*)sr_pd_map.GetByIn((long)inst2);
			for(j=0;j<ext_acu.Size;j++)
			{
				newdata.GetAttrBN(ext_acu[j],S::relating_pd,inst01);
				newdata.GetAttrBN(ext_acu[j],S::related_pd,inst02);
				if((inst01==inst2)&&(inst02==inst1))
				{
					CaplInstance *cdsr=newdata.CreateInstanceBN(_T("context_dependent_shape_representation"));
					pds=newdata.CreateInstanceBN(_T("product_definition_shape"));
					newdata.PutAttrBN(cdsr,_T("represented_product_relation"),pds);
					newdata.PutAttrBN(cdsr,_T("representation_relation"),ext_rr[i]);
					newdata.PutAttrBN(pds,_T("definition"),ext_acu[j]);
					ext_acu.Remove(j);
					break;
				}
			}
		}
	}
	//запись файла
	aplP21Header header;
	//newdata.SaveToTextFile(_T("_exp.000"));
	aplRusSaveMode rusmode=(aplRusSaveMode)dlg.m_text_coding_idx;
	StopBusy();
	
	while (::PeekMessage(&msg, NULL, WM_PAINT,WM_PAINT, PM_REMOVE|PM_NOYIELD))DispatchMessage(&msg);

	prgdlg.m_name.SetWindowText( APL_T("Сохранение файла"));
	if(!newdata.SaveP21(LPCTSTR(dlg.m_FileName),header,rusmode))AfxMessageBox( APL_T("Ошибка при сохранении!"));
	prgdlg.ShowWindow(FALSE);
	AfxMessageBox( APL_T("Экспорт завершен!"));
}

//****************************************************************
void CaplProductTreeItem::EportSpecific()
{
	if(m_doc==0) return;
	if(m_prd==0) return;
	if(m_pdf==0) return;

	CExportSpecificationDlg dlg; 
	dlg.m_item=this;
	dlg.DoModal();
}

void CaplProductTreeItem::ShowBOM()
{
	if(m_prd == 0 || m_pdf == 0) return;
	LoadProperties();
	DoShowContentsDialog(&(m_doc->m_api),m_pdf,1);
}
void CaplProductTreeItem::ShowExplosion()
{
	if(m_prd == 0 || m_pdf == 0) return;
	LoadProperties();
	DoShowContentsDialog(&(m_doc->m_api),m_pdf,0);
}
//****************************************************************

void CaplProductTreeItem::FindInContents(){
	m_doc->m_api.m_query_mgr.FindIntoContent(m_pdf);
}

//****************************************************************
void CaplProductTreeItem::CreateProject()
{
	if(m_doc==0) return;
	if(m_tree==0) return;
	if(m_prd==0) return;
	if(m_prd->GetType()==0) return;
	
	CaplInstance *inst=m_prd;
	if(m_pdf!=0)
	{
		if(m_pdf->GetType()==0) return;
		inst=m_pdf;
	}

	if(inst==0) return;
	if(inst->GetType()==0) return;
	if(inst->GetAccessmode()>=aplRO){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}
	CaplInstance *rel=0;
	
	CaplInstance *project=m_doc->m_project_mgr->CreateProject(0,0,false,inst,&rel);
	if(project && rel)
	{
		CaplProjectTreeItem *new_item=0;
		InsertInstInTree(project,m_item,m_doc,m_tree,m_all_projects,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0)new_item->m_rel=inst;
		MyExpand();
		m_doc->ChangeItem(0);m_doc->ChangeItem(this);
	}
}

bool CaplProductTreeItem::CreateSubstitute(CaplProductTreeItem *pitem, LPCTSTR subst_name, LPCTSTR subst_descr)
{
	if(!pitem) return false;

	//Проверяем состояние родительской сборки
	if(m_nauo==0) return false;

	CString state;
	CaplInstance *parentPdf;
	m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_pdr_r_ting,parentPdf);
	if(0==parentPdf)
	{
		AfxMessageBox( APL_T("Ошибочные данные!\\n\n(m_nauo.a_pdr_r_ting ==0)"),MB_ICONSTOP|MB_OK);
		return false;
	}
	m_doc_data.GetAttr(parentPdf,m_doc->m_api.m_prd_mgr.a_apl_pdf_state,state);
	if(state!=_T("working") && state!=_T("changing") && state!=_T(""))
	{
		AfxMessageBox( APL_T("Родительское иделие находится в состоянии \"")+m_doc->m_api.m_bp_mgr.GetWFStateName(state)+ APL_T("\".\n\n Замену в контексте сборки задать нельзя!"),MB_ICONSTOP|MB_OK);
		return false;
	}

	CaplInstance *par_pdf;
	m_doc_data.GetAttr(m_nauo,m_doc->m_api.m_prd_mgr.a_pdr_r_ting,par_pdf);
	bool b_NoPaste=false; 
	if(par_pdf==0) b_NoPaste=true;
	else if(par_pdf->GetType()==0) b_NoPaste=true;
	else if(par_pdf->GetAccessmode()>=aplRO) b_NoPaste=true;

	if(b_NoPaste)
	{
		aplErrorMessage(S::NoAccessRight(),par_pdf);
		return false;
	}


	CPrdRelationDlg dlg;
	dlg.m_prd_mgr=&(m_doc->m_api.m_prd_mgr);
	dlg.m_charact_mgr=&(m_doc->m_api.m_charact_mgr);
	dlg.m_mode=_T("Create Substitute");
	dlg.m_data=&(m_doc->m_api.m_data);
	dlg.m_in_pdf=m_pdf;
	dlg.m_in_prd=m_prd;
	dlg.m_out_pdf=pitem->m_pdf;
	dlg.m_out_prd=pitem->m_prd;
	dlg.m_nauo=m_nauo;
	dlg.m_pdr_name=subst_name;
	dlg.m_pdr_descr=subst_descr;

	if(dlg.DoModal()==IDOK)
	{
		if(dlg.m_subst)
		{
			InsertSubstItem(dlg.m_subst);
		}
	}
	return true;
}

void CaplProductTreeItem::RemoveSubst(bool delete_instance)
{
	if(!m_subst) return;
	for(int i=0;i<m_doc->m_items.Size;i++)
	{
		if(m_doc->m_items[i]!=this)
		{
			if(m_doc->m_items[i]->m_type==_T("Subst"))
			{
				CaplSubstTreeItem *item=(CaplSubstTreeItem*)m_doc->m_items[i];
				int item_num=item->m_substitutes.Find(m_subst);
				if(item_num>-1)
				{
					item->m_substitutes.Remove(item_num); 
					if(!item->m_substitutes.GetSize()) 
					{
						CaplProductTreeItem *p_item=(CaplProductTreeItem*)GetParentItem(item);
						if(p_item)
						{
							for(int j=0;j<p_item->m_all_substitutes.GetSize();j++)
							{
								if(p_item->m_all_substitutes[j]==item)
								{
									p_item->m_all_substitutes.RemoveAt(j);	
								}
							}
						}
						m_tree->DeleteItem(item->m_item);
					}
				}
			}
		}
	}
	if(delete_instance) m_doc_data.DeleteInstance(m_subst);	
}

void CaplProductTreeItem::InsertSubstItem(CaplInstance *subst)
{
	if(!subst) return;
	if(subst->GetAccessmode()>aplRO) return;
	if(!subst->GetType()) return;
	CString subst_name;
	m_doc_data.GetAttr(subst,m_doc->m_api.m_prd_mgr.a_pdf_subst_name,subst_name);
	CaplSubstTreeItem *subst_item=0;
	for(int j=0;j<m_all_substitutes.GetSize();j++)
	{
		if(!m_all_substitutes[j]) continue;
		if(subst_name==m_all_substitutes[j]->m_subst_name) 
		{
			subst_item=m_all_substitutes[j];
			break;
		}
	}
	if(!subst_item)
	{
		subst_item=new CaplSubstTreeItem(m_tree,m_doc,subst_name);
		subst_item->CreateTreeItem(m_item);
		subst_item->m_pdr=m_nauo;
		m_all_substitutes.Add(subst_item);
	}
	subst_item->Expand(TVE_COLLAPSE);
	subst_item->Expand(TVE_EXPAND);
	subst_item->RefreshItem();
	m_tree->Expand(subst_item->m_item,TVE_EXPAND);
	MyExpand(false);
}

