// aplDocTreeItem.cpp

#include "stdafx.h"
#include <finder.h>
#include "PSMDoc.h"
#include "resource.h"
#include "TreeProductItem.h"
#include "aplFolderTreeItem.h"
#include "aplTreeApprovalItem.h"
#include "aplTreeCharacteristicItem.h"
#include "aplCharacteristicGroupTreeItem.h"
#include "NavigatorView.h"
#include "aplTopLevelItem.h"
#include "aplDocTreeItem.h"
#include "aplBPTreeItem.h"
#include "TabView.h"
#include "aplProjectTreeItem.h"
#include "apl_prd_inst_item.h"
#include "aplDocCopyItem.h"

bool CaplDocTreeItem::m_bShowName = true;;
bool CaplDocTreeItem::m_bShowID = true;
bool CaplDocTreeItem::m_bShowActiveVersion = true;
bool CaplDocTreeItem::m_bShowType = true;
bool CaplDocTreeItem::m_bShowSelectAppDlg = false;
CString CaplDocTreeItem::m_EditPath;

#ifdef ENABLE_ASH_MO
	void WriteAshMoDBLog(CaplAPI *m_api,LPCSTR txt);
#endif

//****************************************************************
CaplDocTreeItem::CaplDocTreeItem(CTreeCtrl *tree, CPSMDoc *doc,
		CaplInstance *i_doc,CaplInstance *i_rel,CaplInstance *i_rev)
{
	m_type=APL_TREE_ITEM_DOCUMENT;
	m_tree=tree;
	m_doc=doc;
	m_inst=i_doc;
	m_rev=i_rev;
	m_rel=i_rel;
	m_pLockInfo=0;
	m_pDocItem=0;
	m_folder=0;
	m_classifier=0;
	m_par_item_docs_ext=0;
	m_project=0;
	m_has_version=false;
	m_bRefreshRevision=true;
	m_bWOForNote= false;
	bIsLock = false ;
	if(doc!=0) doc->m_items.Add(this);

}
//****************************************************************
void CaplDocTreeItem::ShowProperties()
{
	CaplInstance *inst;
	if(m_doc==0) return;
	if(m_inst==0) return;

	if(m_rev!=0) inst=m_rev; else inst=m_inst;

#ifdef ENABLE_ASH_MO
	{
		CString buf, sItemName, sUserName=_T("Неизвестный");
		CaplInstance *curuser=m_doc->m_api.m_appr_mgr.GetCurrentPerson();
		if(0!=curuser) m_doc->m_api.m_appr_mgr.GetPersonName(curuser,sUserName,false);
		m_doc->m_api.GetItemName(inst,sItemName);
		buf.Format(_T("\nПользователь %s открыл свойства документа %s"),sUserName,sItemName);
		WriteAshMoDBLog(&(m_doc->m_api),buf);
	}
#endif

	if(!m_rel || m_doc->m_api.m_data.IsKindOf(m_rel, m_doc->m_api.m_doc_mgr.e_apl_doc_ref))
	{
		if( m_doc->m_api.m_doc_mgr.ShowDocProperties(inst,m_rel))
		{
			RefreshAllThisDocItem();
		}
	}
	else
	{		
		if( m_doc->m_api.m_prd_inst_mgr.ShowPrdInstProperties(m_rev, m_rel))
		{
			RefreshAllThisDocItem();
		}
	}
}

// Сохраняет файл в версию блокиратор
bool SaveFileToDocRevision(CaplAPI &api, CaplInstance *doc, LPCTSTR file)
{
	if(doc==0) return false;
	if(file==0) return false;
	if(!api.m_data.IsKindOf(doc,api.m_doc_mgr.e_doc)) return false;

	CFileFind ff;
	if(FALSE==ff.FindFile(file))
	{
		AfxMessageBox( APL_T("Файл не найден"),MB_OK|MB_ICONSTOP);
		return false;
	}
	

	api.m_doc_mgr.LoadDocInfo(doc); // перечитываем информацию из БД, вдруг что-то изменилось
	if(doc->GetAccessmode()>=aplRO) 
	{
		AfxMessageBox( APL_T("Нет прав"),MB_OK|MB_ICONSTOP);
		return false;
	}

	CaplInstance *lock;
	api.m_data.GetAttr(doc,api.m_doc_mgr.a_apl_doc_lock, lock);
	if(lock==0)
	{
		AfxMessageBox( APL_T("Документ не взят на редактирование"),MB_OK|MB_ICONSTOP);
		return false;
	}
	
	// Проверяем этот ли пользователь взял на редактирование
	CaplInstance *pers1=0,*pers;
	CString buf;
	api.m_data.GetAttr(lock,api.m_doc_mgr.a_apl_doc_rev_autor,pers);
	if(pers!=0)
	{
		// Взято на редактирование не анонимным пользователем
		pers1=api.m_appr_mgr.GetCurrentPerson();
		if(pers!=pers1)
		{
			AfxMessageBox( APL_T("Документ взят на редактирование другим пользователем !"),MB_OK|MB_ICONSTOP);
			return false;
		}
	}
	else
	{
		api.m_data.GetAttr(lock,api.m_doc_mgr.a_apl_doc_rev_user,buf);
		if(buf!=api.m_data.GetNameCurrUser())
		{
			AfxMessageBox( APL_T("Документ взят на редактирование другим пользователем !"),MB_OK|MB_ICONSTOP);
			return false;
		}
	}

	// Пишем в версию

	CaplInstance *stor=0;
	api.m_data.GetAttr(lock,api.m_doc_mgr.a_apl_doc_rev_access_form,stor);
	if(stor==0)
	{
		// Создаем в БД новый файл
		stor=api.m_data.CreateInstance(api.m_doc_mgr.e_apl_stored_document);
		api.m_data.PutAttr(lock,api.m_doc_mgr.a_apl_doc_rev_access_form,stor);
	}
	int i;
	long code;
	CString fpath=file;
	i=fpath.ReverseFind(_T('\\'));
	if(i>=0) buf=fpath.Right(fpath.GetLength()-i-1); else buf=fpath;
	i=buf.ReverseFind(_T(':'));
	if(i>=0) buf=buf.Right(buf.GetLength()-i-1); 
	api.m_data.PutAttr(stor,api.m_doc_mgr.a_apl_stored_document_file_name,buf);
	api.m_data.NET_SaveBlob(stor,api.m_doc_mgr.a_apl_stored_document_source,fpath,code);
	
	api.SaveChanges();
	return true;
}

// Сохраняем файл из блокиратора на диск 
bool SaveLockerToFile(CaplAPI &api, CaplInstance *doc, LPCSTR path)
{
	if(doc==0) return false;
	if(path==0) return false;
	if(!api.m_data.IsKindOf(doc,api.m_doc_mgr.e_doc)) return false;

	api.m_doc_mgr.LoadDocInfo(doc); // перечитываем информацию из БД, вдруг что-то изменилось
	if(doc->GetAccessmode()>=aplRO) 
	{
		AfxMessageBox( APL_T("Нет прав"),MB_OK|MB_ICONSTOP);
		return false;
	}

	CaplInstance *lock;
	api.m_data.GetAttr(doc,api.m_doc_mgr.a_apl_doc_lock, lock);
	if(lock==0)
	{
		AfxMessageBox( APL_T("Документ не взят на редактирование"),MB_OK|MB_ICONSTOP);
		return false;
	}

	CaplInstance *stor=0;
	api.m_data.GetAttr(lock,api.m_doc_mgr.a_apl_doc_rev_access_form,stor);
	if(stor==0)
	{
		AfxMessageBox( APL_T("В блокираторе нет файла"),MB_OK|MB_ICONSTOP);
		return false;
	}

	// Определяем имя файла
	CString buf,fpath=path;
	api.m_data.GetAttr(stor,api.m_doc_mgr.a_apl_stored_document_file_name,buf);
	if(fpath==_T("")) fpath=buf;
	else if(fpath[fpath.GetLength()-1]==_T('\\')) fpath+=buf;
	
	return api.m_data.NET_LoadBlob(stor,api.m_doc_mgr.a_apl_stored_document_source,fpath);

}


//****************************************************************
bool CaplDocTreeItem::DeleteWrongLoadedDocument(CaplInstance *document)
{
	if(0 == document) 
		return false;
	if(!m_doc->m_api.m_data.IsKindOf(document, m_doc->m_api.m_doc_mgr.e_doc)) 
		return false;
	if(false == m_doc->m_api.m_appr_mgr.CheckPersonRole(m_doc->m_api.m_appr_mgr.GetCurrentPerson(), APL_T("Корректировщик архива"))
		&& m_doc->m_api.m_data.IsAdmin() == false)
		return false;	

	CaplAdminMode am(&m_doc->m_api.m_data, true, DEF_SOURCE);
	if(m_doc->m_api.m_doc_mgr.DeleteDoc(document))
	{
		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==m_type)
				{
					CaplDocTreeItem *item1=
						(CaplDocTreeItem*)m_doc->m_items[i];
					{
						if(item1->m_inst==m_inst)
						{m_doc->m_items.Remove(i); i--;}
					}
				}
			}
		}

		m_doc->m_items.Remove(m_doc->m_items.Find(this));
		return true;
	}		

	return false;
}

bool CaplDocTreeItem::TrackPopupMenu(CWnd *wnd, CPoint &point, UINT view_mode)
{
	CString sBuf;
	CaplInstance * inst;
	CMenu menu;  gSetPsmResourceHandle();
	VERIFY(menu.LoadMenu(IDR_TREE_CONTEXT_MENU));
// 	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));
	CaplMenu::Install(wnd); // 	VERIFY(CaplMenu::Install(wnd, ePopupMenu ));
    CMenu* pPopup = menu.GetSubMenu(INDEX_DOCUMENT_MENU);
    ASSERT(pPopup != NULL);
	if(pPopup==0) return false;
	
	aplExtent instances;
	GetAccessedInstances(instances);

	//Нет инстанса документа
	if ( !m_inst )
	{
		//Проверяем, что перед нами локер
		if ( instances.GetSize() && instances[0] )
		{
			CaplInstance* pBaseRev = NULL ;
			CaplInstance* pOfDoc = NULL ;
			m_doc->m_api.m_data.GetAttr ( instances[0], m_doc->m_api.m_doc_mgr.a_apl_doc_rev_base, pBaseRev ) ;
			
			//Если ревизия есть
			if ( pBaseRev )
			{
				m_doc->m_api.m_doc_mgr.LoadDocInfo( pBaseRev ) ;
				m_doc->m_api.m_data.GetAttr ( pBaseRev, m_doc->m_api.m_doc_mgr.a_apl_doc_rev_doc, pOfDoc ) ;

				//Если у неё есть OfDocument
				if ( pOfDoc )
				{
					CaplInstance* pLock = NULL ;
					m_doc->m_api.m_data.GetAttr ( pOfDoc, m_doc->m_api.m_doc_mgr.a_apl_doc_lock, pLock ) ;
					
					//Если у него есть замок
					if (pLock)
					{
						//Если это и есть инстанс с которого мы начинали
						if ( instances[0]->GetId() == pLock->GetId() )
						{
							//Значит документ записываем в m_inst
							bIsLock = true ;
							m_inst = pOfDoc ;
							m_rev = instances[0];
						}
					}
				}
			}
		}
	}


	CHECK_INSTANCE_ITEM_B(m_inst);

	CaplInstance *cur_doc_revision=m_rev;
	if(0==cur_doc_revision && 0!=m_inst) m_doc->m_api.m_data.GetAttr ( m_inst, m_doc->m_api.m_doc_mgr.a_apl_doc_active, cur_doc_revision ) ;
	
	AppendAddIn((CMenu*)pPopup);
	UpdateMenu((CMenu**)&pPopup, view_mode);
//---------------------------------Состояния-----------------------------------
	if(instances.GetSize() && instances[0] && m_doc_data.IsKindOf(instances[0],m_doc->m_api.m_doc_mgr.e_doc))
	{
		CStringArray states;
		CString val = m_doc->m_api.m_doc_mgr.GetPossibleWFState(m_inst,states);
			
			if(val==_T("approved"))
			{
				pPopup->EnableMenuItem(ID_REVISION_MAKE_ACTIVE,MF_BYCOMMAND|MF_GRAYED);
				//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_CHARACTERISTIC, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_BP, MF_BYCOMMAND | MF_GRAYED);
			}
			else if(val==_T("approving") || val==_T("approving_change"))
			{
				pPopup->EnableMenuItem(ID_REVISION_MAKE_ACTIVE,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_CHARACTERISTIC, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_BP, MF_BYCOMMAND | MF_GRAYED);
			}
			else if(val==_T("canceled"))
			{
				pPopup->EnableMenuItem(ID_REVISION_MAKE_ACTIVE,MF_BYCOMMAND|MF_GRAYED);
				pPopup->EnableMenuItem(ID_ITEM_CHECK_IN, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_ITEM_UNDO_CHECK_OUT, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_EDIT_DOCUMENT_AS, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_EDIT_DOCUMENT, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_ITEM_CHECK_OUT, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_DELETE_DOCUMENT_REL, MF_BYCOMMAND | MF_GRAYED);
				//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_CHARACTERISTIC, MF_BYCOMMAND | MF_GRAYED);
				pPopup->EnableMenuItem(ID_CREATE_BP, MF_BYCOMMAND | MF_GRAYED);
			}
	}
	else
	{
		// 09.10.2009 Нахимович: Не понятно зачем это было, но дизейблилась группа Показать для версии ????
#if _MSC_VER >= 1400
//		pPopup->EnableMenuItem(12, MF_BYPOSITION | MF_GRAYED | MF_DISABLED);
#else
//		pPopup->DeleteMenu(12, MF_BYPOSITION);
//		pPopup->DeleteMenu(12, MF_BYPOSITION);
#endif
	}
//---------------------------------Состояния-----------------------------------
	if(m_inst && m_inst->GetType()!=0)
		m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_lock,m_pLockInfo);
	if((m_pDocItem==0) && (m_rev!=0))
	{
		pPopup->RemoveMenu(ID_EDIT_DOCUMENT, MF_BYCOMMAND);
		pPopup->RemoveMenu(ID_EDIT_DOCUMENT_AS, MF_BYCOMMAND);
		pPopup->RemoveMenu(ID_ITEM_CHECK_OUT, MF_BYCOMMAND);
		pPopup->RemoveMenu(ID_ITEM_CHECK_IN, MF_BYCOMMAND);
		pPopup->RemoveMenu(ID_ITEM_UNDO_CHECK_OUT, MF_BYCOMMAND);

	}
	else
	{
		if (m_pLockInfo != NULL)
		{
			//pPopup->RemoveMenu(ID_EDIT_DOCUMENT, MF_BYCOMMAND);
			pPopup->RemoveMenu(ID_ITEM_CHECK_OUT, MF_BYCOMMAND);
		}
		else
		{
			pPopup->RemoveMenu(ID_ITEM_CHECK_IN, MF_BYCOMMAND);
			pPopup->RemoveMenu(ID_ITEM_UNDO_CHECK_OUT, MF_BYCOMMAND);
		}
	}

	if(m_rev==0)
	{
		// Документ
		pPopup->EnableMenuItem(ID_REVISION_MAKE_ACTIVE, MF_BYCOMMAND | MF_GRAYED);
		pPopup->RemoveMenu(ID_DOC_SHOW_DOC, MF_BYCOMMAND);
	}
	else
	{
		// Редакция
		pPopup->EnableMenuItem(ID_SHOW_ALL_VERSION, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_SHOW_ALL_VERSION_FROM_ACTIVE, MF_BYCOMMAND | MF_GRAYED);
		// версию нельзя чекинить и чекаутить - иначе при перерисовке дерева текущий item будет удален и PSM упадет! 
//		pPopup->EnableMenuItem(ID_ITEM_CHECK_IN, MF_BYCOMMAND | MF_GRAYED);
//		pPopup->EnableMenuItem(ID_ITEM_UNDO_CHECK_OUT, MF_BYCOMMAND | MF_GRAYED);
		if(m_rel==0)
			pPopup->EnableMenuItem(ID_DELETE_DOCUMENT_REL, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_SHOW_DOCUMENT_CHANGES, MF_BYCOMMAND | MF_GRAYED);
		if(m_pDocItem!=0)
		{
			if(m_pDocItem->m_pLockInfo!=0)
			{
//				pPopup->EnableMenuItem(ID_EDIT_DOCUMENT, MF_BYCOMMAND | MF_GRAYED);
//				pPopup->EnableMenuItem(ID_ITEM_CHECK_OUT, MF_BYCOMMAND | MF_GRAYED);
			}
		}

	}

	if(0==cur_doc_revision)
	{
		pPopup->EnableMenuItem(ID_SET_NEED_WORK, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_UNSET_NEED_WORK, MF_BYCOMMAND | MF_GRAYED);
	}
	else
	{
		bool b;
		m_doc->m_api.m_data.GetAttr(cur_doc_revision, m_doc->m_api.m_doc_mgr.a_apl_doc_rev_it_needs_work, b);
		if(b) pPopup->EnableMenuItem(ID_SET_NEED_WORK, MF_BYCOMMAND | MF_GRAYED);
		else pPopup->EnableMenuItem(ID_UNSET_NEED_WORK, MF_BYCOMMAND | MF_GRAYED);
	}

	if(m_rel==0 && m_project==0)
		pPopup->EnableMenuItem(ID_DELETE_DOCUMENT_REL, 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);}

	if (m_inst->GetAccessmode() != aplOWN)
		pPopup->EnableMenuItem(ID_DELETE, MF_BYCOMMAND | MF_GRAYED);

	if (bIsLock)
	{
		pPopup->EnableMenuItem(ID_ITEM_VIEW, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_ITEM_VIEW_AS, MF_BYCOMMAND | MF_DISABLED );
	    pPopup->EnableMenuItem(ID_EDIT_DOCUMENT, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_EDIT_DOCUMENT_AS, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_WINETD_SAVE, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_ITEM_CHECK_OUT, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_ITEM_CHECK_IN, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_ITEM_UNDO_CHECK_OUT, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_ALL_VERSION, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_ALL_VERSION_FROM_ACTIVE, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_DOC_SHOW_DOC, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_DOCUMENT_CHANGES, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_ALL_DOCS, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_ALL_CHARACTERISTIC, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_ALL_BP, MF_BYCOMMAND | MF_DISABLED );
	 	pPopup->EnableMenuItem(ID_SHOW_ALL_APPROVAL, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_DOCUMENT_SHOW_BASE_ITEMS, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_WHERE_USED_AS_COMPONENT, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_WHERE_USED_AS_COMPONENT_NOW, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_CONTAINED_FOLDER, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_CONTAINED_CLASSIFIER, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_CONTAINED_PROJECTS, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_CONTAINED_PROCCESS, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_CREATE_APPROVAL, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_CREATE_DOC, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_DOCUMENT_DEPENDENCE, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_CREATE_CHARACTERISTIC_GROUP, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_CREATE_BP, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_WFS_CHANGE, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_WFS_HISTORY, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_CREATE_NOTE, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_NOTES, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_CREATE_HARD_COPY, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_DOC_COPYES, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_HARD_COPYES, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_EDIT_COPY, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_EDIT_PASTE, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_OPEN_ITEM_IN_NEW_WINDOW, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_REVISION_MAKE_ACTIVE, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SUBSCRIPTION, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SET_INST_ACCSESS, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_FREZEE_INST, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SET_INST_OWNER, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_DELETE_DOCUMENT_REL, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_REMOVE_FROM_FOLDER, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_REMOVE_FROM_CLASSIFIER, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_DELETE, MF_BYCOMMAND | MF_DISABLED );
		pPopup->EnableMenuItem(ID_SHOW_PROPERTIES, MF_BYCOMMAND | MF_DISABLED );
	}

	if(false == m_doc->m_api.m_options_mgr.CheckInstallCode(_T("KVZ")))
	{
		pPopup->DeleteMenu(ID_DELETE_WRONG_LOADED, MF_BYCOMMAND);
	}
	else
	{
		if(false == m_doc->m_api.m_appr_mgr.CheckPersonRole(m_doc->m_api.m_appr_mgr.GetCurrentPerson(), APL_T("Корректировщик архива")) 
			&& m_doc->m_api.m_data.IsAdmin() == false)
		{
			pPopup->EnableMenuItem(ID_DELETE_WRONG_LOADED, MF_BYCOMMAND | MF_DISABLED );
		}
	}

	if(0!=m_inst)
	{
		CString buf;
		m_doc->m_api.m_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_apl_doc_system, buf );
		if(buf!=_T("GenerateESI")) pPopup->DeleteMenu(ID_COMPARE_ESI,MF_BYCOMMAND);
	}

	BOOL res = pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,
						point.x, point.y, wnd);
	switch (res)
	{
		case ID_SHOW_CONTAINED_PROJECTS:
			ShowContainedProjects(m_inst);
			break;
		case ID_SHOW_CONTAINED_PROCCESS:
			if(m_rev!=0) ShowContainedProccess(m_rev);
			else ShowContainedProccess(m_inst);
			break;
		case ID_WINETD_SAVE:			
			m_doc->m_exchng_mgr.SaveDocsToWinETDpackage(m_inst);
			break;

		case ID_SHOW_CONTAINED_FOLDER:
			ShowContainedFolder(m_inst);
			break;
		case ID_SHOW_CONTAINED_MESSAGE: ShowContainedMessage(m_inst); break;
		case ID_SHOW_CONTAINED_TASKS: ShowContainedTasks(m_inst); break;
		case ID_SHOW_CONTAINED_ALERT: ShowContainedAlert(m_inst); break;
		case ID_DELETE_WRONG_LOADED: DeleteWrongLoadedDocument(m_inst); break;

		case ID_SHOW_CONTAINED_CLASSIFIER:
			ShowContainedClassifier(m_inst);
			break;
		
		case ID_OPEN_ITEM_IN_NEW_WINDOW:
			if(m_rev!=0) m_doc->OpenInstanceInNewWindow(m_rev);
			else if(m_inst!=0) m_doc->OpenInstanceInNewWindow(m_inst);
		break;
		case ID_SHOW_ALL_VERSION:  ShowAllVersion(); break;
		case ID_SHOW_ALL_VERSION_FROM_ACTIVE:  ShowAllVersion(true,true); break;
		case ID_DOC_SHOW_DOC:
			{
				if(m_rev!=0)
				{
					CaplInstance* pDoc= NULL;
					m_doc->m_api.m_data.GetAttr(m_rev, m_doc->m_api.m_doc_mgr.a_apl_doc_rev_doc, pDoc);
					if(pDoc)
					{
						InsertInstInTree(pDoc, m_item, m_doc, m_tree, m_all_documents);
						MyExpand(false);
					}
				}
			}
			break;
		case ID_SHOW_DOCUMENT_CHANGES:m_doc->m_api.m_doc_mgr.ShowDocChanges(m_inst);break;
		case ID_CREATE_CHARACTERISTIC: CreateCharacteristic();break;
		case ID_CREATE_CHARACTERISTIC_GROUP: CreateCharacteristicGroup();break;
		case ID_GET_DOCUMENT_LAST_VERSION: GetDocumentLatestVersion();break;
		case ID_ITEM_VIEW: 
		case ID_ITEM_VIEW_AS: 
			{
				bool bShowSelPrg=false;
				if(res==ID_ITEM_VIEW_AS) bShowSelPrg=true;
				//++Колесников - работа с SolidWorks
				m_doc->m_api.m_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_system,sBuf);
				if (0==sBuf.CompareNoCase(_T("SolidWorks")))
				{
					if(IDNO == AfxMessageBox( APL_T("Данный документ был создан при помощи интеграции с SolidWorks.\nДальнейшая работа с ним может быть некорректной.\nПродолжить?"),MB_YESNO))
						break;
				}
				View(bShowSelPrg); 
			}
			break;
		case ID_ITEM_CHECK_IN: CheckIn(); break;
		case ID_ITEM_CHECK_OUT: CheckOut();break;
		case ID_EDIT_DOCUMENT: 
		case ID_EDIT_DOCUMENT_AS: 
			{
				bool b_openAs=false;
				if(res==ID_EDIT_DOCUMENT_AS) b_openAs=true;
				//++Колесников - работа с SolidWorks
				m_doc->m_api.m_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_system,sBuf);
				if (0==sBuf.CompareNoCase(_T("SolidWorks")))
				{
					if(IDNO == AfxMessageBox( APL_T("Данный документ был создан при помощи интеграции с SolidWorks.\nДальнейшая работа с ним может быть некорректной.\nПродолжить?"),MB_YESNO))
						break;
					if(m_rev!=0) 
						m_doc->m_api.m_doc_mgr.Edit(m_rev,ChangePathIfIntegration(m_inst),b_openAs);
						//m_doc->m_api.m_doc_mgr.Edit(m_rev,ChangePathIfIntegration(m_inst),m_bShowSelectAppDlg);
					else 
						m_doc->m_api.m_doc_mgr.Edit(m_inst,ChangePathIfIntegration(m_inst),b_openAs);
						//m_doc->m_api.m_doc_mgr.Edit(m_inst,ChangePathIfIntegration(m_inst),m_bShowSelectAppDlg);
				} 
				else //++ работа с обычным документом
				{
					if(m_rev!=0) 
						m_doc->m_api.m_doc_mgr.Edit(m_rev,m_EditPath,b_openAs);
						//m_doc->m_api.m_doc_mgr.Edit(m_rev,m_EditPath,m_bShowSelectAppDlg);
					else 
						m_doc->m_api.m_doc_mgr.Edit(m_inst,m_EditPath,b_openAs);
						//m_doc->m_api.m_doc_mgr.Edit(m_inst,m_EditPath,m_bShowSelectAppDlg);
				}
				RefreshAllDocItem();
			}
			break;
		case ID_ITEM_UNDO_CHECK_OUT: UndoCheckOut();break;
		case ID_REVISION_MAKE_ACTIVE:
			if(m_rev!=0)
			{
				if(m_inst->GetAccessmode()>aplRW)
				{
					aplErrorMessage(S::NoAccessRight(),m_inst);
					return true;
				}
				m_doc->m_api.m_doc_mgr.LoadDocInfo(m_inst);
				if(m_inst->GetType()==0)AfxMessageBox( APL_T("Документ был удален другим пользователем !"),MB_OK|MB_ICONSTOP);
				else if(m_rev->GetType()==0)AfxMessageBox( APL_T("Версия документа была удалена другим пользователем !"),MB_OK|MB_ICONSTOP);
				else
				{
					if(m_doc->m_api.m_doc_mgr.CreateChange(m_rev,true))
						RefreshAllThisDocItem();
				}
			}
			break;
		case ID_DELETE:
			if(m_rev!=0)
			{
				m_doc->m_api.m_doc_mgr.DeleteRevision(m_rev); RefreshAllThisDocItem();
			}
			else
			{
				if(m_doc->m_api.m_doc_mgr.DeleteDoc(m_inst))
				{
					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==m_type)
							{
								CaplDocTreeItem *item1=
									(CaplDocTreeItem*)m_doc->m_items[i];
								{
									if(item1->m_inst==m_inst)
									{m_doc->m_items.Remove(i); i--;}
								}
							}
						}
					}
					m_doc->m_items.Remove(m_doc->m_items.Find(this));
				}
			}
			break;
		case ID_DELETE_DOCUMENT_REL:
			if(m_rel!=0)
			{
				if(m_rel->GetAccessmode()>aplOWN)
				{
					AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);return true;
				}
				bool can_del=true;
				m_doc_data.GetAttr(m_rel,m_doc->m_api.m_doc_mgr.a_apl_doc_ref_item,inst);
				if(inst>0)
				{
					if(inst->GetAccessmode()>aplRW)
					{
						can_del=false;
						AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);
					}
					else if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_prd_mgr.e_pdf) || m_doc_data.IsKindOf(inst,m_doc->m_api.m_change_mgr.e_chng))
					{
						CString sState;
						bool bNeedCheck=false;
						if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_prd_mgr.e_pdf))
						{
							m_doc_data.GetAttr(inst,m_doc->m_api.m_prd_mgr.a_apl_pdf_state,sState);
							if(sState!=_T("working") && sState!=_T("changing")) bNeedCheck=true;

						}
						else if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_change_mgr.e_chng))
						{
							m_doc_data.GetAttr(inst,m_doc->m_api.m_change_mgr.a_chng_state,sState);
							if(sState!=_T("not_applied")) bNeedCheck=true;
						}

						if(bNeedCheck)
						{
							if(!m_doc_data.IsAdmin())
							{
								int opt=0;
								m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Настройка документов\\Запретить удаление связи с документами у неразрабатываемых изделий"),opt,0);
								if(1==opt)		
								{
									AfxMessageBox(APL_T("Запрещено удалять связь с нередактируемыми изделиями и пакетами изменений!"),MB_OK|MB_ICONSTOP);
									can_del=false;
								}
							}
						}
					}
				}
				if(can_del)
				{
					if(AfxMessageBox( APL_T("Вы действительно хотите удалить связь ?"),MB_YESNO)==IDYES)
					{
						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==m_type)
								{
									CaplDocTreeItem *item1=
										(CaplDocTreeItem*)m_doc->m_items[i];
									{
										if(item1->m_rel==m_rel)
										{m_doc->m_items.Remove(i); i--;}
									}
								}
							}
						}
						if(m_par_item_docs_ext!=0)
						{
							int i_d=m_par_item_docs_ext->Find(m_inst);
							if(i_d>=0)m_par_item_docs_ext->Remove(i_d);
						}
						m_doc_data.DeleteInstance(m_rel);
						m_doc_data.NET_SaveChanges();
						m_doc->m_items.Remove(m_doc->m_items.Find(this));
					}
				}
			}
			else if(m_project)
			{
 				if(AfxMessageBox( APL_T("Вы уверены ?"),MB_YESNO|MB_DEFBUTTON2)==IDYES) 
				{
					if(m_doc->m_project_mgr->DeleteAssociation(m_project,m_inst)) 
					{
						CaplProjectTreeItem *prj_item=(CaplProjectTreeItem*)GetParentItem(this);
						if(prj_item) prj_item->m_all_items.Remove(prj_item->m_all_items.Find(m_inst));
						m_doc->m_items.Remove(m_doc->m_items.Find(this));
					}
				}
			}
			break;
		case ID_REMOVE_FROM_FOLDER:
			if(m_folder!=0)
			{
				if(CaplFolderManager::m_create_assoc_folder_doc==TRUE){
					CaplInstance* association;
					association=m_doc->m_api.m_doc_mgr.FindAssociation(m_folder, m_inst);
					if(association!=0){
						m_doc->m_api.m_data.DeleteInstance(association);
						m_doc->m_items.Remove(m_doc->m_items.Find(this));
					}
				}
				else
				{
					if(m_doc->m_api.m_folder_mgr.RemoveFromFolder(m_folder,m_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;}
				if(m_doc->m_api.m_classifier_mgr.DeleteClassifierAssociation(m_inst,m_classifier))
					m_doc->m_items.Remove(m_doc->m_items.Find(this));
			}
			break;
		case ID_DOCUMENT_SHOW_BASE_ITEMS: ShowAllBaseObjects();break;
		case ID_SHOW_WHERE_USED_AS_COMPONENT: ShowWhereUsedAsComponent(true);break;
		case ID_SHOW_WHERE_USED_AS_COMPONENT_NOW: ShowWhereUsedAsComponent(false);break;
		case ID_CREATE_BP: CreateBP(m_inst);break;
		case ID_CREATE_REFUSAL: CreateRefusal(); break;
		case ID_SHOW_ALL_BP: ShowAllBPs(true); break;
		case ID_SUBSCRIPTION:
				m_doc->m_api.m_message_mgr.EditItemSubscribeList(m_inst);
			break;
		case ID_WFS_CHANGE:
			if(m_doc->m_api.m_doc_mgr.ChangeWFState(m_inst,_T("")))
			{
				m_doc->OnRefreshAllTreeItem();
			}
			break;
		case ID_WFS_HISTORY: m_doc->m_api.m_doc_mgr.ShowWFStateHistory(m_inst);
			break;
		case ID_DOCUMENT_DEPENDENCE: 
			{
				CaplInstance *rel;
				CaplInstance *doc = m_doc->m_api.m_doc_mgr.CreateDocument(0,0,0,0,0,true,m_inst,&rel,APL_DOCUMENT_DEPENDENCE);
				if(doc)
					ShowAllDocs();
					//RefreshAllThisDocItem();
				break;
			}
		case ID_CREATE_HARD_COPY:
			{
				CreateHardCopy();
				break;
			}
		case ID_SHOW_HARD_COPYES:
			{
				ShowAllHardCopyes(true);
				break;
			}
		case ID_SHOW_DOC_COPYES:
			{
				ShowAllHardCopyes(true,true);
				break;
			}
		case ID_SHOW_CARD_ACCOUNT:
			{
				m_doc->m_api.m_doc_mgr.ShowCardAccount(m_inst, false);
				break;
			}
		case ID_COMPARE_ESI:
			if(0!=m_rev) m_doc->m_api.m_prd_mgr.CompareDocWintESI(m_rev);
			else m_doc->m_api.m_prd_mgr.CompareDocWintESI(m_inst);
			break;

		case ID_SET_NEED_WORK:  if(m_doc->m_api.m_appr_mgr.SetNeedWork4DocRevision(cur_doc_revision,true))RefreshAllThisDocItem(); break;
		case ID_UNSET_NEED_WORK:  if(m_doc->m_api.m_appr_mgr.SetNeedWork4DocRevision(cur_doc_revision,false))RefreshAllThisDocItem(); break;

		case ID_CREATE_WF_PROCESS:
			{
				aplExtent prots, wos;

				if(0!=m_rev) wos.Add(m_rev);
				else wos.Add(m_inst);

				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 CaplDocTreeItem::View(bool bShowSelectPtogram)
{
	if(m_pLockInfo && m_rev==0)
	{
		CaplInstance* pers= NULL;
		m_doc->m_api.m_data.GetAttr(m_pLockInfo, m_doc->m_api.m_doc_mgr.a_apl_doc_rev_autor, pers);
		CaplInstance* lockPers= m_doc->m_api.m_appr_mgr.GetCurrentPerson();
		
		CString buf;
		m_doc->m_api.m_data.GetAttr(m_pLockInfo, m_doc->m_api.m_doc_mgr.a_apl_doc_rev_user, buf);

		if((lockPers && pers && lockPers==pers) || (buf==m_doc->m_api.m_data.GetNameCurrUser()))
		{
			if(IDYES==AfxMessageBox( APL_T("Документ редактируется Вами. Открыть текущий вариант редакции документа с жесткого диска?"), MB_YESNO|MB_ICONQUESTION))
			{
				CString fpath;
				m_doc->m_api.m_data.GetAttr(m_pLockInfo, m_doc->m_api.m_doc_mgr.a_apl_doc_rev_edit_path, fpath);
				HANDLE hProcess=m_doc->m_api.m_doc_mgr.RunFile(fpath, bShowSelectPtogram);
				return;
			}
		}
	}

	CaplInstance *inst4view=m_rev;
	if(0==inst4view) inst4view=m_inst;
	m_doc->m_api.m_doc_mgr.View(inst4view,bShowSelectPtogram);
}

void CaplDocTreeItem::GetDocumentLatestVersion()
{
	if(0==m_inst) return;
	//++Колесников - работа с SolidWorks
	CString sBuf;
	m_doc->m_api.m_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_system,sBuf);
	if (0==sBuf.CompareNoCase(_T("SolidWorks")))
	{
		if(IDNO == AfxMessageBox( APL_T("Данный документ был создан при помощи интеграции с SolidWorks.\nДальнейшая работа с ним может быть некорректной.\nПродолжить?"),MB_YESNO))
			return;
		if(m_rev!=0) 
			m_doc->m_api.m_doc_mgr.LoadRevision(m_rev,ChangePathIfIntegration(m_inst));
		else 
			m_doc->m_api.m_doc_mgr.LoadRevision(m_inst,ChangePathIfIntegration(m_inst));
	}
	else //++ работа с обычным документом
	{
		if(m_rev!=0) 
			m_doc->m_api.m_doc_mgr.LoadRevision(m_rev,0);
		else 
			m_doc->m_api.m_doc_mgr.LoadRevision(m_inst,0);
	}

#ifdef ENABLE_ASH_MO
	{
		CaplInstance *inst=m_inst;
		if(0!=m_rev) inst=m_rev;
		CString buf, sItemName, sUserName=_T("Неизвестный");
		CaplInstance *curuser=m_doc->m_api.m_appr_mgr.GetCurrentPerson();
		if(0!=curuser) m_doc->m_api.m_appr_mgr.GetPersonName(curuser,sUserName,false);
		m_doc->m_api.GetItemName(inst,sItemName);
		buf.Format(_T("\nПользователь %s Сохранил на диск документ %s"),sUserName,sItemName);
		WriteAshMoDBLog(&(m_doc->m_api),buf);
	}
#endif
}

void CaplDocTreeItem::CheckIn()
{
	//Определяем галочку "сделать версию активной"
	bool bSetActive=false;

	if(m_inst!=0)
	{
		CString buf;
		m_doc->m_api.m_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_wf_state,buf);
		if(buf.IsEmpty() || buf== _T("working")) bSetActive=true;
	}

	// обрабатываем
	
	if(m_doc->m_api.m_doc_mgr.CheckInEx(m_inst,0,bSetActive, true))
	{
		m_doc->m_tab_view->Update(this, true);
		RefreshAllDocItem();
		
		if(1 == IsExpandet())
		{
			Expand(1);
			MyExpand(true);
		}

	}
}
void CaplDocTreeItem::CheckOut()
{
	CString sBuf;
	CaplInstance *inst;
	bool bRes = false;
	if(m_doc==0) return;

	if(m_rev!=0) 
		inst=m_rev;
	else
		inst=m_inst;



	//++Колесников - это безобразие необходимо для корректной работы PSM с интеграцией
	m_doc->m_api.m_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_system,sBuf);
	if (0==sBuf.CompareNoCase(_T("SolidWorks")))
	{
		if(IDNO == AfxMessageBox( APL_T("Данный документ был создан при помощи интеграции с SolidWorks.\nДальнейшая работа с ним может быть некорректной.\nПродолжить?"),MB_YESNO))
			return;
		bRes = m_doc->m_api.m_doc_mgr.CheckOutEx(inst,ChangePathIfIntegration(m_inst),true);
	}
	else
		bRes = m_doc->m_api.m_doc_mgr.CheckOutEx(inst,m_EditPath,true);

	//было if(m_doc->m_api.m_doc_mgr.CheckOutEx(inst,m_EditPath,true))
	if(bRes)
	{
		if(m_doc->m_tab_view)
		{
			m_doc->m_tab_view->Update(this, true);
			RefreshAllDocItem();
			if(1 == IsExpandet())
			{
				Expand(1);
				MyExpand(true);
			}
		}
	}
}
void CaplDocTreeItem::UndoCheckOut()
{
	if(m_doc->m_api.m_doc_mgr.UndoCheckOutEx(m_inst))
	{
		m_doc->m_tab_view->Update(this, true);
		RefreshAllDocItem();
		if(1 == IsExpandet())
		{
			Expand(1);
			MyExpand(true);
		}

	}
}
//****************************************************************
void CaplDocTreeItem::ShowCmd(long cmd)
{
	switch (cmd)
	{
		case ID_CREATE_CHARACTERISTIC: CreateCharacteristic(); break;
		case ID_SHOW_ALL_VERSION:  ShowAllVersion(); break;
		case ID_SHOW_ALL_CONTENTS:  Expand(2); MyExpand(); break;
		case ID_SHOW_ALL_BP: ShowAllBPs(true); break;
		case ID_EXPAND_ALL: {int i=1; ExpandAll(i);} break;
		case ID_ITEM_VIEW: View(false); break;
		case ID_ITEM_VIEW_AS: View(true); break;
		case ID_ITEM_CHECK_IN: CheckIn(); break;
		case ID_ITEM_CHECK_OUT: CheckOut(); break;
		case ID_ITEM_UNDO_CHECK_OUT: UndoCheckOut(); break;
		case ID_CREATE_BP: CreateBP(m_inst);break;
		case ID_SHOW_HARD_COPYES:ShowAllHardCopyes(true);break;
		case ID_SHOW_DOC_COPYES:ShowAllHardCopyes(true,true);break;
		case ID_GET_DOCUMENT_LAST_VERSION: GetDocumentLatestVersion();break;
		case ID_SHOW_DOCUMENT_CHANGES: m_doc->m_api.m_doc_mgr.ShowDocChanges(m_inst);break;
		default: PrepareContextMenu(cmd);break;
	}
}

BOOL CaplDocTreeItem::ShowToolBarButton(CCmdUI* pCmdUI)
{
//---------------------------------Состояния-----------------------------------
	CStringArray states;
	if(m_inst==0)return FALSE;
	if(m_inst->GetType()==0)return FALSE;

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

	CString val = m_doc->m_api.m_doc_mgr.GetPossibleWFState(m_inst,states);
		if(val==_T("approved"))
		{
			if(pCmdUI->m_nID==ID_REVISION_MAKE_ACTIVE) return FALSE;
			//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;
		}
		else if(val==_T("approving_change"))
		{
			if(pCmdUI->m_nID==ID_REVISION_MAKE_ACTIVE) 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;
		}
		else if(val==_T("canceled"))
		{
			if(pCmdUI->m_nID==ID_REVISION_MAKE_ACTIVE) return FALSE;
			if(pCmdUI->m_nID==ID_ITEM_CHECK_IN) return FALSE;
			if(pCmdUI->m_nID==ID_ITEM_UNDO_CHECK_OUT) return FALSE;
			if(pCmdUI->m_nID==ID_EDIT_DOCUMENT) return FALSE;
			if(pCmdUI->m_nID==ID_EDIT_DOCUMENT_AS) return FALSE;
			if(pCmdUI->m_nID==ID_ITEM_CHECK_OUT) return FALSE;
			if(pCmdUI->m_nID==ID_DELETE_DOCUMENT_REL) return FALSE;
			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_SHOW_ALL_VERSION)
	{
		if(m_rev!=0) return FALSE;
		pCmdUI->Enable(TRUE); return TRUE;
	}
	if(pCmdUI->m_nID==ID_GET_DOCUMENT_LAST_VERSION)
	{
		pCmdUI->Enable(TRUE); return TRUE;
	}
	if(pCmdUI->m_nID==ID_SHOW_DOCUMENT_CHANGES)
	{
		pCmdUI->Enable(TRUE); return TRUE;
	}	
	if(pCmdUI->m_nID==ID_SHOW_HARD_COPYES)
	{
		if(m_rev!=0) return FALSE;
	}
	if((m_pDocItem==0) && (m_rev!=0))
	{
		if(pCmdUI->m_nID==ID_ITEM_CHECK_OUT)	return FALSE;
		if(pCmdUI->m_nID==ID_ITEM_UNDO_CHECK_OUT)  return FALSE;
		if(pCmdUI->m_nID==ID_ITEM_CHECK_IN)  return FALSE;
	}
	else
	{
		if (m_pLockInfo != NULL)
		{
			if(pCmdUI->m_nID==ID_ITEM_CHECK_OUT)	return FALSE;
		}
		else
		{
			if(pCmdUI->m_nID==ID_ITEM_UNDO_CHECK_OUT)  return FALSE;
			if(pCmdUI->m_nID==ID_ITEM_CHECK_IN)  return FALSE;
		}
	}

	switch(pCmdUI->m_nID)
	{
	case ID_SHOW_ALL_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_CHARACTERISTIC:
	case ID_CREATE_DOC:
	case ID_CREATE_BP:
	case ID_ITEM_VIEW:
	case ID_ITEM_VIEW_AS:
	case ID_ITEM_CHECK_OUT:
	case ID_ITEM_CHECK_IN:
	case ID_ITEM_UNDO_CHECK_OUT:
	case ID_SHOW_NOTES:
	case ID_CREATE_NOTE:
	case ID_SHOW_HARD_COPYES:
		pCmdUI->Enable(TRUE); return TRUE; break;
	}
	return FALSE;
}
//****************************************************************
bool CaplDocTreeItem::GetName(CString &name)
{
//	name=_T("Doc");
	name=_T("???");
	_APL_TREE_ITEM_CHEK_PARAM_BOOL

	HTREEITEM hParItem= m_tree->GetParentItem(m_item);;
	CaplTreeItem* parItem= NULL;
	if(hParItem)
		parItem= (CaplTreeItem*)m_tree->GetItemData(hParItem);
	
	CString buf;
	if((m_rev!=0)/*&&(m_pDocItem!=0)*/)
	{
		CHECK_GET_NAME(m_rev);
		if(m_rel && m_doc->m_api.m_data.IsKindOf(m_rel, m_doc->m_api.m_prd_inst_mgr.e_apl_component))
		{
			m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_doc_id, name);
			m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_doc_name, buf);
			if(!buf.IsEmpty()){if(!name.IsEmpty())name+=_T(" : "); name+=buf;}	
			m_doc_data.GetAttr(m_rev,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_label,buf);
			if(!buf.IsEmpty()){if(!name.IsEmpty())name+=_T(" : "); name+=buf;}
			m_doc_data.GetAttr(m_rel,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_date_installed,buf);
			if(buf!=_T(""))
			{
				name+=_T(" (");
				COleDateTime odt;
				aplString2Date(buf,odt);
				buf=odt.Format(_T("%d.%m.%Y"));
				name+=buf;
				
				m_doc_data.GetAttr(m_rel,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_date_removed,buf);
				if(buf!=_T(""))
				{
					aplString2Date(buf,odt);
					buf=odt.Format(_T(" - %d.%m.%Y"));
					name+=buf;
				}
				name+=_T(")");
			}
			aplExtent rel_contexts;
			m_doc_data.GetAttr(m_rel,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_frames_of_reference,rel_contexts);
			m_doc->m_api.m_prd_inst_mgr.PrintItemContextInString(rel_contexts,buf);
			if(buf!=_T(""))	{ name+=_T(" ["); name+=buf; name+=_T("]");}			
		}
		else
		{
			if(m_rev->GetAccessmode() <= aplRO)
			{
				m_doc_data.GetAttr(m_rev,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_id,name);
				m_doc_data.GetAttr(m_rev,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_litera,buf);
				if(!buf.IsEmpty()){if(!name.IsEmpty())name+=_T(" : "); name+=buf;}
				m_doc_data.GetAttr(m_rev,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_label,buf);
				if(!buf.IsEmpty()){if(!name.IsEmpty())name+=_T(" : "); name+=buf;}
			}

			if(parItem && parItem->m_type!=APL_TREE_ITEM_DOCUMENT)
			{
				CaplInstance* doc= NULL;
				m_doc->m_api.m_data.GetAttr(m_rev, m_doc->m_api.m_doc_mgr.a_apl_doc_rev_doc, doc);
				if(doc)
				{
					name+=_T("  [");
					m_doc->m_api.GetItemName(doc,buf);
					name+=buf;
					name+=_T("]");
				}
			}
			
			CaplInstance *src_ver;
			m_doc_data.GetAttr(m_rev,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_src_doc_ver,src_ver);
			if(src_ver!=0)
			{
				if(src_ver->attrs== NULL)
					m_doc->m_api.m_doc_mgr.LoadDocInfo(src_ver);
				m_doc->m_api.GetItemName(src_ver,buf);
				name+= APL_T("  [Исх: ");
				name+=buf;
				name+=_T("]");
			}
		}
		
		return true;
	}
	
	if(m_inst!=0)
	{	
		m_doc->m_api.GetItemName(m_inst,name);

/*	
		if(m_inst->GetType()==0) return false;
		if(m_inst->GetAccessmode()<=aplRO)
		{
		if(m_bShowID)
			{
				 m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_id,buf);
				 name=buf;
			} 
			if(m_bShowName)
			{
				 m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_name,buf);
				 if(name!=_T("")) name+=_T(" : ");
				 name+=buf;
			} 
			if(m_bShowActiveVersion)
			{
				CaplInstance *rev;
				m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_active,rev);
				if(rev!=0)
				{
					m_doc_data.GetAttr(rev,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_id,buf);
					if(name!=_T("")) name+=_T(" : ");
					name+=buf;
				}
			} 
			if(m_bShowType)
			{
				CaplInstance *type;
				m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_kind,type);
				if(type!=0)
				{
					m_doc_data.GetAttrBN(type,S::product_data_type,buf);
					if(name!=_T("")) name+=_T(" : ");
					name+=buf;
				}
			}
		}*/
	}
	if(name==_T(""))name=_T("???");
	if(m_rev!=0)
	{
		m_doc_data.GetAttr(m_rev,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_id,buf);
		name+= APL_T(" : Вер. ") + buf;		
	}

	if(m_inst)
	{
		CaplInstance *activeRev = 0;
		m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_apl_doc_active, activeRev);

		if(activeRev && m_doc->m_api.m_options_mgr.CheckInstallCode(_T("kvz")) && activeRev->GetAccessmode() <= aplRO)
		{
			CString label;
			m_doc_data.GetAttr(activeRev, m_doc->m_api.m_doc_mgr.a_apl_doc_rev_label, label);

			if(0==label.CompareNoCase(_T("ПР")) || 0==label.CompareNoCase(_T("АНН")) || 0==label.CompareNoCase(_T("ПР-утвер")))
				name = APL_T("ПРОЕКТ ") + name;
		}
	}

	return true;
}
//****************************************************************
bool CaplDocTreeItem::CreateTreeItem(HTREEITEM parent_item)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	CString buf;
	GetName(buf);
	InsetItem(buf,ICON_DOCUMENT,parent_item);
	if(m_rev==0)
	{
		m_fictive_item=m_tree->InsertItem(_T("fictive"),0,0,m_item);
		m_expanded=false;
	}
	else m_expanded=true;
	RefreshItem();
	return true;
}

//****************************************************************
bool CaplDocTreeItem::RefreshItem()
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	CString name;
	GetName(name);
	UINT ico;
	ico = m_doc->m_api.GetInstIco(m_inst);
	if(m_inst!=0)
	{
		if(m_inst->GetType()==0)
		{
			
			m_tree->SetItemText(m_item,name);
			return false;
		}
		else
		{
		//для обновления кнопок
			m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_apl_doc_lock, m_pLockInfo);
			if(m_inst->GetAccessmode()<=aplRO)
			{
				if(m_rev!=0)
				{
					ico = m_doc->m_api.GetInstIco(m_rev);
					if(m_pDocItem!=0) 
					{
						m_pDocItem->m_bRefreshRevision=false;
						m_pDocItem->RefreshItem();
						m_pDocItem->m_bRefreshRevision=true;
					}
				}
				else
				{
					ico = m_doc->m_api.GetInstIco(m_inst);
					if(m_has_version)
					{if(m_bRefreshRevision){ HideAllVersion();	ShowAllVersion();}}
				}
			}
		}
	}
	
	if(m_rel!=0 && m_doc->m_api.m_data.IsKindOf(m_rel, m_doc->m_api.m_prd_inst_mgr.e_apl_component))
	{
		CString buf;
		m_doc_data.GetAttr(m_rel, m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_date_removed,buf);
		if(buf!=_T(""))
		{
//			SetItemImage(ICO_EFF_NOT_USED, IDX_IL_TREE_EFF);
			color=RGB(128,128,128);
			font_style|=APL_FONT_STRIKEOUT;
		}
	}
	if(m_rel!=0)
	{
		CString buf;
		m_doc_data.GetAttr(m_rel, m_doc->m_api.m_doc_mgr.a_apl_doc_ref_end_date, buf);
		if(buf!=_T(""))
		{
//			SetItemImage(ICO_EFF_NOT_USED, IDX_IL_TREE_EFF);
			color=RGB(128,128,128);
			font_style|=APL_FONT_STRIKEOUT;
		}
	}
	
	SetItemImage(ico, IDX_IL_TREE_ITEM);

	if(m_rev==0)
	{
		CString state;
		int state_ico=-1;
		m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_apl_doc_wf_state, state);

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

	if(m_rel)
	{
		CString buf;
		m_doc_data.GetAttr(m_rel, m_doc->m_api.m_doc_mgr.a_apl_doc_ref_type,buf);
		if(buf==APL_DOC_DEPENDENCE) 
			SetItemImage(ICO_REL_DEPEND_DOC, IDX_IL_TREE_REL_TYPE);
	}

	if(m_bWOForNote)
		SetItemImage(ICO_REL_WO_4NOTE, IDX_IL_TREE_REL_TYPE);

	CString sExtRefGuid;
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_external_ref, sExtRefGuid);
	if(!sExtRefGuid.IsEmpty()) SetItemImage(ICO_SUBTYPE_HAS_REF, IDX_IL_TREE_ITEM_SUBTYPE);
	else SetItemImage(-1, IDX_IL_TREE_ITEM_SUBTYPE);


	m_tree->SetItemText(m_item,name);
//	if(m_rev==0)
	{
//		if(m_tree->EnsureVisible(m_item)==FALSE) m_tree->SelectSetFirstVisible(m_item);
	}
	m_tree->RedrawWindow();
	if(m_doc->m_tab_view->m_item_old==this) 
		m_doc->ChangeItem(this);

	// цвет текста элемента
	ChangeTextColor();

	return true;
}
//****************************************************************
bool CaplDocTreeItem::ChangeTextColor()
{
	color = RGB(0, 0, 0);

	if(m_doc->m_api.m_options_mgr.CheckInstallCode(_T("KVZ"))) 
	{
		CaplInstance *activeRevision = 0;
		m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_apl_doc_active, activeRevision);

		if(activeRevision && activeRevision->GetAccessmode() <= aplRO)
		{
			CString label;
			m_doc_data.GetAttr(activeRevision, m_doc->m_api.m_doc_mgr.a_apl_doc_rev_label, label);

			if(0==label.CompareNoCase(APL_NO_T("ПР")) || 0==label.CompareNoCase(APL_NO_T("АНН")) || 0==label.CompareNoCase(APL_NO_T("ПР-утвер")))
				color = RGB(255, 0, 0);
		}

		m_tree->Invalidate();
	}
		
	return true;
}
//****************************************************************
bool CaplDocTreeItem::RefreshAllDocItem()
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
//	int i;
//	m_tree->SetRedraw(FALSE);
//	for(i=0;i<m_doc->m_items.Size;i++)
//	{
//		if(m_doc->m_items[i]->m_type==APL_TREE_ITEM_DOCUMENT) m_doc->m_items[i]->RefreshItem();
//	}
//	m_tree->SetRedraw();
	m_doc->RefreshAllItemsByType(APL_TREE_ITEM_DOCUMENT);
	return true;
}
//****************************************************************
bool CaplDocTreeItem::RefreshAllThisDocItem()
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	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_DOCUMENT)
			{
				CaplDocTreeItem *item=(CaplDocTreeItem*)m_doc->m_items[i];
				if((item->m_inst==m_inst)&&(item->m_rev==0))
				{
					if(m_pDocItem!=item)item->RefreshItem();
				}
			}
		}
	}
	if(m_pDocItem==0)RefreshItem();
	else m_pDocItem->RefreshItem();
	return true;
}

//****************************************************************
void CaplDocTreeItem::InsertRevisionInTree(aplExtent &ext_rev,CaplDocTreeItem *docitem, aplExtent *ext_approval)
{
	_APL_TREE_ITEM_CHEK_PARAM_VOID
	// вызов подверсий
	CaplInstance *inst;
	m_pDocItem=docitem;

	int i;
	aplExtent ext_sub_rev; // Версии входящие в текущий item


	for(i=0;i<ext_rev.Size;i++)
	{
		if(0==ext_rev[i])  {ext_rev.Remove(i); i--; continue;}
		if(0==ext_rev[i]->GetType()) {ext_rev.Remove(i); i--;continue;} 
		m_doc_data.GetAttr(ext_rev[i],m_doc->m_api.m_doc_mgr.a_apl_doc_rev_base,inst);
		if(inst==m_rev)
		{
			ext_sub_rev.Add(ext_rev[i]);
			ext_rev.Remove(i);
			i--;
		}
	}

	for(i=0;i<ext_sub_rev.Size;i++)
	{
		CaplInstance *rev_i=ext_sub_rev[i];
		CaplDocTreeItem *doc_item=
			new CaplDocTreeItem(m_tree, m_doc, m_inst,0,rev_i);
		if(m_pDocItem==0) doc_item->m_pDocItem=this;
		else doc_item->m_pDocItem=m_pDocItem;
		doc_item->CreateTreeItem(m_item);
		if(CPSMDoc::m_auto_show_sign_in_doc_ver) doc_item->ShowAllApproval(false,ext_approval);	
		doc_item->InsertRevisionInTree(ext_rev,docitem,ext_approval);
	}
	if(ext_sub_rev.GetSize()>0) { Sort();m_tree->Expand(m_item,TVE_EXPAND);}
}
//****************************************************************
void CaplDocTreeItem::ShowAllVersion(bool showMsg, bool bFromActive)
{
	_APL_TREE_ITEM_CHEK_PARAM_VOID
	
	if(m_has_version) HideAllVersion();
	if(m_inst->GetAccessmode()>aplRO) return;
	int i;
	CaplInstance *inst;
	aplExtent ext_rev, top_rev,ext_approval;
	StartBusy();
	m_doc->m_api.m_doc_mgr.LoadAllDocumentRevision(m_inst,ext_rev);

	if(bFromActive) // Убираем все, которые до активной
	{
		CaplInstance *act;
		m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_active,act);

		if(0!=act)
		{
			apl_id id_act=act->GetId();

			for(i=0;i<ext_rev.Size;i++)
			{
				CaplInstance *rev=ext_rev[i];
				if(act==rev) continue;
				if(rev->GetId()<id_act)
				{
					ext_rev.Remove(i);
					i--;
				}
			}
		}
	}

	m_doc->m_api.m_appr_mgr.LoadItemApproval(ext_rev,ext_approval,true);
	StopBusy();

	CSortClass::SortExtentByInst(ext_rev);

	// Определение верхнего уровня
	for(i=0;i<ext_rev.Size;i++)
	{
		if(ext_rev[i]==0) continue;
		if(ext_rev[i]->GetType()==0) continue;
		m_doc_data.GetAttr(ext_rev[i],m_doc->m_api.m_doc_mgr.a_apl_doc_rev_base,inst);
		if(inst==0){ top_rev.Add(ext_rev[i]);}
		else if(inst->GetAccessmode()>aplRO){ top_rev.Add(ext_rev[i]);}
		else
		{
			if(aplQFindInstInExtent(ext_rev,inst,true)==-1){top_rev.Add(ext_rev[i]);} //Если родительская версия - не пойми что, то кидаем в корень
		}
	}
	// Составление дерева
	if(m_bShowNoFoundMessage && showMsg) m_tree->SetRedraw(FALSE);
	for(i=0;i<top_rev.Size;i++)
	{
		CaplDocTreeItem *doc_item=
			new CaplDocTreeItem(m_tree, m_doc, m_inst, 0,top_rev[i]);
		doc_item->m_pDocItem=this;
		doc_item->CreateTreeItem(m_item);
		if(CPSMDoc::m_auto_show_sign_in_doc_ver) doc_item->ShowAllApproval(false,&ext_approval);
		doc_item->InsertRevisionInTree(ext_rev,this,&ext_approval);
		m_tree->Expand(doc_item->m_item,TVE_EXPAND);
	}

	m_has_version=true;
	if(showMsg)	MyExpand(false);
	if(m_bShowNoFoundMessage && showMsg) m_tree->SetRedraw(TRUE);
	m_tree->Select(m_item,TVGN_FIRSTVISIBLE);
}

//****************************************************************
bool CaplDocTreeItem::ShowInListCtrl(CListCtrl *list)
{
	if(list==0) return false;
	CHECK_SHOW_LIST_CTRL(m_inst);
	if(m_doc==0)return false;
	if(m_doc->m_BShowInListCtrl==false) return true;

	COleDateTime odt;
	CString buf,buf1;
	CaplInstance *inst_po;
	CaplInstance *stor=0,*ver=0,*type=0;
	int i,j;
	__int64 size_file=-1;

	if(m_inst->GetAccessmode()<=aplRO)
	{
		if(m_doc_data.IsKindOf(m_inst,m_doc->m_api.m_doc_mgr.e_apl_stored_document))
		{
			list->InsertItem(list->GetItemCount(), APL_T("Файл в БД"));

			i=list->InsertItem(list->GetItemCount(), APL_T("Файл:"));
			buf= _T("");
			if(m_inst)m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_apl_stored_document_file_name, buf);
			list->SetItemText(i,1,buf);

			if(!m_doc_data.NET_GetBlobSize(m_inst,m_doc->m_api.m_doc_mgr.a_apl_stored_document_source,size_file))
			{
				// мало ли почему ошибка, вдруг документ удалили или изменили в другом клиенте
				m_doc->m_api.m_doc_mgr.LoadDocInfo(m_inst);
			}

			i=list->InsertItem(list->GetItemCount(), APL_T("Размер:"));
			buf.Format(_T("%i"),size_file);
			list->SetItemText(i,1,buf);

			aplExtent ext; ext.Add(m_inst);
			ShowInstanceInfoInListCtrl(ext,list,0);
			return true;
		}
		else if(m_doc_data.IsKindOf(m_inst,m_doc->m_api.m_doc_mgr.e_apl_assigned_document))
		{
			list->InsertItem(list->GetItemCount(), APL_T("Файл на диске"));

			i=list->InsertItem(list->GetItemCount(), APL_T("Файл:"));
			buf= _T("");
			if(m_inst)m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_apl_assigned_document_location_path, buf);
			list->SetItemText(0,1,buf);

			m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_assigned_document_location_path,buf);
			CFileStatus status;
			if(CFile::GetStatus(buf,status)) size_file=(long)status.m_size;
	
			i=list->InsertItem(list->GetItemCount(), APL_T("Размер:"));
			buf.Format(_T("%i"),size_file);
			list->SetItemText(i,1,buf);

			aplExtent ext; ext.Add(m_inst);
			ShowInstanceInfoInListCtrl(ext,list,0);
			return  true;
		}

		i=list->InsertItem(0, APL_T("Обозначение:"));
		buf= _T("");
		if(m_inst)m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_doc_id, buf);
		list->SetItemText(i,1,buf);

		i=list->InsertItem(1, APL_T("Наименование:"));
		buf= _T("");
		if(m_inst)m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_doc_name, buf);
		list->SetItemText(i,1,buf);
		
		i=list->InsertItem(2, APL_T("Код:"));
		buf= _T("");
		if(m_inst)m_doc_data.GetAttr(m_inst, m_doc->m_api.m_doc_mgr.a_doc_code, buf);
		list->SetItemText(i, 1, buf);

		i=list->InsertItem(3, APL_T("Описание:"));
		buf= _T("");
		m_doc_data.GetAttrBN(m_inst,S::description,buf);
		list->SetItemText(i,1,buf);

		i=list->InsertItem(4, APL_T("Вид:"));
		if(m_inst)m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_kind,type);
		buf=_T("");
		if(type!=0 && type->GetAccessmode()!=aplNO) m_doc_data.GetAttr(type, m_doc->m_api.m_doc_mgr.a_dt_pdt,buf);
		list->SetItemText(i,1,buf);

		
		if(m_inst)m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_inv_num,buf);
		if(buf!=_T(""))
		{
			i=list->InsertItem(list->GetItemCount(),_T(""));
			i=list->InsertItem(list->GetItemCount(), APL_T("Инвентарный номер:"));
			list->SetItemText(i,1,buf);
		}
	}

	if(m_rel)
	{
		i=list->InsertItem(list->GetItemCount(),_T(""));
		i=list->InsertItem(list->GetItemCount(), APL_T("Тип зависимости:"));
		m_doc_data.GetAttr(m_rel,m_doc->m_api.m_doc_mgr.a_apl_doc_ref_type,buf);
		if(buf==APL_DOC_DEPENDENCE) buf=  APL_T("Исходный документ");
		else buf=  APL_T("Связанный документ");
		i=list->SetItemText(i,1,buf);
	}

	if(m_rev!=0) ver=m_rev;
	else
	{
		if(m_inst)if(m_inst->GetAccessmode()<=aplRO)if(m_inst)m_doc_data.GetAttrBN(m_inst,S::active,ver);
	}
		
	if(ver!=0 && ver->GetAccessmode()<aplNO)
	{
		if(m_inst->GetAccessmode()<=aplRO)
		{
			// сначала выполняем обращение к БД - на случай если документ удалили
			m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_access_form,stor);
			if(stor!=0 && stor->GetType()!=0)
			{
				if(m_doc_data.IsKindOf(stor,m_doc->m_api.m_doc_mgr.e_apl_stored_document))
				{
					bool bOldHM = m_doc_data.SetHideMode(true);
					if(!m_doc_data.NET_GetBlobSize(stor,m_doc->m_api.m_doc_mgr.a_apl_stored_document_source,size_file))
					{
						// мало ли почему ошибка, вдруг документ удалили или изменили в другом клиенте
						m_doc->m_api.m_doc_mgr.LoadDocInfo(m_inst);
						size_file=-1;
					}
					m_doc_data.SetHideMode(bOldHM);
				}
				else if(m_doc_data.IsKindOf(stor,m_doc->m_api.m_doc_mgr.e_apl_assigned_document))
				{
					m_doc_data.GetAttr(stor,m_doc->m_api.m_doc_mgr.a_apl_assigned_document_location_path,buf);
					CFileStatus status;
					if(CFile::GetStatus(buf,status)) size_file=(long)status.m_size;
				}
			}
			if(m_inst->GetType()==0)
			{
				i=list->InsertItem(0, APL_T("Ошибка: документ удален!"));
				return true;
			}

			i=list->InsertItem(list->GetItemCount(),_T(""));
			CString state;state.Empty();
			m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_wf_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(""));

			i=list->InsertItem(list->GetItemCount(), APL_T("Версия:"));
			if(ver->GetType()!=0 && ver->GetAccessmode()<aplNO)
			{
				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_id,buf);
				list->SetItemText(i,1,buf);

				i=list->InsertItem(list->GetItemCount(), APL_T("Описание версии:"));
				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_descr,buf);
				list->SetItemText(i,1,buf);	
				
				i=list->InsertItem(list->GetItemCount(), APL_T("Версия исходного документа:"));
				CaplInstance *src_ver;
				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_src_doc_ver,src_ver);
				if(src_ver!=0)
				{
					if(src_ver->GetType()!=0 && src_ver->GetAccessmode()<=aplRO)
					m_doc->m_api.GetItemName(src_ver,buf);
					list->SetItemText(i,1,buf);
				}

				i=list->InsertItem(list->GetItemCount(), APL_T("Формат:"));
				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_format,buf);
				list->SetItemText(i,1,buf);	


				i=list->InsertItem(list->GetItemCount(), APL_T("Оператор:"));
				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_user,buf);
				
				/*
				CaplInstance *po;
				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_autor,po);
				if(po!=0)
				{
					m_doc->m_api.m_appr_mgr.GetPersonName(po,buf1);
					m_doc->m_api.GetItemName(po,buf1);
					if(buf1!=_T(""))
					{
						buf1 +=_T(" ("); buf1 +=buf; buf1 +=_T(")"); buf=buf1;
					}
				}*/
				list->SetItemText(i,1,buf);

				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_end_s,buf);
				if(buf!=_T(""))
				{
					i=list->InsertItem(list->GetItemCount(), APL_T("Дата создания:"));
					aplString2Date(buf,odt);	
					buf=odt.Format(_T("%d.%m.%Y  %H:%M:%S"));
					list->SetItemText(i,1,buf);
				}

				m_doc->m_api.m_doc_mgr.GetFileName(ver,buf);
				i=list->InsertItem(list->GetItemCount(), APL_T("Файл:"));
				list->SetItemText(i,1,buf);
				
				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_crc,j);
				i=list->InsertItem(list->GetItemCount(),_T("CRC32:"));
				buf.Format(_T("%08X"),j);
				list->SetItemText(i,1,buf);

				i=list->InsertItem(list->GetItemCount(), APL_T("Размер:"));
				if(size_file>=0) buf.Format(_T("%I64i"),size_file);
				else buf=APL_T("Ошибка определения размера. Скорее всего, BLOB отсутствует ав БД.");
				list->SetItemText(i,1,buf);

				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_src_author,inst_po);
				if(inst_po!=0){
					//m_doc->m_api.m_appr_mgr.GetPersonName(inst_po,buf,true);
					m_doc->m_api.GetItemName(inst_po,buf);
					if(buf!=_T(""))
					{
						i=list->InsertItem(list->GetItemCount(), APL_T("Автор источника:"));
						list->SetItemText(i,1,buf);
						list->SetItemData(i,(long)inst_po);
					}
				}
				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_src_date,buf);
				if(buf!=_T(""))
				{
					i=list->InsertItem(list->GetItemCount(), APL_T("Дата источника:"));
					aplString2Date(buf,odt);	
					buf=odt.Format(_T("%d.%m.%Y  %H:%M:%S"));
					list->SetItemText(i,1,buf);
				}
				m_doc_data.GetAttr(ver,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_language,buf);
				if(buf!=_T(""))
				{
					i=list->InsertItem(list->GetItemCount(), APL_T("Язык:"));
					list->SetItemText(i,1,buf);
				}
			}else{
				list->SetItemText(i,1, APL_T("Ошибка: версия удалена"));
			}
		}
	}
	if(m_inst)m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_lock,m_pLockInfo);
	if(m_pLockInfo!=0)
	{
		i=list->InsertItem(list->GetItemCount(),_T(""));

		m_doc_data.GetAttr(m_pLockInfo,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_start_s,buf);
		if(buf!=_T(""))
		{
			i=list->InsertItem(list->GetItemCount(), APL_T("Начало редактирования:"));
			aplString2Date(buf,odt);	
			buf=odt.Format(_T("%d.%m.%Y  %H:%M:%S"));
			list->SetItemText(i,1,buf);
		}

		i=list->InsertItem(list->GetItemCount(), APL_T("Редактирует:"));
		m_doc_data.GetAttr(m_pLockInfo,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_user,buf);
		list->SetItemText(i,1,buf);

		i=list->InsertItem(list->GetItemCount(), APL_T("Компьютер:"));
		m_doc_data.GetAttr(m_pLockInfo,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_stored_on,buf);
		list->SetItemText(i,1,buf);
		
		i=list->InsertItem(list->GetItemCount(), APL_T("Путь:"));
		m_doc_data.GetAttr(m_pLockInfo,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_edit_path,buf);
		list->SetItemText(i,1,buf);

		i=list->InsertItem(list->GetItemCount(), APL_T("Комментарий:"));
		m_doc_data.GetAttr(m_pLockInfo,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_descr,buf);
		list->SetItemText(i,1,buf);

	}

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

	i=list->InsertItem(list->GetItemCount(), APL_T("Доступ к документу:"));
	GetAccessName(m_inst,buf);
	list->SetItemText(i,1,buf);

	if(m_rev!=0)
	{
		i=list->InsertItem(list->GetItemCount(), APL_T("Доступ к версии:"));
		GetAccessName(m_rev,buf);
		list->SetItemText(i,1,buf);
	}
	if(m_project)
	{
		CaplInstance *rel=m_doc->m_project_mgr->FindAssociation(m_project,m_inst);
		if(rel) 
		{
			CaplInstance *control_status=0;
			m_doc_data.GetAttr(rel,m_doc->m_project_mgr->a_project_ref_control_status,control_status);
			CString buf0= APL_T("Рабочий объект");
			if(control_status) buf0= APL_T("Контрольный объект");
			list->InsertItem(list->GetItemCount(),_T(""));
			i=list->InsertItem(list->GetItemCount(), APL_T("Тип объекта:"));
			list->SetItemText(i,1,buf0);
			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,buf0);
				list->SetItemText(i,1,buf0);
			}
		}
	}

	aplExtent ext;
	CStringArray comment;
	if(m_inst!=0){ comment.Add( APL_T("Документ")); ext.Add(m_inst);}
	if(ver!=0){ comment.Add( APL_T("Версия")); ext.Add(ver);}
	if(m_rel!=0){ comment.Add( APL_T("Связь")); ext.Add(m_rel);}
	if(type!=0){ comment.Add( APL_T("Тип")); ext.Add(type);}
	if(stor!=0){ comment.Add(_T("Stored")); ext.Add(stor);}
	if(m_pLockInfo!=0){ comment.Add(_T("Locker")); ext.Add(m_pLockInfo);}
	if(m_classifier!=0){
		CaplInstance* classif_ref;
		m_doc->m_api.m_classifier_mgr.TestClassifierAssociation(m_inst,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);
	}
	ShowInstanceInfoInListCtrl(ext,list,&comment);

	return true;
}
//****************************************************************
void CaplDocTreeItem::HideAllVersion()
{
	_APL_TREE_ITEM_CHEK_PARAM_VOID

	int i;
	//m_tree->SelectItem(m_item);
	m_tree->Select(m_item,TVGN_CARET);
	m_tree->Select(m_item,TVGN_DROPHILITE);
	m_tree->SetRedraw(FALSE);
	for(i=0;i<m_doc->m_items.Size;i++)
	{
		if(m_doc->m_items[i]->m_type==APL_TREE_ITEM_DOCUMENT)
		{
			CaplDocTreeItem *item=(CaplDocTreeItem*)m_doc->m_items[i];
			if(item->m_pDocItem==this) {m_doc->m_items.Remove(i); i--;}
		}
	}
	m_tree->SetRedraw(TRUE);
	m_has_version=false;
}
//****************************************************************
bool CaplDocTreeItem::Expand(UINT action)
{
	if(m_rev!=0)return true;
	if (action == TVE_COLLAPSE)
	{
		CollapseItem();
		HideAllVersion();
		m_all_copyes.Clear();
		m_all_base_objects.Clear();
		m_all_parent_prd_inst.Clear();
	}
	else if (action == TVE_EXPAND)
	{
		if(m_expanded) return true;
		if(m_hasSubItem)Expand(1);
		m_tree->SetRedraw(FALSE);
		bool bOldVal=m_bShowNoFoundMessage;
		m_bShowNoFoundMessage=false;
		if(m_ShowContentsOnExpand) ShowAllDocs(false);
		m_bShowNoFoundMessage=bOldVal;
		if(m_fictive_item!=0)
		{
			m_tree->DeleteItem(m_fictive_item);
			m_fictive_item=0;
		}
			bool old = m_bShowNoFoundMessage;
			m_bShowNoFoundMessage = old;
			m_ExecMyExpand = true;
			if(m_doc->m_auto_expand_items.m_showintree_doc&APL_SHOW_CHARACT)
				ShowAllCharacteristic(false);
			if(m_doc->m_auto_expand_items.m_showintree_doc&APL_SHOW_APPROVAL)
				ShowAllApproval(false);
			if(m_doc->m_auto_expand_items.m_showintree_doc&APL_SHOW_BP)
				ShowAllBPs(false);
			if(m_doc->m_auto_expand_items.m_showintree_doc&APL_SHOW_VER)
				ShowAllVersion(FALSE);
		
			//if(m_doc->m_api.m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие")))
			{
				ShowAllBaseObjects(m_doc->m_wf_mgr.e_proc_tmpl);
			}
			m_bShowNoFoundMessage = old;
			m_ExecMyExpand = true;
		Sort();
		m_tree->SetRedraw(TRUE);
		m_expanded=true;
	}
	return true;
}

//****************************************************************
bool CaplDocTreeItem::InsertDoc(CPSMDoc *doc, CaplTreeItem *item,
					aplExtent *exist_items, CaplInstance *i_doc,CaplInstance *i_obj, bool add)
{
	if(doc==0) return false;
	if(item==0) return false;
	if(i_doc==0) return false;
	if(i_obj==0) return false;
	if(i_obj->GetType()==0) return false;
	if(i_obj->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight(),i_obj);return false;};

	if(exist_items==0) return false;
	
	if(!doc->m_api.m_data.TestCycleInRelationBN(_T("apl_document_reference"),_T("item"),_T("assigned_document"),i_obj,i_doc))
	{
		AfxMessageBox( APL_T("Создание данной связи недопустимо!"));
		return false;
	}

	CaplInstance *rel=doc->m_api.m_doc_mgr.CreateAssociation(i_obj,i_doc);
	if(rel==0) return false;

	bool found=false;
	for(int j=0;j<exist_items->Size;j++)
	{
		if((*exist_items)[j]==i_doc){found=true; break;}
	}
	if(!found && add)
	{
		CaplDocTreeItem *doc_item= new CaplDocTreeItem(item->m_tree,doc,i_doc,rel);
		doc_item->CreateTreeItem(item->m_item);
		exist_items->Add(i_doc);
		doc_item->m_par_item_docs_ext=exist_items;
	}
	return true;
}
//****************************************************************
void CaplDocTreeItem::GetAccessedInstances(aplExtent &ext)
{
	ext.Clear();
//	CaplInstance* stor;
	m_doc->m_api.m_doc_mgr.LoadDocInfo(m_inst);
	if(m_rev!=0)
	{
		if(m_rev->GetType()!=0)
		{
			ext.Add(m_rev);
//			DIV: раньше был баг - stor проверялся, но добавлялся опять m_rev. А 20_01_2009 по указанию ЯАИ баг был исправлен, а кусок - закомментарен
// 			m_doc_data.GetAttr(m_rev,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_access_form,stor);
// 			if(stor!=0){
// 				if(stor->GetType()!=0){ext.Add(stor);}
// 			}
		}
		//DIV: раньше в экстент включался и relation. Удалено
	}
	else
	{
		if(m_inst->GetType()!=0) 
			ext.Add(m_inst);
		//DIV: раньше в экстент включался и relation. Удалено
	}
}

void CaplDocTreeItem::GetMainInstances(aplExtent &ext)
{
	ext.Clear();
	if(m_rev!=0)
	{
		if(m_rev->GetType()!=0)
			ext.Add(m_rev);
	}
	else 
	{
		if(m_inst->GetType()!=0) 
			ext.Add(m_inst);	
	}

	if(m_rel)
	{
		if(m_rel->GetType()!=0) 
			ext.Add(m_rel);	
	}
}

//*****************************************************************************
bool CaplDocTreeItem::PasteFile(LPCTSTR file, CPoint *point)
{
	if(file==0) return false;

	CMenu menu;  gSetPsmResourceHandle();
	VERIFY(menu.LoadMenu(IDR_PASTE_ITEM_MENU));
// 	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));
	CaplMenu::Install(m_tree); // 	VERIFY(CaplMenu::Install(m_tree, ePopupMenu ));
	CMenu *pPopup = menu.GetSubMenu(INDEX_PASTE_FILE_MENU);
	if(pPopup==0) return false;
	
	//if(m_pLockInfo==0)
	//		pPopup->EnableMenuItem(ID_CREATE_DOC_VER,MF_BYCOMMAND|MF_GRAYED);


	CPoint point1;
	if(0==point)
	{
		RECT rect;
		m_tree->GetItemRect(m_item,&rect,TRUE);
		m_tree->ClientToScreen(&rect);
		point1.x=rect.right;
		point1.y=rect.bottom;
		point=&point1;
	}

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

	if(res==ID_CREATE_DOC_VER)
	{
		if(m_pLockInfo!=0)
		{
			if(m_doc->m_api.m_doc_mgr.CheckInEx(m_inst,file,true,true)) RefreshAllThisDocItem();
		}
		else
		{
			if(m_doc->m_api.m_doc_mgr.CreateDocumentRevision(m_inst,file,true,true,m_rev,true)) RefreshAllThisDocItem();
		}
	}
	else if(res==ID_CREATE_DOC)
	{
		CreateDoc(m_inst,file);
	}
	return true;
}
//****************************************************************
bool CaplDocTreeItem::PasteItem(CaplTreeItem *item, CPoint *point)
{
	if(item==0) return false;
	if(m_tree==0) return false;
	if(m_doc==0) return false;
	if(m_inst==0) return false;
	if(m_inst->GetType()==0) return false;


	CString state;
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_wf_state,state);
	if(state!=_T("") && state!=_T("working") && state!=_T("changing"))
	{
		AfxMessageBox( APL_T("Документ находится в состоянии \"")+m_doc->m_api.m_bp_mgr.GetWFStateName(state)+ APL_T("\" и не может быть изменен"));
		return false;
	}
	if (item->m_type==APL_TREE_ITEM_DOCUMENT)
	{
		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 ));

		//if(item->m_type == APL_TREE_ITEM_PRODUCT)
		//	pPopup = menu.GetSubMenu(INDEX_PRODUCT_MENU);
		//else 
		if(item->m_type == APL_TREE_ITEM_DOCUMENT)
		{

			aplExtent ext;
			item->GetAccessedInstances(ext);
			if(m_doc_data.IsKindOf(ext[0],m_doc->m_api.m_doc_mgr.e_apl_doc_rev) &&
				m_rel && m_doc_data.IsKindOf(m_rel, m_doc->m_api.m_prd_inst_mgr.e_apl_component) &&
				m_rev)
			{
				pPopup= menu.GetSubMenu(INDEX_PROJECT_PASTE_MENU+1);			
				pPopup->RemoveMenu(ID_DOCUMENT_REV_PAST, MF_BYCOMMAND);
			}
			else
			{
				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);
			}
		}
		else if((item->m_type == APL_TREE_ITEM_CHARACTERISTIC)||(item->m_type == APL_TREE_ITEM_CHARACTERISTICGROUP))
			pPopup = menu.GetSubMenu(INDEX_CHARACTERISTIC_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;
			}

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

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

			// Вставка документа
			if (res == ID_DOCUMENT_COPY)
			{
				CaplInstance *inst=0;
				if(m_rev!=0) inst=m_rev;
				else inst=m_inst;
				if(inst==0) return false;

				CaplInstance *i_doc=((CaplDocTreeItem *)item)->m_inst;
				
				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();

				}
				
				if(m_inst->GetAccessmode()>aplRW || access>aplRO)
				{
					AfxMessageBox( APL_T("Нет доступа к объекту"));
					return false;
				}
				if(i_doc==m_inst)
				{
					AfxMessageBox( APL_T("Ссылка документа на самого себя не допустима !!!"),MB_OK|MB_ICONSTOP);
					return true;
				}
				if(CaplDocTreeItem::InsertDoc(m_doc,this,&m_all_documents,i_doc,inst, false))
					ShowAllDocs();
				return true;
			}
			else if(res == ID_DOCUMENT_BYDOT)
			{
				CaplInstance *i_doc = ((CaplDocTreeItem *)item)->m_inst;
				
				aplExtent instances;
				GetAccessedInstances(instances);
				if(m_doc->m_api.m_doc_mgr.CreateDocumentByDot(i_doc,instances[0]))
					ShowAllDocs();
			}
			//премещение документа
			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);
				
				return CaplDocTreeItem::MoveDocument(m_doc, d_item, parent_item, this);
			}
			else if(res == ID_DOCUMENT_INITIAL)
			{
				aplExtent ext, inst;
				item->GetAccessedInstances(ext);
				GetAccessedInstances(inst);
				if(ext[0]==inst[0])
				{
					AfxMessageBox( APL_T("Ссылка документа на самого себя не допустима!"));
					return false;
				}
				if(!m_doc->m_api.m_data.TestCycleInRelationBN(_T("apl_document_reference"),_T("item"),_T("assigned_document"),inst[0],ext[0]))
				{
					AfxMessageBox( APL_T("Создание данной связи недопустимо!"));
					return false;
				}
				if(m_doc->m_api.m_doc_mgr.CreateAssociation(inst[0],ext[0],0,0,APL_DOCUMENT_DEPENDENCE))
				{
					CString access_template;
					m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Назначать доступ\\Шаблон доступа при назначении документа исходным"),access_template);
					if(!access_template.IsEmpty())
					{
						aplExtent ext_access;
						ext_access.Add(ext[0]);
						m_doc->m_api.m_data.NET_SetAccessFromPatternName(&ext_access,access_template);
					}
					ShowAllDocs();
				}

			}
			else if(res==ID_DOCUMENT_REV_REPLACE)
			{
				if(m_rev!=((CaplDocTreeItem *)item)->m_rev)
				{					
					CString sDateRem= _T("");
					m_doc_data.GetAttr(m_rel, m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_date_removed, sDateRem);
					if(sDateRem.IsEmpty())
					{
						CaplAttrValue tst_values[3];
						aplExtent ext;

						tst_values[0].value.Set(((CaplPrdInstTreeItem*)GetParentItem(this))->m_inst);
						tst_values[0].attr= m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_relating;

						tst_values[1].value.Set(((CaplDocTreeItem *)item)->m_rev);
						tst_values[1].attr= m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_related;
						
						sDateRem= _T("");
						tst_values[2].value.Set(sDateRem);
						tst_values[2].attr= m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_date_removed;

						m_doc_data.NET_FindInstancesWithAttrValues(m_doc->m_api.m_prd_inst_mgr.e_apl_component,3,&tst_values[0],ext,true);
						
						COleDateTime odt;
						CString sDate;
						m_doc->m_api.m_data.NET_GetServerDateTime(odt);
						aplDate2String(odt, sDate);
						
						CaplInstance *rel= NULL;
						for(int i= 0; i<ext.GetSize(); i++)
						{
							m_doc_data.GetAttr(ext[i], m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_date_removed, sDateRem);
							if(sDateRem.IsEmpty())	{rel= ext[i];break;}
						}

						if(!rel)
						{
							rel= m_doc_data.CreateInstance(m_doc->m_api.m_prd_inst_mgr.e_apl_component);
							CaplInstance* pi_ing= NULL;
							m_doc_data.GetAttr(m_rel, m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_relating, pi_ing);
							
							m_doc_data.PutAttr(rel, m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_relating, pi_ing);
							m_doc_data.PutAttr(rel, m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_related, ((CaplDocTreeItem *)item)->m_rev);					
							m_doc_data.PutAttr(rel, m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_date_installed, sDate);
						}
						
						m_doc_data.GetAttr(m_rel, m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_date_removed, sDateRem);
						if(sDateRem.IsEmpty())
						{
							m_doc_data.PutAttr(m_rel, m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_date_removed, sDate);

							CaplInstance* subst= m_doc->m_api.m_data.CreateInstance(m_doc->m_api.m_prd_inst_mgr.e_pi_subst);
							m_doc->m_api.m_data.PutAttr(subst, m_doc->m_api.m_prd_inst_mgr.a_pi_subst_predecessor, m_rel);
							m_doc->m_api.m_data.PutAttr(subst, m_doc->m_api.m_prd_inst_mgr.a_pi_subst_successor, rel);				
							
							RefreshItem();
						}				

						CaplDocTreeItem *inst_item= new CaplDocTreeItem(m_tree, m_doc, 
							((CaplDocTreeItem *)item)->m_inst, rel, ((CaplDocTreeItem *)item)->m_rev);
						inst_item->m_project= NULL;
						inst_item->CreateTreeItem(m_tree->GetParentItem(m_item));
	//					m_all_prd_instances.Add(ext_rel[i]);
						inst_item->RefreshItem();
						m_doc_data.NET_SaveChanges();					
					}	
				}
			}
		}
	}
	if(item->m_type == APL_TREE_ITEM_CHARACTERISTIC||item->m_type == APL_TREE_ITEM_CHARACTERISTICGROUP)
	{
		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 ));
		pPopup = menu.GetSubMenu(INDEX_CHARACTERISTIC_MENU);
		if(pPopup==0) return false;
		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;
		}

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

		// Вставка характеристики
		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);
			}
		}
	}
	m_tree->RedrawWindow();
	return false;
}
//*****************************************************************************

void CaplDocTreeItem::CopyDataToDataSource(CMyOleDataSource *pSource)
{
	if(pSource==0) return;

	CString file_name;
	CaplInstance *inst=m_inst;
	if(m_rev!=0)inst=m_rev;
	m_doc->m_api.m_doc_mgr.GetFileName(inst,file_name);
	pSource->m_doc=m_doc;
	pSource->m_inst=inst;
	pSource->m_item=this;
	if(m_pLockInfo!=0)pSource->m_bNoEdit=true;

	//UINT cf_fn=RegisterClipboardFormat(CFSTR_FILENAME);	
	UINT cf_fc=RegisterClipboardFormat(CFSTR_FILECONTENTS);	
	UINT cf_fd=RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR);

	pSource->DelayRenderData(cf_fc);
	
	STGMEDIUM stm;
	memset((void far *)&stm,0,sizeof(stm));
	stm.tymed = TYMED_HGLOBAL;

	FORMATETC fe;
	memset((void far *)&fe,0,sizeof(fe));
	fe.tymed = TYMED_HGLOBAL;            
	fe.cfFormat=cf_fc;
	fe.lindex = -1;            
	fe.dwAspect = DVASPECT_CONTENT;


	HGLOBAL              hg;
	FILEGROUPDESCRIPTOR  *pfgd;

	hg = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT, sizeof(FILEGROUPDESCRIPTOR)+sizeof(FILEDESCRIPTOR));
	if(hg)
	{
		pfgd = (FILEGROUPDESCRIPTOR*)GlobalLock(hg);
		if(pfgd)
		{
			int   i=0;
			pfgd->cItems = 1;
			pfgd->fgd[i].dwFlags = FD_ATTRIBUTES;
			pfgd->fgd[i].dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
			_strcpy(pfgd->fgd[i].cFileName,LPCTSTR(file_name));
			fe.cfFormat=cf_fd;
			stm.hGlobal = hg;
			GlobalUnlock(hg);	
			pSource->CacheData(0, &stm, &fe);
			pSource->m_FileName=file_name;
		}
	}
}
//*************************************************************************************************************
void CaplDocTreeItem::ShowWhereUsedAsComponent(bool bAnyTime)
{
	if(m_doc==0) return;
	if(m_inst==0) return;
	if(m_inst->GetType()==0) return;

	aplExtent ext_rev;
	if(0!=m_rev) ext_rev.Add(m_rev);
	else m_doc->m_api.m_doc_mgr.LoadAllDocumentRevision(m_inst,ext_rev);

	int i;
	aplExtent out_ext,ext;
	CaplInstance *inst;
	// Чтение из базы
	
	if(m_doc_data.IsConnected())
	{
		StartBusy();	

		CaplLoadData ld(&(m_doc->m_api.m_data),DEF_SOURCE);

		for(i=0;i<ext_rev.GetSize();i++) ld.AddQuery(0,ext_rev[i]);

		// ссылка
		i=ld.AddQuery(_T('r'),0, m_doc->m_api.m_prd_inst_mgr.e_apl_component,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_related, true, true);
		ld.AddQuery(_T('d'), i, m_doc->m_api.m_prd_inst_mgr.e_apl_component,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_relating, true, true);

		if (!ld.LoadEx(true,&out_ext))
			AfxMessageBox(IDS_ERROR_LOAD_DATA_APL,MB_OK|MB_ICONSTOP);

		StopBusy();
	}

	CSortClass::SortExtentById(ext_rev);

	m_doc_data.GetEntityExtent(m_doc->m_api.m_prd_inst_mgr.e_apl_component,out_ext);

	aplExtent ext_rel; 
	CString sDateEnd;
	for(i=0;i<out_ext.GetSize();i++)
	{
		CaplInstance *inst_rel=out_ext.GetAt(i);

		if(!m_doc_data.IsKindOf(inst_rel,m_doc->m_api.m_prd_inst_mgr.e_apl_component)) continue;


		if(!bAnyTime)
		{
			m_doc_data.GetAttr(inst_rel,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_date_removed,sDateEnd);
			if(sDateEnd!=_T("")) continue;
		}

		m_doc_data.GetAttr(inst_rel,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_related,inst);

		if(aplQFindInstInExtent(ext_rev,inst)<0)continue; 
		m_doc_data.GetAttr(inst_rel,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_relating,inst);
		ext.Add(inst);
		ext_rel.Add(inst_rel);
	}
	if(0==ext.GetSize())
	{
		AfxMessageBox( APL_T("Экземпляры изделий не найдены!"));
		return;
	}

	m_doc->m_api.LoadExtentInfo(ext);

	// Создание item-ов для связанных объектов
	bool bFoundNew=false;
	for(i=0;i<ext_rel.Size;i++)
	{
		CaplInstance *inst_rel=ext_rel[i];
		m_doc_data.GetAttr(inst_rel,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_rel_relating,inst);

		CaplTreeItem *new_tree_item=0;
		InsertInstInTree(inst,m_item,m_doc,m_tree,m_all_parent_prd_inst,0,&new_tree_item);
		if(0!=new_tree_item)
		{
			bFoundNew=true;
			((CaplPrdInstTreeItem*)new_tree_item)->m_used_inst_rel=inst_rel;
			((CaplPrdInstTreeItem*)new_tree_item)->RefreshItem();
		}
	}
	if(m_ExecMyExpand)
		MyExpand(false);

	if(!bFoundNew) AfxMessageBox( APL_T("Новые экземпляры изделий не найдены!"));

}

//*****************************************************************************
void CaplDocTreeItem::ShowAllBaseObjects(CaplEntity *ent)
{
	if(m_doc==0) return;
	if(m_inst==0) return;
	if(m_inst->GetType()==0) return;
		
	int i;
	aplExtent out_ext,ext;
	CaplInstance *inst;
	if(m_inst->GetId()!=0)
	{
		// Чтение из базы
		StartBusy();	
		if(m_doc_data.IsConnected())
		{
			CaplLoadData ld(&(m_doc->m_api.m_data),DEF_SOURCE);

			// ссылка
			i=ld.AddQuery(_T('b'), m_inst->GetId(), m_doc->m_api.m_doc_mgr.e_apl_doc_ref,m_doc->m_api.m_doc_mgr.a_apl_doc_ref_doc, true, true);
			ld.AddQuery(_T('d'), i, m_doc->m_api.m_doc_mgr.e_apl_doc_ref,m_doc->m_api.m_doc_mgr.a_apl_doc_ref_doc, true, true);
			i=ld.AddQuery(_T('d'), i, m_doc->m_api.m_doc_mgr.e_apl_doc_ref,m_doc->m_api.m_doc_mgr.a_apl_doc_ref_item, true, true);
			
			if (!ld.LoadEx(true,&out_ext))
				AfxMessageBox(IDS_ERROR_LOAD_DATA_APL,MB_OK|MB_ICONSTOP);

			ext.Clear();
			for(i=0;i<out_ext.GetSize();i++)
			{
				inst=out_ext.GetAt(i);
				
				if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_doc_mgr.e_apl_doc_ref))
				{
					m_doc_data.GetAttr(inst,m_doc->m_api.m_doc_mgr.a_apl_doc_ref_item,inst);
					if(0!=ent && 0!=inst)
					{
						if(ent!=inst->GetType())
							continue;
					}
					ext.Add(inst);
				}
			}			
			m_doc->m_api.LoadExtentInfo(ext);
			
		}
		StopBusy();
	}
	// Поиск связанных объектов
	m_doc_data.GetEntityExtent(m_doc->m_api.m_doc_mgr.e_apl_doc_ref,out_ext);
	for(i=0;i<out_ext.Size;i++)
	{
		m_doc_data.GetAttr(out_ext[i],m_doc->m_api.m_doc_mgr.a_apl_doc_ref_doc,inst);
		if(inst!=m_inst) continue;
		m_doc_data.GetAttr(out_ext[i],m_doc->m_api.m_doc_mgr.a_apl_doc_ref_item,inst);

		if(0!=ent && inst)
		{
			if(ent!=inst->GetType())
				continue;
		}

		ext.Add(inst);
	}
	// Создание item-ов для связанных объектов
	for(i=0;i<ext.Size;i++)
	{
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_base_objects,m_inst);

		/*
		if(-1==m_all_base_objects.Find(ext[i]))
		{
			if(m_doc_data.IsKindOf(ext[i],m_doc->m_api.m_prd_mgr.e_prd))
			{
				// Изделие
				CaplProductTreeItem *product_item=
					new CaplProductTreeItem(m_tree,m_doc,ext[i]);
				product_item->CreateTreeItem(m_item);
				m_all_base_objects.Add(ext[i]);
			}
			else if(m_doc_data.IsKindOf(ext[i],m_doc->m_api.m_prd_mgr.e_pdf))
			{
				// Версия изделия
				CaplProductTreeItem *product_item=
					new CaplProductTreeItem(m_tree,m_doc,0,ext[i]);
				product_item->CreateTreeItem(m_item);
				m_all_base_objects.Add(ext[i]);
			}
			else if(m_doc_data.IsKindOf(ext[i],m_doc->m_api.m_doc_mgr.e_doc))
			{
				// Документ
				CaplDocTreeItem *doc_item= new CaplDocTreeItem(m_tree,m_doc,ext[i]);
				doc_item->CreateTreeItem(m_item);
				m_all_base_objects.Add(ext[i]);
			}
			else if(m_doc_data.IsKindOf(ext[i],m_doc->m_api.m_categ_mgr.e_categ))
			{
				// Категория
				CaplCategoryTreeItem *categ_item=
					new CaplCategoryTreeItem(m_tree,m_doc,0,ext[i]);
				categ_item->CreateTreeItem(m_item);
				m_all_base_objects.Add(ext[i]);
			}
			else if(m_doc_data.IsKindOf(ext[i],m_doc->m_api.m_bp_mgr.e_bp))
			{
				// бизнес-процесс
				if(InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_contents,m_inst))
					m_all_base_objects.Add(ext[i]);
			}
		}	*/
	}
	if(m_ExecMyExpand)
		MyExpand(false);
}
//****************************************************************
void CaplDocTreeItem::CreateCharacteristic(CaplInstance *val)
{
	CaplInstance *item,*new_val=0;
	if(m_rev!=0) item=m_rev; else item=m_inst;

	if(item->GetType()==0) return;
	if(item->GetAccessmode()>aplRO) return;
	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 CaplDocTreeItem::CreateCharacteristicGroup(CaplInstance *group)
{
	CaplInstance *item,*new_ass=0, *new_val=0;
	if(m_rev!=0) item=m_rev; else item=m_inst;
	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 CaplDocTreeItem::CreateBP(CaplInstance *inst_for_id)
{
	if(m_doc==0) return;
	if(m_tree==0) return;
	
	CaplInstance *inst=m_inst;
	if(m_rev!=0)
	{
		if(m_rev->GetType()==0) return;
		inst=m_rev;
	}

	m_doc->m_api.m_doc_mgr.LoadDocInfo(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()>aplRW){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 CaplDocTreeItem::CreateRefusal()
{
	if(m_doc==0) return;
	if(m_tree==0) return;
	if(m_inst==0) return;
	if(m_inst->GetType()==0) return;
	if(m_inst->GetAccessmode()>aplRO){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}

	//CaplInstance *refusalt=m_doc->m_api.m_expl_mgr->CreateRefusal(m_inst);

	aplExtent ext,ext_doc;
	ext_doc.Add(m_inst);

	CaplInstance *refusalt=m_doc->m_fault_mgr.CreateRefusal(0,ext,&ext_doc);
	if(refusalt!=0)
	{
		//m_doc->m_api.m_doc_mgr.CreateAssociation(refusalt,m_inst);
		InsertInstInTree(refusalt,m_item,m_doc,m_tree,m_all_base_objects,m_inst);
		MyExpand();
	}
}

void CaplDocTreeItem::CreateHardCopy()
{
	if(m_doc==0) return;
	if(m_item==0) return;
	if(m_inst==0) return;
	if(m_inst->GetType()==0) return;
	if(m_inst->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight(),m_inst);return;};
	
	if(m_rev!=0) return;
	
	CString id=_T(""),buf=_T("");
	int num=m_doc->m_api.m_doc_mgr.GetNextHardCopyNumber(m_inst);
	if(num>-1) id.Format(_T("%d"),num);
	CaplInstance *new_hard_copy=m_doc->m_api.m_doc_mgr.CreateDocumentHardCopy(m_inst,id);
	if(new_hard_copy)
	{
		CaplDocCopyTreeItem *new_item=0;
		InsertInstInTree(new_hard_copy,m_item,m_doc,m_tree,m_all_copyes,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0) new_item->m_document=m_inst;
		MyExpand();
	}
}

//****************************************************************
void CaplDocTreeItem::ShowAllHardCopyes(bool showMsg,bool b_show_dlg)
{
	if(m_doc==0) return;
	if(m_item==0) return;
	if(m_inst==0) return;
	if(m_inst->GetType()==0) return;
	if(m_inst->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight(),m_inst);return;};
	
	if(m_rev!=0) return;

	if(b_show_dlg)
	{
		CDocCopyFilter filter;
		filter.m_doc=m_inst;
		filter.m_b_only_out_of_order=false;
		filter.m_state=_T("");
		m_doc->m_api.m_doc_mgr.ShowAllDocCopyes(&filter);
		return;
	}

	int i,k=m_all_copyes.Size;
	aplExtent ext;
	StartBusy();
	m_doc->m_api.m_doc_mgr.FindHardCopyes(ext,0,m_inst);
	StopBusy();
	
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	for(i=0;i<ext.Size;i++)
	{
		CaplDocCopyTreeItem *new_item=0;
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_copyes,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0) new_item->m_document=m_inst;
	}
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
		
	if(k>=m_all_copyes.Size) if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Новые копии документа не найдены"));
	if(m_ExecMyExpand)
		MyExpand(false);
	return;
}

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

	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("Новые бизнес-процессы не найдены"));
	if(m_ExecMyExpand)
		MyExpand(false);
	return;
}

bool CaplDocTreeItem::CreateDocByDot(CPSMDoc* doc, CaplInstance* dot, CaplInstance* inst)
{
	if(inst->GetAccessmode()>aplRW)
	{
		AfxMessageBox( APL_T("Нет доступа к объекту."));
		return false;
	}
	
	CString tmp_path, tmp;
	tmp_path.GetEnvironmentVariable(_T("temp"));
	CString doc_id= _T(""), name = _T(""), doc_name=_T(""), doc_descr=_T("");


	//++Колесников - это безобразие необходимо для корректной работы PSM с интеграцией
	CString sBuf,sDef,sWF;
	CaplInstance* ciWFInst = NULL;
	CFileFind ff;
	
	//принадлежит ли файл интеграции с SolidWorks, если нет
	doc->m_api.m_data.GetAttr(dot,doc->m_api.m_doc_mgr.a_apl_doc_system,sBuf);
	if (0==sBuf.CompareNoCase(_T("SolidWorks")))
	{

		AfxMessageBox( APL_T("Данный документ является документом интеграции.\nДанную функцию с ним выполнить невозможно."));
		return false;
	}//++конец безобразия
	
	doc->m_api.m_doc_mgr.GetFileName(dot, name);
	tmp_path+=_T("\\")+name;
	doc->m_api.m_doc_mgr.LoadRevision(dot, tmp_path);
	
	CaplInstance *doc_kind=0;
	doc->m_api.m_data.GetAttr(dot, doc->m_api.m_doc_mgr.a_doc_id, doc_id);
	doc->m_api.m_data.GetAttr(dot, doc->m_api.m_doc_mgr.a_doc_name, doc_name);
	doc->m_api.m_data.GetAttr(dot, doc->m_api.m_doc_mgr.a_doc_descr, doc_descr);
	doc->m_api.m_data.GetAttr(dot, doc->m_api.m_doc_mgr.a_doc_kind, doc_kind);
	if(doc->m_api.m_doc_mgr.CreateDocument(doc_id, doc_name,doc_descr,doc_kind,tmp_path,true,inst))	
		return true;

	return false;
}

bool CaplDocTreeItem::MoveDocument(CPSMDoc* doc, 
	CaplDocTreeItem* doc_item, CaplTreeItem* from_item, CaplTreeItem* to_item)
{
	if(!doc_item || !from_item || !to_item) return false;
	if(from_item==to_item) return false;//уже есть здесь
	if(doc_item->m_rev!=0) return false;
	
	CaplInstance *i_doc = doc_item->m_inst;//собственно документ
	
	aplExtent from_instance, to_instance;
	from_item->GetAccessedInstances(from_instance);
	to_item->GetAccessedInstances(to_instance);
	if(to_item->m_type==APL_TREE_ITEM_DOCUMENT)
	{
		if(i_doc == ((CaplDocTreeItem*)to_item)->m_inst)
		{
			AfxMessageBox( APL_T("Ссылка документа на самого себя недопустима!"));
			return false;
		}
	}
	
	if(!to_instance.GetSize()) return false;

	//Проверка перетаскивания документа на самого себя
	if(to_instance[0]==i_doc)
	{
		AfxMessageBox( APL_T("Ссылка документа на самого себя недопустима!"));
		return false;
	}

	//Проверка на цикл.
	if(doc->m_api.m_data.IsKindOf(to_instance[0],doc->m_api.m_doc_mgr.e_doc))
	{
		aplExtent doc_ext;
		doc_ext.Clear();
		doc_ext.Add(i_doc);
		CaplInstance *in_doc = to_instance[0];
		if(RecursiveDoc(doc,i_doc,in_doc,doc_ext)<0)
		{
			AfxMessageBox( APL_T("Недопустимая операция!"),MB_OK|MB_ICONERROR);
			return false;
		}
	}

	if(to_instance[0]->GetAccessmode()>aplRW)
	{
		AfxMessageBox( APL_T("Нет доступа к объекту"));
		return false;
	}
	if(from_instance.GetSize()>0 && from_instance[0]->GetAccessmode()>aplRW)
	{
		AfxMessageBox( APL_T("Нет доступа к объекту"));
		return false;
	}
	
	//два варианта: папка или не папка
	if(doc->m_api.m_data.IsKindOf(to_instance[0], doc->m_api.m_folder_mgr.e_folder))
	{
		if(doc->m_api.m_folder_mgr.AddToFolder(to_instance[0], i_doc))
		{
			((CaplFolderTreeItem*)to_item)->ShowContents();
			((CaplFolderTreeItem*)to_item)->MyExpand();
		}
	}
	else
	{
		if(CaplDocTreeItem::InsertDoc(doc, to_item, &to_item->m_all_documents, 
			i_doc, to_instance[0], false))
			to_item->ShowCmd(ID_SHOW_ALL_DOCS);
	}

	if(doc_item->m_folder!=0)//документ в папке
	{
		if(doc->m_api.m_folder_mgr.RemoveFromFolder(doc_item->m_folder, i_doc))
		{
			((CaplFolderTreeItem*)from_item)->m_contents.
				Remove(((CaplFolderTreeItem*)from_item)->m_contents.Find(i_doc));
		}
	}
	else if(doc_item->m_project)
	{
		
	}
	else //не из папки
	{
		from_item->m_all_documents.Remove(from_item->m_all_documents.Find(i_doc));
		if(doc_item->m_rel) doc->m_api.m_data.DeleteInstance(doc_item->m_rel);
	}
	
	doc->m_items.Remove(doc->m_items.Find(doc_item));
	doc->m_api.m_data.NET_SaveChanges();	

	return true;
}

int CaplDocTreeItem::RecursiveDoc(CPSMDoc* m_doc, CaplInstance *doc, CaplInstance *in_doc, aplExtent &insts)
{
	aplExtent ext,rel;
	m_doc->m_api.m_doc_mgr.FindAssociatedDocuments(insts,ext,rel,NULL);
	if(ext.Size==0) return 0;
	if(ext.Find(doc)>-1) return -1;
	else if(ext.Find(in_doc)>-1) return -2;
	else
		return RecursiveDoc(m_doc,doc,in_doc,ext);
}

//*********************************************************************
void CaplDocTreeItem::ShowAllCharacteristic(bool showMsg)
{
	CaplTreeItem::ShowAllCharacteristic(false);
}

CString CaplDocTreeItem::ChangePathIfIntegration(CaplInstance *inst)
{

	if(!inst)
		return m_EditPath;
	CString sDef,sWF;
	CaplInstance* ciWFInst = NULL;
	CFileFind ff;
	sDef =  APL_NO_T("SW_REFS\\Рабочая папка");
	sWF = _T("c:\\sw\\");
	ciWFInst = m_doc->m_api.m_options_mgr.FindOptionBN(sDef);

	if ((!ciWFInst)||(ciWFInst == (CaplInstance*)-1))
		ciWFInst = m_doc->m_api.m_options_mgr.CreateOption(sDef,sWF);
	else
		if (m_doc->m_api.m_data.IsKindOf(ciWFInst,m_doc->m_api.m_options_mgr.e_str))
			m_doc->m_api.m_data.GetAttr(ciWFInst,m_doc->m_api.m_options_mgr.a_str_value,sWF);

	if(TRUE == ff.FindFile(sWF))
		ff.Close();
	else
		CreateDirectory(sWF,NULL);
	return sWF;
}
