// aplTreeItem.cpp
#include "stdafx.h"
#include "PSMDoc.h"
#include "resource.h"
#include "NavigatorView.h"
#include "TabView.h"
#include "ExpandAllDlg.h"
#include "CancelDlg.h"

#include "aplQueryItem.h"
#include "aplTopLevelItem.h"
#include "TreeProductItem.h"
#include "aplDocTreeItem.h"
#include "aplFolderTreeItem.h"
#include "apl_lot_item.h"
#include "apl_prd_inst_item.h"
#include "aplBPTreeItem.h"
#include "aplBPInstTreeItem.h"
#include "aplChangeTreeItem.h"
#include "aplMessageTreeItem.h"
#include "aplTreeTaskItem.h"
#include "aplTreeProcessItem.h"
#include "aplTreeCharacteristicItem.h"
#include "aplTreeApprovalItem.h"
#include "aplCharacteristicGroupTreeItem.h"
#include "aplProjectTreeItem.h"
#include "act_res_treeitem.h"
#include "aplOrganizationTreeItem.h"
#include "aplPersonTreeItem.h"
#include "aplRecAlertTreeItem.h"
#include "aplClassifierTreeItem.h"
#include "aplDocCopyItem.h"
#include "CaplRequirementTreeItem.h"
#include "CaplRefusalTreeItem.h"
#include "aplTreeProcessTmplItem.h"
#include "CaplVirtualFolderItem.h"

CaplRecurseFindDlg CaplTreeItem::m_dlg;

int CaplTreeItem::m_num_doc_4_group=10;

//****************************************************************
//****************************************************************
//****************************************************************
CaplTreeItem::CaplTreeItem()
{
        m_type=_T("treeitem");
        m_fictive_item=0; m_doc=0;
        m_hasSubItem=false;
		m_expanded=false;
		m_expanding=false;
		m_PropertiesLoaded=false;
		m_ShowContentsOnExpand=true;
		m_addInCall= false;
		m_ExecMyExpand = true;
		m_bWOForNote=false;
}

//****************************************************************
CaplTreeItem::~CaplTreeItem()
{	
	if(m_doc==0) return;
	if(m_doc->m_tab_view->m_item_old==this)m_doc->m_tab_view->m_item_old=0;
	if(m_doc->m_tab_view->m_item_new==this)m_doc->m_tab_view->m_item_new=0;

/*	for(int i= 0; i<m_sub_menu.GetSize(); i++)
	{
		if(m_sub_menu[i])
		{
			m_sub_menu[i]->DestroyMenu();
			delete m_sub_menu[i];
		}
	}*/

    if(m_tree==0) return;
    if(m_item==0) return;
    if(!::IsWindow(m_tree->m_hWnd)) return;
	// чтобы - пока item еще не удален из дерева - не обратиться к корявому CaplTreeItem
	m_tree->SetItemData(m_item,0);
	CaplTreeItem *itemmmm=(CaplTreeItem*)m_tree->GetItemData(m_item);


    HTREEITEM item;
    while(1)
    {
        item=m_tree->GetChildItem(m_item);
        if(item==0) break;
        CaplTreeItem *treeitem=(CaplTreeItem*)m_tree->GetItemData(item);
		if(treeitem==this) continue;
        if(treeitem!=0) 
		{
			int idx=m_doc->m_items.Find(treeitem);
			//if(idx>=0)
			m_doc->m_items.Remove(idx);
			//else m_tree->DeleteItem(item);
		}
        else m_tree->DeleteItem(item);
    }
	m_tree->DeleteItem(m_item);

}

void CaplTreeItem::RemoveFromParenContents(CaplInstance *inst)
{
	int i;
	if(inst==0)return;
	if(m_doc_data.IsConnected()){
		CaplTreeItem *parent=GetParentItem(this);
		if(parent!=0){
			for(i=0;i<parent->m_contents.GetSize();i++){
				if(inst==parent->m_contents.GetAt(i)){
					parent->m_contents.Remove(i);
					break;
				}
			}
		}
	}
}

void CaplTreeItem::MyExpand(bool ShowContents)
{
	if(m_expanding)return;
	if(m_doc==0) return;
    if(m_tree==0) return;
    if(m_item==0) return;
	
	bool old_ShowContentsOnExpand=m_ShowContentsOnExpand;
	m_ShowContentsOnExpand=ShowContents;
	//if(/*(m_fictive_item!=0)||*/(m_expanded==false))
	{
		m_expanding=true;
		Expand(2);
		m_tree->Expand(m_item,TVE_EXPAND);
		m_expanding=false;
	}
	m_ShowContentsOnExpand=old_ShowContentsOnExpand;
	if(m_fictive_item!=0)
	{
		m_tree->DeleteItem(m_fictive_item);
		m_fictive_item=0;
	}
	Sort();
	m_tree->RedrawWindow();
}
//******************************************************************
void  CaplTreeItem::CollapseItem(bool bInsertFictive)
{
	if(m_tree==0) return;
	if(m_doc==0) return;
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	if(m_fictive_item!=0) m_tree->DeleteItem(m_fictive_item);
	while(1)
	{
		HTREEITEM item1=m_tree->GetChildItem(m_item);
		if(item1==0) break;
		CaplTreeItem *item=(CaplTreeItem*)m_tree->GetItemData(item1);
		if(item!=0) m_doc->m_items.Remove(m_doc->m_items.Find(item));
		else m_tree->DeleteItem(item1);//Удаляем если это фиг знает какой итем.
	}
	if(bInsertFictive==true)
	{
		m_fictive_item=m_tree->InsertItem(_T("fictive"),0,0,m_item);

		m_all_approval.Clear();
		m_all_caracteristic.Clear();
		m_all_documents.Clear();
		m_all_version.Clear();
		m_all_projects.Clear();
		m_all_bp_inst.Clear();
		m_all_bp.Clear();
		m_all_refusal.Clear();
	}
	else m_fictive_item=0;

	m_tree->Expand(m_item, TVE_COLLAPSE);

	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
	m_hasSubItem=false;
	m_expanded=false;
}
//*********************************************************************
void CaplTreeItem::GetAccessedInstances(aplExtent &ext){ext.Clear();};

void CaplTreeItem::FrezeInstances()
{
	aplExtent ext;
	int i;
	GetAccessedInstances(ext);
	if(ext.Size>0){
		for(i=0;i<ext.Size;i++)
		{
			if(ext[i]->GetAccessmode()>aplOWN)
			{
				AfxMessageBox( APL_T("У Вас не хватает прав чтобы изменить степень\nдоступа для указанных объектов\n"),MB_OK|MB_ICONERROR);
				return;
			}
		}
		if(IDYES==AfxMessageBox( APL_T("Вы действительно хотите запретить изменения ?"),MB_YESNO|MB_ICONQUESTION))
		{
			if(m_doc_data.NET_SetInstancesAccess(&ext,(CaplInstance *)-1,aplRO))
			{
				AfxMessageBox( APL_T("Права доступа успешно изменены!"),MB_ICONINFORMATION | MB_OK);
			}else{
				AfxMessageBox( APL_T("При назначении доступа возникли ошибки!"),MB_ICONERROR | MB_OK);
			}
		}
	}
}

void CaplTreeItem::SetInstancesOwner()
{
	aplExtent ext;
	GetAccessedInstances(ext);
	if(ext.Size>0)
		m_doc_data.NET_BecomeInstancesOwner(&ext);
}

void CaplTreeItem::SetInstancesAccess()
{
	aplExtent ext;
	GetAccessedInstances(ext);
	if(ext.Size>0)
		m_doc_data.NET_SetInstancesAccess(&ext,(CaplInstance *)0,
			(aplAccessModeType)-1);
}

void CaplTreeItem::SetInstancesAccessRecursive()
{
	aplExtent ext;
	GetAccessedInstances(ext);
	if(ext.Size>0){
		if(m_doc->m_api.SetRecursiveAccess(ext[0])){
			AfxMessageBox( APL_T("Права доступа успешно изменены!"),MB_ICONINFORMATION | MB_OK);
		}
	}
}


void CaplTreeItem::SetAccessFromPattern(CString &pattern)
{
	aplExtent ext;
	GetAccessedInstances(ext);
	if(ext.Size>0){
		if(m_doc_data.NET_SetAccessFromPattern(&ext,pattern, APL_T("Установка доступа"))){
			AfxMessageBox(APL_T("Доступ установлен!"));
		}
	}
}
//****************************************************************
void CaplTreeItem::ShowAllDocs(bool bExpand, bool showMsg)
{
	if(m_doc==0) return ;
	aplExtent ext;
	GetMainInstances(ext);
	if(ext.Size<=0) return;
	
	CaplInstance *inst=ext[0],*inst1=0;
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO)
	{if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};

	int i,count0=m_all_documents.Size;
	aplExtent ext_rel;

	StartBusy();
	m_doc->m_api.m_doc_mgr.FindAssociatedDocuments(inst,ext,ext_rel,m_doc->m_cur_context);
	StopBusy();
	
	if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_prd_mgr.e_apl_pdf))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_prd_mgr.a_pdf_prd,inst1);
	}
	else if (m_doc_data.IsKindOf(inst,m_doc->m_api.m_doc_mgr.e_apl_doc))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_doc_mgr.a_apl_doc_active,inst1);
	}
/*	else if (m_doc_data.IsKindOf(inst,m_doc->m_api.m_doc_mgr.e_apl_doc_rev))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_doc,inst1);
	}*/
	if(inst1!=0)
	{
		if(inst1->GetType()!=0)
		{
			if(inst1->GetAccessmode()<aplNO)
			{
				aplExtent ext1,ext_rel1;
				StartBusy();
				m_doc->m_api.m_doc_mgr.FindAssociatedDocuments(inst1,ext1,ext_rel1,m_doc->m_cur_context);
				StopBusy();
				ext_rel.Append(ext_rel1);
				ext.Append(ext1);
			}
			else
			{if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst1);};
		}
	}

	CaplInstance *inst0;
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);

	if((CaplTreeItem::m_num_doc_4_group >0 )&& (ext_rel.Size > CaplTreeItem::m_num_doc_4_group))
	{	
		ShowDocsInVirtualFolders(ext_rel);
	}
	else
	{
		for(i=0;i<ext_rel.Size;i++)
		{
			m_doc_data.GetAttr(ext_rel[i],m_doc->m_api.m_doc_mgr.a_apl_doc_ref_doc,inst0);
			if(0==inst0) continue;
			if(m_all_documents.Find(inst0)==-1)
			{
				CaplDocTreeItem *doc_item= new CaplDocTreeItem(m_tree,m_doc,inst0,ext_rel[i]);
				doc_item->CreateTreeItem(m_item);
				m_all_documents.Add(inst0);
				doc_item->m_par_item_docs_ext=&m_all_documents;
			}
		}
	}
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
	if(count0==m_all_documents.Size)
	{
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox(APL_T("Новые документы не найдены !"));
	}
	else {if(bExpand && m_ExecMyExpand)MyExpand(false);}
	
	return ;
}
//*********************************************************************
void CaplTreeItem::ShowDocsInVirtualFolders(aplExtent &ext_doc_rel)
{
	int i,j;
	CaplInstance *dt,*doc,*dg;

	CaplAggrMap map_doc_group;

	aplExtent ext_doc_without_group;

	// разбиваем на кучки
	for(i=0;i<ext_doc_rel.Size;i++)
	{
		CaplInstance *rel=ext_doc_rel[i];
		m_doc_data.GetAttr(rel,m_doc->m_api.m_doc_mgr.a_apl_doc_ref_doc,doc);
		if(0==doc) continue;
		if(m_all_documents.Find(doc)>=0) continue;
		m_doc_data.GetAttr(doc,m_doc->m_api.m_doc_mgr.a_doc_kind,dt);
		//map_doc_group.Add((long)dt,rel);

		if(0==dt){ext_doc_without_group.Add(rel); continue;}

		dg=(CaplInstance*)m_doc->m_map_dt_dg.QGetPointerByIn((long)dt);
		if(-1==(long)dg) // относится к нескольким группам
		{
			ext_doc_without_group.Add(rel);
		}
		else if (0!=dg)
		{
			CaplInstance *par;
			while(true)
			{
				m_doc_data.GetAttr(dg,m_doc->m_api.m_doc_mgr.a_dt_group_par,par);
				if(0==par) break;
				dg=par;
			}
			map_doc_group.Add((long)dg,rel);
		}
		else if(0!=dt) map_doc_group.Add((long)dt,rel);
	}

	// Создаем документы без групп
	for(i=0;i<ext_doc_without_group.Size;i++)
	{
		CaplInstance *rel=ext_doc_without_group[i];
		if(0==rel) continue;;
		m_doc_data.GetAttr(rel,m_doc->m_api.m_doc_mgr.a_apl_doc_ref_doc,doc);
		if(0==doc) continue;

		CaplDocTreeItem *doc_item= new CaplDocTreeItem(m_tree,m_doc,doc,rel);
		doc_item->CreateTreeItem(m_item);
		m_all_documents.Add(doc);
		doc_item->m_par_item_docs_ext=&m_all_documents;
	}


	// Создаем виртуальные папки для кучек
	for(i=0;i<map_doc_group.Size;i++)
	{
		dt=(CaplInstance*)map_doc_group.Data[i].in;

		CaplVirtualFolderItem *virt_folder_item= new CaplVirtualFolderItem(m_tree,m_doc,0,0);
		if(0==dt) virt_folder_item->m_name=APL_T("Документы без вида");
		else if(m_doc->m_api.m_data.IsKindOf(dt,m_doc->m_api.m_doc_mgr.e_dt_group))
			m_doc_data.GetAttr(dt,m_doc->m_api.m_doc_mgr.a_dt_group_name,virt_folder_item->m_name);
		else if(m_doc->m_api.m_data.IsKindOf(dt,m_doc->m_api.m_doc_mgr.e_dt))
			m_doc_data.GetAttr(dt,m_doc->m_api.m_doc_mgr.a_dt_pdt,virt_folder_item->m_name);
		else virt_folder_item->m_name=APL_T("Неизвестный тип группировки");

		virt_folder_item->m_par_item_docs_ext=&m_all_documents;
		
		virt_folder_item->CreateTreeItem(m_item);

		virt_folder_item->m_group_item=dt;


		CaplAggr &aggr=map_doc_group.Data[i].out;

		for(j=0;j<aggr.GetSize();j++)
		{
			CaplInstance *rel=0;
			aggr.GetByIndex(j,rel);
			if(0==rel) continue;;
			m_doc_data.GetAttr(rel,m_doc->m_api.m_doc_mgr.a_apl_doc_ref_doc,doc);
			m_all_documents.Add(doc);
			virt_folder_item->m_items.Add(rel);
		}
	}
}
//*********************************************************************
void CaplTreeItem::ShowAllCharacteristic(bool  showMsg)
{
	if(m_doc==0) return ;
	aplExtent ext;
	GetMainInstances(ext);
	if(ext.Size<=0) return;
	
	CaplInstance *inst=ext[0],*inst1=0;
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO)
	{if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};

	int i,count0=m_all_caracteristic.Size;
	aplExtent ext1, ext_rel,extGroup;

	StartBusy();
	int bWithSystem= 0;
	m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Показывать системные характеристики в дереве объектов"), bWithSystem, 0);
	m_doc->m_api.m_charact_mgr.FindAssociatedCharacteristic(inst,ext_rel,extGroup, false, false, true, (bWithSystem!=0)?true:false);
	StopBusy();

	if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_prd_mgr.e_apl_pdf))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_prd_mgr.a_pdf_prd,inst1);
	}
	else if (m_doc_data.IsKindOf(inst,m_doc->m_api.m_doc_mgr.e_apl_doc))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_doc_mgr.a_apl_doc_active,inst1);
	}
	else if (m_doc_data.IsKindOf(inst,m_doc->m_api.m_doc_mgr.e_apl_doc_rev))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_doc,inst1);
	}
	else if (m_doc_data.IsKindOf(inst,m_doc->m_api.m_classifier_mgr.e_apl_classifier_level))
	{
		inst1 = inst;
	}

	if(inst1!=0)
	{
		if(inst1->GetType()==0) return ;
		if(inst1->GetAccessmode()>aplRO) return ;
// 			{if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight,inst1);return;};
		aplExtent ext_rel1,extGroup1;
		StartBusy();
		m_doc->m_api.m_charact_mgr.FindAssociatedCharacteristic(inst1,ext_rel1,extGroup1);
		StopBusy();
		ext_rel.Append(ext_rel1);
		extGroup.Append(extGroup1);
	}

	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);

	for(i=0;i<ext_rel.Size;i++)
	{
		if(m_all_caracteristic.Find(ext_rel[i])==-1)
		{
			m_doc_data.GetAttr(ext_rel[i],m_doc->m_api.m_charact_mgr.a_apl_charact_val_group,inst);
			if(inst!=0)
			{
				if(extGroup.Find(inst)>=0) continue;
			}
			CaplCharacteristicTreeItem *characteristic_item=
				new CaplCharacteristicTreeItem(m_tree,m_doc,ext_rel[i]);
			characteristic_item->CreateTreeItem(m_item);
			characteristic_item->RefreshItem();
			m_all_caracteristic.Add(ext_rel[i]);
		}
	}
	for(i=0;i<extGroup.Size;i++)
	{
		if(m_all_caracteristic.Find(extGroup[i])==-1)
		{
			CaplCharacteristicGroupTreeItem *characteristic_group_item=
				new CaplCharacteristicGroupTreeItem(m_tree,m_doc,extGroup[i]);
			characteristic_group_item->CreateTreeItem(m_item);
			m_all_caracteristic.Add(extGroup[i]);
		}
	}
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
	if(count0==m_all_caracteristic.Size)
	{
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox(APL_T("Новые характеристики не найдены !"));
	}
	else if(m_ExecMyExpand)MyExpand(false);
	return;
}
//****************************************************************
void CaplTreeItem::ShowAllApproval(bool showMsg, aplExtent *ext_approval)
{
	aplExtent ext;
	GetMainInstances(ext);
	if(ext.Size<=0) return;
	CaplInstance *inst=ext[0];
	CaplInstance *inst0=0;
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};


	if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_doc_mgr.e_doc))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_doc_mgr.a_apl_doc_active,inst);
		if(inst==0) return ;
		if(inst->GetType()==0) return ;
		if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};
	}
	if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_bp_mgr.e_bp))
	{
		if(m_doc->m_api.m_bp_mgr.m_bUseVersions)
			m_doc_data.GetAttr(inst,m_doc->m_api.m_bp_mgr.a_bp_act,inst0);
	}
	if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_charact_mgr.e_apl_charact_value))
	{
		if(m_doc->m_api.m_charact_mgr.m_bUseVersions)
			m_doc_data.GetAttr(inst,m_doc->m_api.m_charact_mgr.a_apl_charact_val_act_ver,inst0);
			
	}
// 	if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_charact_mgr.e_apl_charact_value_ver))
// 	{
// 		m_doc_data.GetAttr(inst,m_doc->m_api.m_charact_mgr.a_apl_charact_val_ver_char_value,inst0);
// 	}

	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);

	aplExtent ext0,ext1;

	if(0!=ext_approval) ext0.Append(*ext_approval);
	else
	{
		bool bShowRevocated=false;
		if(CPSMDoc::m_show_revocated_approval) bShowRevocated=true;

		StartBusy();
		m_doc->m_api.m_appr_mgr.LoadItemApproval(inst,ext0,true,bShowRevocated);
		if(inst0)
			if(inst0->GetType()!=0)
				if(inst0->GetAccessmode()<aplNO)
				{
					m_doc->m_api.m_appr_mgr.LoadItemApproval(inst0,ext1,true,bShowRevocated);
					ext0.Append(ext1);
				}
				StopBusy();
	}


	int count0=m_all_approval.Size;
	int i;
	bool not_found=true;
	for(i=0;i<ext0.Size;i++)
	{
		CaplInstance *aprr_item;
		m_doc->m_api.m_data.GetAttr(ext0[i],m_doc->m_api.m_appr_mgr.a_appr_item,aprr_item);
		if(!(aprr_item==inst || aprr_item==inst0)) continue;
		bool f=true;
		if(m_all_approval.Find(ext0[i])!=-1)f=false;
		if(f)
		{
			not_found=false;
			CaplApprovalTreeItem *approval_item=
				new CaplApprovalTreeItem(m_tree,m_doc,ext0[i]);
			approval_item->CreateTreeItem(m_item);
			m_all_approval.Add(ext0[i]);
		}
	}
	if(count0==m_all_approval.Size)
	{
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Новые электронные подписи не найдены !"));
	}
	else if(m_ExecMyExpand)MyExpand(false);
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}

//****************************************************************
void CaplTreeItem::ShowAllBPInst(CaplInstance *inst, bool showMsg)
{
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};

	int i,k=m_all_bp_inst.Size;
	CaplInstance *inst0;
	aplExtent ext, ext_rel;
	StartBusy();
	m_doc->m_api.m_bp_mgr.FindAssociatedBPInst(inst,ext,ext_rel,m_doc->m_cur_context);
	StopBusy();
	
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	for(i=0;i<ext_rel.Size;i++)
	{
		m_doc_data.GetAttr(ext_rel[i],m_doc->m_api.m_bp_mgr.a_bp_inst_ref_process,inst0);
		if(inst0==0) continue;
		CaplBPInstTreeItem *new_item=0;
		InsertInstInTree(inst0,m_item,m_doc,m_tree,m_all_bp_inst,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0) new_item->m_rel=ext_rel[i];
	}
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
		
	if(k>=m_all_bp_inst.Size) if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Новые экземпляры бизнес-процессы не найдены"));
	if(ext_rel.Size >0) MyExpand(false);
	return;
}


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

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

}

//****************************************************************
void CaplTreeItem::ShowAllProjects(CaplInstance *inst,bool showMsg)
{
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};

	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);

	StartBusy();
	aplExtent ext,ext_rel0;
	m_doc->m_project_mgr->FindAssociatedProjects(inst, ext, ext_rel0); 
	for(int i=0;i<ext.Size;i++)
	{
		CaplProjectTreeItem *new_item=0;
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_projects,0,(CaplTreeItem **)(&new_item));
		if(new_item!=0) new_item->m_rel=inst;
	}
	StopBusy();
	if(!ext.GetSize())
	{
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Новые проекты не найдены !"));
	}
	else 
		if(m_ExecMyExpand)MyExpand(false);

	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}
//*********************************************************************
void CaplTreeItem::CreateApproval()
{
	aplExtent ext;
	GetMainInstances(ext);
	if(ext.Size<=0) return;
	CaplInstance *inst=ext[0];
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};

	if (m_doc_data.IsKindOf(inst,m_doc->m_api.m_doc_mgr.e_apl_doc))
		m_doc_data.GetAttr(inst,m_doc->m_api.m_doc_mgr.a_apl_doc_active,inst);
	if (m_doc_data.IsKindOf(inst,m_doc->m_api.m_bp_mgr.e_bp))
		if(m_doc->m_api.m_bp_mgr.m_bUseVersions)
		{
			CaplInstance *bp=inst;
			if(m_doc->m_api.m_bp_mgr.CheckMyLock(bp,false))
			{
				AfxMessageBox( APL_T("Нельзя подписывать редактируемую версию!"));
				return;
			}
			m_doc_data.GetAttr(bp,m_doc->m_api.m_bp_mgr.a_bp_act,inst);
			if(!inst)
			{
				CString num=_T("");
				inst=m_doc->m_api.m_bp_mgr.GetLatestBPVersion(bp,num);
				if(inst)
					m_doc_data.PutAttr(bp,m_doc->m_api.m_bp_mgr.a_bp_act,inst);
				else
				{
					aplExtent ext_char,ext_group;
					m_doc->m_api.m_charact_mgr.FindAssociatedCharacteristic(bp,ext_char,ext_group,true);
					inst=m_doc->m_api.m_bp_mgr.CreateBPVersion(bp,_T("0"));
				}
			}
		}
	if (m_doc_data.IsKindOf(inst,m_doc->m_api.m_charact_mgr.e_apl_charact_value))
		if(m_doc->m_api.m_charact_mgr.m_bUseVersions)
		{
			CaplInstance *char_val=inst;
			if(m_doc->m_api.m_charact_mgr.CheckMyLock(char_val,false))
			{
				AfxMessageBox( APL_T("Нельзя подписывать редактируемую версию!"));
				return;
			}
			m_doc_data.GetAttr(inst,m_doc->m_api.m_charact_mgr.a_apl_charact_val_act_ver,inst);
			if(!inst)
			{
				CString num=_T("");
				inst=m_doc->m_api.m_charact_mgr.GetLatestCharValVersion(char_val,num);
				if(inst)
					m_doc_data.PutAttr(char_val,m_doc->m_api.m_charact_mgr.a_apl_charact_val_act_ver,inst);
				else
					inst=m_doc->m_api.m_charact_mgr.CreateCharValVersion(char_val,_T("0"));
			}
		}
		
	CaplInstance *appr=m_doc->m_api.m_appr_mgr.CreateApproval(inst);
	if(appr==0) return;

	RefreshItem();
	
	CaplApprovalTreeItem *approval_item=
			new CaplApprovalTreeItem(m_tree,m_doc,appr);
	approval_item->CreateTreeItem(m_item);
	m_all_approval.Add(appr);
/*	if(CaplTreeItem::m_AutoUzurpireApproval)
	{
		if (appr->GetAccessmode()<aplRO)
		{
			aplExtent ext; ext.Add(appr);
			m_doc_data.NET_BecomeInstancesOwner(&ext);
		}
	}*/
	
	MyExpand();
	if(m_doc->m_tab_view->m_item_old==this) m_doc->ChangeItem(0);m_doc->ChangeItem(this);
}
//*********************************************************************
void CaplTreeItem::GetInstID(CaplInstance *inst,CString &str_id, CString *str_name)
{
	str_id=_T("");
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};

	if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_prd_mgr.e_pdf))
	{
		CString buf;
		CaplInstance *prd;
		m_doc_data.GetAttr(inst,m_doc->m_api.m_prd_mgr.a_pdf_prd,prd);
		if(prd!=0)
		{
			m_doc_data.GetAttr(prd,m_doc->m_api.m_prd_mgr.a_prd_id,str_id);
			m_doc_data.GetAttr(inst,m_doc->m_api.m_prd_mgr.a_pdf_id,buf);
			if(buf!=_T("")) { str_id+=_T("-"); str_id+=buf;}
			if(str_name!=0) m_doc_data.GetAttr(prd,m_doc->m_api.m_prd_mgr.a_prd_name,*str_name);
		}
	}
	else if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_prd_mgr.e_prd))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_prd_mgr.a_prd_id,str_id);
	}
	else if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_doc_mgr.e_doc))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_doc_mgr.a_doc_id,str_id);
	}
	else if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_bp_mgr.e_bp))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_bp_mgr.a_bp_id,str_id);
	}
	else if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_categ_mgr.e_categ))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_categ_mgr.a_categ_id,str_id);
	}
	else if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_folder_mgr.e_folder))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_folder_mgr.a_folder_name,str_id);
	}
	else if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_project_mgr->e_project))
	{
		m_doc_data.GetAttr(inst,m_doc->m_api.m_project_mgr->a_project_id,str_id);
	}
}

//*********************************************************************
void CaplTreeItem::CreateDoc(CaplInstance *inst_for_id, LPCTSTR file_name)
{
	aplExtent ext;
	GetMainInstances(ext);
	if(ext.Size<=0) return;
	CaplInstance *inst=ext[0];
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};

	CaplInstance *par_inst=inst;
	if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_folder_mgr.e_folder))
	{
		m_doc->m_api.m_folder_mgr.LoadFolderInfo(inst);
		if(CaplFolderManager::m_create_assoc_folder_doc==FALSE)
			par_inst=0;
		if(inst->GetAccessmode()>aplRW)
			{if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};
	}
	else if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_classifier_mgr.e_apl_classifier_level))
	{
		par_inst=0;
	}

	CString sDocId,str_name, buf,buf1;

	CString sFnameShort; // имя файла без расширения и пути
	buf=file_name;
	if(buf!=_T(""))
	{
		int i=buf.ReverseFind(_T('\\'));
		if(i>0){buf1=buf.Right(buf.GetLength()-(i+1)); buf=buf1;}
 		i=buf.ReverseFind(_T('.'));
		if(i>0) sFnameShort=buf.Left(i);
		else sFnameShort=buf;
	}
	
	if(inst_for_id!=0)
	{
		if(!m_doc_data.IsKindOf(inst_for_id,m_doc->m_api.m_folder_mgr.e_folder))
		{
			GetInstID(inst_for_id, sDocId, &str_name);
		}
		if(sFnameShort!=_T("")) str_name=sFnameShort;
	}

	if(sDocId==_T(""))  sDocId=sFnameShort;


	// Создание документа
	CaplInstance *instd_rel=0;

	// автоматическое создание обозначения, изначально для ГРПЗ

//	if(! (m_doc->m_api.m_data.IsKindOf(inst_for_id, m_doc->m_api.m_doc_mgr.e_doc) ||
//		m_doc->m_api.m_data.IsKindOf(inst_for_id, m_doc->m_api.m_prd_mgr.e_pdf)))
//		{
		//CString sInstallCode;
		//m_doc->m_api.m_options_mgr.GetOptionValueBN(APL_NO_T("Код установки"), sInstallCode, _T(""));
		//if(sInstallCode==_T("GRPZ"))
		if(sDocId==_T(""))
		{
			CaplInstance *pers=m_doc->m_api.m_appr_mgr.GetCurrentPerson();
			if(0!=pers)
			{
				CString buf;
				m_doc->m_api.m_appr_mgr.GetPersonName(pers,sDocId,true);
				CaplInstance *org=m_doc->m_api.m_appr_mgr.GetActualPersOrg(pers,true);
				if(0!=org)
				{
					m_doc->m_api.m_data.GetAttr(org,m_doc->m_api.m_appr_mgr.a_org_id,buf);
					sDocId+=_T("_");
					sDocId+=buf;
				}
				COleDateTime odt=COleDateTime::GetCurrentTime();
				buf=odt.Format(_T("%d.%m.%Y_%H:%M:%S"));
				sDocId+=_T("_");
				sDocId+=buf;
			}
		}
//	}

	CaplStrStrMap mapRequsite;
	CString sDocDescription;
	CaplInstance *instDocType=0;

	// Проверка файла реквизитов
	
	{
		CString sReqFile=file_name; sReqFile+=_T(".requisite");
		if(CaplFile::IsFileExist(sReqFile))
		{
			if(IDYES==AfxMessageBox(_T("Загрузить реквизиты из файла реквизитов ?"),MB_YESNO|MB_ICONQUESTION))
			{
				if(!CaplDocManager::LoadRequisiteFromFile(sReqFile,mapRequsite))  AfxMessageBox(_T("Ошибка открытия файла реквизтов!"),MB_OK|MB_ICONSTOP);
				else
				{
					sDocId=mapRequsite.Get(_T("обозначение"),true);
					str_name=mapRequsite.Get(_T("наименование"),true);
					sDocDescription=mapRequsite.Get(_T("описание"),true);
					CString sDocType=mapRequsite.Get(_T("вид"),true);
					if(sDocType!=_T(""))
					{
						instDocType=m_doc->m_api.m_doc_mgr.GetDocumentTypeBN(sDocType);
						if(0==instDocType)
						{
							CString sBuf=_T("Создать вид документа '%s'?");
							sBuf.Replace(_T("%s"),sDocType);
							if(IDYES==AfxMessageBox(sBuf,MB_YESNO|MB_ICONQUESTION))
							{
								instDocType = m_doc->m_api.m_data.CreateInstance(m_doc->m_api.m_doc_mgr.e_dt);
								m_doc->m_api.m_data.PutAttr(instDocType, m_doc->m_api.m_doc_mgr.a_dt_pdt, sDocType);
								m_doc->m_api.SaveChanges();
							}
						}
					}
				}
			}
		}
	}


	CaplInstance *instd=m_doc->m_api.m_doc_mgr.CreateDocument(sDocId,str_name,sDocDescription,instDocType,file_name,true,par_inst,&instd_rel);
	if(instd==0) return ;


	if(mapRequsite.GetSize()>0)
	{
		// Загружааем реквизиты
		CaplInstance *actDocRev=0;
		m_doc->m_api.m_data.GetAttr(instd,m_doc->m_api.m_doc_mgr.a_apl_doc_active, actDocRev);
		if(0!=actDocRev)
		{
			m_doc->m_api.m_doc_mgr.SaveRequisiteToRevision(actDocRev,mapRequsite,true);
		}
	}


	/*
	if(CaplTreeItem::m_AutoUzurpireDoc)
	{
		aplExtent ext; ext.Add(instd);
		m_doc_data.NET_BecomeInstancesOwner(&ext);
	}*/
	
	if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_folder_mgr.e_folder))
	{
			// Занесение в папку
		if(CaplFolderManager::m_create_assoc_folder_doc==FALSE)
			m_doc->m_api.m_folder_mgr.AddToFolder(inst,instd);
		Expand(TVE_COLLAPSE);
		MyExpand();
		//((CaplFolderTreeItem*)this)->ShowContents();
	}
	else if(m_doc_data.IsKindOf(inst,m_doc->m_api.m_classifier_mgr.e_apl_classifier_level))
	{
		// Занесение в справочник
		m_doc->m_api.m_classifier_mgr.CreateClassifierAssociation(instd,inst);
		Expand(TVE_COLLAPSE);
		MyExpand();
		//((CaplFolderTreeItem*)this)->ShowContents();
	}
	else
	{
		/// DIV - если вставить item как в трех следующих строчках, то в дереве будут два документа
		//CaplDocTreeItem *doc_item= new CaplDocTreeItem(m_tree,m_doc,instd,instd_rel);
		//doc_item->CreateTreeItem(m_item);
		//m_all_approval.Add(instd);
		//Expand(TVE_COLLAPSE);
		//MyExpand();	
		ShowAllDocs();
	}
	

	return;
}
//*********************************************************************
void CaplTreeItem::ShowAllResusal(bool bExpand, bool showMsg)
{
	aplExtent ext;
	GetMainInstances(ext);
	if(ext.Size<=0) return;
	CaplInstance *inst=ext[0];

	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};

	aplExtent ext_refusal;
	StartBusy();
	m_doc->m_api.m_expl_mgr->FindAssociatedRefusal(inst,ext_refusal);
	int i;
	for(i=0; i<ext_refusal.GetSize(); i++)
	{
		CaplInstance *refusal=ext_refusal[i];
		CaplRefusalTreeItem *new_item=0;
		InsertInstInTree(refusal,m_item,m_doc,m_tree,m_all_refusal,0,(CaplTreeItem **)(&new_item));
	}
	StopBusy();

	if(bExpand)	MyExpand();
	if(0==ext_refusal.GetSize() && showMsg) {AfxMessageBox(APL_T("Нет связанных неисправностей")); return;}
	return;

}
//*********************************************************************
void CaplTreeItem::ShowContainedProccess(CaplInstance *inst,bool showMsg)
{
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};
	
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	
	StartBusy();
	aplExtent ext;
	
	m_doc->m_wf_mgr.FindProcessContained(inst,ext);
	for(int i=0;i<ext.Size;i++)
	{
		CaplProcessTreeItem *new_item=0;
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_projects,0,(CaplTreeItem **)(&new_item));
	}

	StopBusy();
	if(!ext.GetSize()) 
	{
		if(m_bShowNoFoundMessage && showMsg) 
			AfxMessageBox( APL_T("Процессы не найдены!"));
	}
	else 
	{
		if(m_ExecMyExpand)
			MyExpand(false);
	}
		
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}
//*********************************************************************
void CaplTreeItem::ShowContainedProjects(CaplInstance *inst,bool showMsg)
{
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};
	
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	
	StartBusy();
	aplExtent ext,ext_rel;
	
	m_doc->m_api.m_project_mgr->FindAssociatedProjects(inst,ext,ext_rel);
	for(int i=0;i<ext.Size;i++)
	{
		CaplProjectTreeItem *new_item=0;
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_projects,0,(CaplTreeItem **)(&new_item));
	}
	StopBusy();

	if(!ext.GetSize())
	{
		if(m_bShowNoFoundMessage && showMsg) 
			AfxMessageBox( APL_T("Проекты не найдены!"));
	}
	else 
	{
		if(m_ExecMyExpand)
			MyExpand(false);
	}
		
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}
//*********************************************************************
void CaplTreeItem::ShowContainedFolder(CaplInstance *inst,bool showMsg)
{
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};
	
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	
	StartBusy();
	aplExtent ext;
	
	m_doc->m_api.m_folder_mgr.FindFolderContained(inst,ext);
	for(int i=0;i<ext.Size;i++)
	{
		CaplFolderTreeItem *new_item=0;
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_projects,0,(CaplTreeItem **)(&new_item));
		if(0!=new_item)
		{
			new_item->m_bIsParent4Folder=true;
			new_item->RefreshItem();
		}
	}
	StopBusy();
	if(!ext.GetSize())
	{
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Папки не найдены !"));
	}
	else 
		if(m_ExecMyExpand)MyExpand(false);
		
		if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);

}
//*********************************************************************
void CaplTreeItem::FindContainedMessage(CaplInstance *inst, aplExtent &ext_msg)
{
	ext_msg.Clear();
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) return;

	CaplInstance* person= m_doc->m_api.m_appr_mgr.GetCurrentPerson();
	if(0==person) return;

	CString sSql;
	//sSql.Format(_T("SELECT Ext_1 FROM Ext_1 { apl_message(.items LIKE #%d AND .copy=#0 AND .status!='draft')} END_SELECT"), inst->GetId());

	sSql.Format(_T("SELECT Ext_1 FROM Ext_1 { apl_message(.items LIKE #%d  AND .status!='draft' AND (.sender=#%i OR .recipient=#%i))} END_SELECT"), 
		inst->GetId(),person->GetId(),person->GetId() );


	if(!m_doc->m_api.m_data.NET_QueryEditParse(sSql)) return;

	aplExtent ext0;
	m_doc->m_api.m_data.NET_QueryExecute(ext0);

	if(0==ext0.GetSize()) return;

	m_doc->m_api.m_message_mgr.LoadMessageInfo(ext0);

	int i;
	CaplInstance *msgcopy;
	for(i=0;i<ext0.GetSize();i++)
	{
		CaplInstance *mes=ext0[i];
		if(mes->GetAccessmode()>aplRO) continue;
		m_doc->m_api.m_data.GetAttr(mes,m_doc->m_api.m_message_mgr.a_message_copy,msgcopy);
		if(0!=msgcopy ) ext_msg .Add(msgcopy);
		else ext_msg.Add(mes);
	}
}

void CaplTreeItem::ShowContainedMessage(CaplInstance *inst,bool showMsg)
{
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};

	aplExtent ext;
	FindContainedMessage(inst,ext);

	if(ext.GetSize()<1)
	{
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Сообщения не найдены !"));
		return;
	}
	StartBusy();
	m_doc->m_api.m_message_mgr.LoadMessageInfo(ext);

	bool bNewItems=false;
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	for(int i=0;i<ext.Size;i++)
	{
		CaplMessageTreeItem *new_item=0;
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_projects,0,(CaplTreeItem **)(&new_item));
		if(0!=new_item) bNewItems=true;
	}
	StopBusy();
	if(m_bShowNoFoundMessage && showMsg && !bNewItems) AfxMessageBox( APL_T("Новые сообщения не найдены !"));
	if(m_ExecMyExpand)MyExpand(false);
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}
//*********************************************************************
void CaplTreeItem::ShowContainedTasks(CaplInstance *inst,bool showMsg)
{
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};


	aplExtent ext;
	CString buf,sSql;

	sSql= _T("SELECT Ext2 FROM  Ext1{apl_process.work_objects->apl_work_object.object= #%i} ")
		_T("Ext2 {apl_task (.end_date = '' AND .of_process IN #Ext1)}	END_SELECT");

	buf.Format(_T("%i"),inst->GetId());
	sSql.Replace(_T("%i"),buf);

	if(!m_doc->m_api.m_data.NET_QueryEditParse(sSql)) return;
	m_doc->m_api.m_data.NET_QueryExecute(ext);


	if(ext.GetSize()<1)
	{
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Задания не найдены !"));
		return;
	}
	StartBusy();
	m_doc->m_api.m_message_mgr.LoadMessageInfo(ext);

	bool bNewItems=false;
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	for(int i=0;i<ext.Size;i++)
	{
		CaplTaskTreeItem *new_item=0;
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_projects,0,(CaplTreeItem **)(&new_item));
		if(0!=new_item) bNewItems=true;
	}
	StopBusy();
	if(m_bShowNoFoundMessage && showMsg && !bNewItems) AfxMessageBox( APL_T("Новые задания не найдены !"));
	if(m_ExecMyExpand)MyExpand(false);
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}
//*********************************************************************
void CaplTreeItem::ShowContainedAlert(CaplInstance *inst,bool showMsg)
{
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};


	aplExtent ext;
	CString sSql;
	sSql.Format(_T("SELECT Ext_1 FROM Ext_1 { apl_alert.item=#%i } END_SELECT"), inst->GetId());

	if(!m_doc->m_api.m_data.NET_QueryEditParse(sSql)) return;
	m_doc->m_api.m_data.NET_QueryExecute(ext);


	if(ext.GetSize()<1)
	{
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Напоминания не найдены !"));
		return;
	}
	StartBusy();
	m_doc->m_api.m_message_mgr.LoadMessageInfo(ext);

	bool bNewItems=false;
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	for(int i=0;i<ext.Size;i++)
	{
		CaplAlertTreeItem *new_item=0;
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_projects,0,(CaplTreeItem **)(&new_item));
		if(0!=new_item) bNewItems=true;
	}
	StopBusy();
	if(m_bShowNoFoundMessage && showMsg && !bNewItems) AfxMessageBox( APL_T("Новые напоминания не найдены !"));
	if(m_ExecMyExpand)MyExpand(false);
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}

//*********************************************************************
void CaplTreeItem::ShowContainedClassifier(CaplInstance *inst,bool showMsg)
{
	if(inst==0) return ;
	if(inst->GetType()==0) return ;
	if(inst->GetAccessmode()>aplRO) {if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),inst);return;};
	
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	
	StartBusy();
	aplExtent ext;
	m_doc->m_api.m_classifier_mgr.FindClassifiersContained(inst,ext);
	for(int i=0;i<ext.Size;i++)
	{
		CaplClassifierTreeItem *new_item=0;
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_projects,0,(CaplTreeItem **)(&new_item));
	}
	StopBusy();
	if(!ext.GetSize())
	{
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Справочники не найдены !"));
	}
	else 
		if(m_ExecMyExpand)MyExpand(false);
		
		if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
}
//*********************************************************************
void CaplTreeItem::PrepareContextMenu(int command)
{
	if(command==0) return;
	switch(command)
	{
	case ID_SHOW_ALL_CONTENTS:  Expand(2); MyExpand(); break;
	case ID_SHOW_PROPERTIES:
		{
			CPSMDoc *m_doc_local=m_doc; // копия члена класса в памяти функции, чтобы она не была убита при удалении item-a
			bool bFound=false;
			ShowProperties();
			for(int i=0; i<m_doc_local->m_items.GetSize();i++)
			{
				if(this==m_doc_local->m_items[i]) {bFound=true; break;}
			}
			if(!bFound) return; // текущий экземпляр был убит в ShowProperties
			RefreshItem();
			/*this->RefreshItem(); */
		}
		break;
	case ID_EDIT_COPY: ((CNavigatorView*)m_tree)->OnCopy(); break;
	case ID_EDIT_PASTE: ((CNavigatorView*)m_tree)->OnPaste(); break;

	case ID_FREZEE_INST:
		FrezeInstances();
		break;
	case ID_SHOW_ALL_VERSION:ShowAllVersion();break;
	case ID_SET_INST_ACCSESS: SetInstancesAccess();	break;
	case ID_SET_INST_ACCSESS_RECURSIVE: SetInstancesAccessRecursive();	break;
	case ID_SET_INST_OWNER:	SetInstancesOwner();break;
	case ID_REFRESH_ITEM:   RefreshItem(); break;
	case ID_SHOW_ALL_CHARACTERISTIC: ShowAllCharacteristic(true);break;
	case ID_SHOW_ALL_APPROVAL: ShowAllApproval(true); break;
	case ID_SHOW_ALL_DOCS: ShowAllDocs();break;
	case ID_CREATE_APPROVAL: CreateApproval();break;
	case ID_CREATE_NOTE: CreateNote(); break;
	case ID_SHOW_NOTES: ShowNotes(); break;
	case ID_CREATE_DOC:
		{
			aplExtent ext;
			GetMainInstances(ext);
			if(ext.Size>0)CreateDoc(ext[0]);
			else CreateDoc();
		}
		break;
	default:
		{
			if(command>=ID_ACCESS_PATTERN_00 && command <ID_ACCESS_PATTERN_29){
				CString pattern;
				int indx=command-ID_ACCESS_PATTERN_00;
				if(indx>m_doc->m_AccessPatterns.GetSize()){
					return;
				}
				m_doc_data.GetAttr(m_doc->m_AccessPatterns.GetAt(indx),
					m_doc->m_api.m_appr_mgr.a_apl_acc_pat_pattern,pattern);
				SetAccessFromPattern(pattern);
			}
			for(int i= 0; i<m_doc->m_addin_menu_items.GetSize(); i++)
			{
				CaplAddInMenuItem &addinitem=m_doc->m_addin_menu_items[i];

				if(command==addinitem.m_id && 	addinitem.m_pFunc)
				{
					aplExtent ext;
					m_addInCall= true;
					GetMainInstances(ext);
					m_addInCall= false;

					if(m_type==APL_TREE_ITEM_PRODUCT)
					{
						CaplProductTreeItem* prod_item= (CaplProductTreeItem*)m_tree->GetItemData(m_item);
						if(prod_item->m_nauo)
							ext.Add(prod_item->m_nauo);
					}

					bool bUI= false;
					
					if(addinitem.m_iFuncParamType<=0)
					{
						addinitem.m_pFunc(&m_doc->m_api, ext, bUI);
					}
					else if(1==addinitem.m_iFuncParamType)
					{
						aplExtent ext_out;
						int iCmd=aplPluginCommandNo;
						LPADDINFUNCTION_v1 FuncV1=(LPADDINFUNCTION_v1) addinitem.m_pFunc;
						FuncV1(&m_doc->m_api, ext, bUI,ext_out,iCmd);

						switch(iCmd)
						{
						case aplPluginCommandOpenInNewWindow:
							{
								m_doc->OpenExtentInNewWindow(ext_out,0);
							}
							break;
						}
					}
					else if(2==addinitem.m_iFuncParamType)
					{
						aplExtent ext_out;
						int iCmd=aplPluginCommandNo;
						CString sStr;
						LPADDINFUNCTION_v2 FuncV2=(LPADDINFUNCTION_v2) addinitem.m_pFunc;
						FuncV2(&m_doc->m_api, ext, bUI,ext_out,iCmd,sStr);

						switch(iCmd)
						{
						case aplPluginCommandOpenInNewWindow:
							{
								m_doc->OpenExtentInNewWindow(ext_out,LPCTSTR(sStr));
							}
							break;
						}
					}
					RefreshItem();
					return;
				}
			}
			/* Убрана поддержка форм им. Орлова
			{
				//	поиск по формам
				aplExtent		aeInInsts,aeOutInsts,aet;
				CaplInstance*	cit		=NULL;
				CaplInstance*	ciFldr	=NULL;

				BOOL			bRet	=FALSE;
				BOOL			bFolder =FALSE;

				int				i,j;

				GetMainInstances(aeInInsts);

				for(i=0;i<m_doc->m_caFormMenuItems.GetSize();i++)
				{
					FormMenuItem item=m_doc->m_caFormMenuItems.GetAt(i);
					if(command==item.m_iID)
					{
						if(aeInInsts.GetSize()!=0)
						{
							cit=aeInInsts.GetAt(0);
							if(cit->GetType()!=0)
							{
								if(cit->GetType()==m_doc->m_api.m_folder_mgr.e_folder)
								{
									aeInInsts.Clear();
									ciFldr=cit;
									bFolder=TRUE;
								}
							}
						}
						bRet=m_doc->m_form_mgr_dlg.ShowForm(&m_doc->m_api,item.m_ciForm,
															aeInInsts,aeOutInsts,NULL,_T(""),_T(""));
						if(TRUE==bRet && TRUE==bFolder)
						{
							for(j=0;j<aeOutInsts.GetSize();j++)
							{
								cit=aeOutInsts.GetAt(j);
								if(cit->GetType()->name==item.m_csBaseInstEntName)
									m_doc->m_api.m_folder_mgr.AddToFolder(ciFldr,cit);
							}
							((CaplFolderTreeItem*)this)->ShowContents();
							
						}
						RefreshItem();
					}
				}
			}*/
		}
	}
}
//*********************************************************************
bool CaplTreeItem::InsertInstInTree(CaplInstance *inst,
							HTREEITEM item,
							CPSMDoc *doc,
							CTreeCtrl *tree,
							aplExtent &contents,
							CaplInstance *folder,
							CaplTreeItem **result_item,
							CaplInstance *classifier,
							bool bShowNoteIcon)
{
	if(inst==0) return false;
	if(inst->GetType()==0) return false;
	if(result_item!=0) *result_item=0;
	if(-1!=contents.Find(inst)) return false;
	CaplTreeItem *new_item=0;
	bool retval=true;

	if(doc_data.IsKindOf(inst,doc->m_api.m_prd_mgr.e_prd))
	{
		// Изделие
		CaplProductTreeItem *product_item=
			new CaplProductTreeItem(tree,doc,inst);
		product_item->CreateTreeItem(item);
		product_item->m_folder=folder;
		product_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=product_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_prd_mgr.e_pdf))
	{
		// Версия изделия
		CaplProductTreeItem *product_item=
			new CaplProductTreeItem(tree,doc,0,inst);
		product_item->CreateTreeItem(item);
		product_item->m_folder=folder;
		product_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=product_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_query_mgr.e_apl_query))
	{
		// Запрос
		CaplQueryTreeItem *query_item=
			new CaplQueryTreeItem(tree,doc,inst);
		query_item->CreateTreeItem(item);
		query_item->m_folder=folder;
		query_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=query_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_query_mgr.e_apl_ct))
	{
		// Запрос
		CaplQueryTreeItem *query_item=
			new CaplQueryTreeItem(tree,doc,inst);
		query_item->CreateTreeItem(item);
		query_item->m_folder=folder;
		query_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=query_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_doc_mgr.e_doc))
	{
		// Документ
		CaplDocTreeItem *doc_item= new CaplDocTreeItem(tree,doc,inst);
		doc_item->CreateTreeItem(item);
		doc_item->m_folder=folder;
		doc_item->m_classifier=classifier;
		doc_item->m_bWOForNote= bShowNoteIcon;
		contents.Add(inst);
		new_item=doc_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_req_mgr.e_requirement))
	{
		// Требование
		CaplRequirementTreeItem *req_item= new CaplRequirementTreeItem(tree,doc,inst);
		req_item->CreateTreeItem(item);
		contents.Add(inst);
		new_item=req_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_doc_mgr.e_apl_doc_rev))
	{
		// Версия Документа
		CaplInstance *main;
		doc_data.GetAttr(inst,doc->m_api.m_doc_mgr.a_apl_doc_rev_doc,main);

		CaplDocTreeItem *doc_item= new CaplDocTreeItem(tree,doc,main,0,inst);
		doc_item->CreateTreeItem(item);
		doc_item->m_folder=folder;
		doc_item->m_classifier=classifier;
		doc_item->m_bWOForNote= bShowNoteIcon;
		contents.Add(inst);
		new_item=doc_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_bp_mgr.e_bp))
	{
		// бизнес-процесс
		CaplBPTreeItem *act_item= new CaplBPTreeItem(tree,doc,inst);
		act_item->CreateTreeItem(item);
		act_item->m_folder=folder;
		act_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=act_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_bp_mgr.e_apl_bp_inst))
	{
		// экземпляр бизнес-процесса
		CaplBPInstTreeItem *act_item= new CaplBPInstTreeItem(tree,doc,inst);
		act_item->CreateTreeItem(item);
		act_item->m_folder=folder;
		act_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=act_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_bp_mgr.e_bp_res))
	{
		// ресурс
		CaplBPResourceTreeItem *act_item= new CaplBPResourceTreeItem(tree,doc,inst);
		act_item->CreateTreeItem(item);
		contents.Add(inst);
		new_item=act_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_bp_mgr.e_apl_bp_ver))
	{
		CaplInstance *main;
		doc_data.GetAttr(inst,doc->m_api.m_bp_mgr.a_bp_ver_bp,main);

		// Версия бизнес-процесс
		CaplBPTreeItem *act_item= new CaplBPTreeItem(tree,doc,main);
		act_item->m_rev=inst;
		act_item->CreateTreeItem(item);
		act_item->m_folder=folder;
		act_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=act_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_prd_inst_mgr.e_lot))
	{
		// Партия
		CaplLotTreeItem *lot_item= new CaplLotTreeItem(tree,doc,inst);
		lot_item->CreateTreeItem(item);
		lot_item->m_folder=folder;
		lot_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=lot_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_prd_inst_mgr.e_prd_inst))
	{
		// Экземпляр изделия
		CaplPrdInstTreeItem *inst_item= new CaplPrdInstTreeItem(tree,doc,inst);
		inst_item->CreateTreeItem(item);
		inst_item->m_folder=folder;
		inst_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=inst_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_categ_mgr.e_categ))
	{
		// Категория
		CaplCategoryTreeItem *categ_item=
			new CaplCategoryTreeItem(tree,doc,0,inst);
		categ_item->CreateTreeItem(item);
		categ_item->m_folder=folder;
		categ_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=categ_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_folder_mgr.e_folder))
	{
		//Ярлык на папку
		CaplFolderTreeItem *fi=new CaplFolderTreeItem(tree,doc,0,inst);
		fi->m_folder= folder;
		fi->m_classifier=classifier;
		fi->CreateTreeItem(item);
		contents.Add(inst);
		//m_sub_folders.Add(ext[i]);
		new_item=fi;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_change_mgr.e_chng))
	{
		//Изменение
		CaplChangeTreeItem *change_item=
			new CaplChangeTreeItem(tree, doc, inst);
		change_item->CreateTreeItem(item);
		change_item->m_folder= folder;
		change_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=change_item;
	}
	else if(doc_data.IsKindOf(inst, doc->m_wf_mgr.e_task))
	{
		//Задание
		CaplTaskTreeItem *task_item= 
			new CaplTaskTreeItem(tree, doc, inst, APL_WF_SHOW_WO);
		task_item->CreateTreeItem(item);
		contents.Add(inst);
		new_item= task_item;		
	}
	else if(doc_data.IsKindOf(inst, doc->m_wf_mgr.e_proc))
	{
		//Процесс
		CaplProcessTreeItem *proc_item= 
			new CaplProcessTreeItem(tree, doc, inst);
		proc_item->CreateTreeItem(item);
		proc_item->m_folder= folder;
		contents.Add(inst);
		new_item= proc_item;		
	}
	else if(doc_data.IsKindOf(inst, doc->m_wf_mgr.e_proc_tmpl))
	{
		//Процесс
		CaplProcessTmplTreeItem *proc_tmpl_item= 
			new CaplProcessTmplTreeItem(tree, doc, inst);
		proc_tmpl_item->CreateTreeItem(item);
		proc_tmpl_item->m_folder= folder;
		contents.Add(inst);
		new_item= proc_tmpl_item;		
	}
	else if(doc_data.IsKindOf(inst, doc->m_project_mgr->e_project))
	{
		//Проект
		CaplProjectTreeItem *proj_item= 
			new CaplProjectTreeItem(tree, doc, inst);
		proj_item->CreateTreeItem(item);
		proj_item->m_folder=folder;
		proj_item->m_classifier=classifier;
		contents.Add(inst);
		new_item= proj_item;		
	}
	else if(doc_data.IsKindOf(inst, doc->m_api.m_expl_mgr->e_apl_refusal))
	{
		//Неисправность
		CaplRefusalTreeItem *refusal_item = new CaplRefusalTreeItem(tree, doc, inst, folder);
		refusal_item->CreateTreeItem(item);
		contents.Add(inst);
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_classifier_mgr.e_apl_classifier_level))
	{
		//Элемент структуры справочника
		CaplInstance *system;
		doc_data.GetAttr(inst,doc->m_api.m_classifier_mgr.a_apl_classifier_level_system,system);
		CaplClassifierTreeItem *ce_item = new CaplClassifierTreeItem(tree, doc, inst,system,folder);
		ce_item->CreateTreeItem(item);
		contents.Add(inst);
		new_item = ce_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_classifier_mgr.e_apl_classifier_system))
	{
		//Справочник
		CaplClassifierTreeItem *cs_item = new CaplClassifierTreeItem(tree, doc, inst,0,folder);
		cs_item->CreateTreeItem(item);
		contents.Add(inst);
		new_item = cs_item;
		cs_item->m_classifier=classifier;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_appr_mgr.e_org))
	{
		CaplOrganizationTreeItem *org = new CaplOrganizationTreeItem(tree, doc, inst);
		org->m_folder=folder;
		org->m_classifier=classifier;
		org->CreateTreeItem(item);
		contents.Add(inst);
		new_item = org;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_appr_mgr.e_person))
	{
		CaplPersonTreeItem *org = new CaplPersonTreeItem(tree,doc,inst,0);
		org->m_folder=folder;
		org->CreateTreeItem(item);
		contents.Add(inst);
		new_item = org;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_appr_mgr.e_official))
	{
		CaplPersonTreeItem *org = new CaplPersonTreeItem(tree,doc,inst,0);
		org->m_folder=folder;
		org->CreateTreeItem(item);
		contents.Add(inst);
		new_item = org;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_message_mgr.e_alert))
	{
		CaplAlertTreeItem *alert = new CaplAlertTreeItem(tree,doc,inst);
		alert->CreateTreeItem(item);
		contents.Add(inst);
		new_item = alert;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_doc_mgr.e_doc_copy))
	{
		// Копия документа
		CaplDocCopyTreeItem *doc_copy_item= new CaplDocCopyTreeItem(tree,doc,inst);
		doc_copy_item->CreateTreeItem(item);
		doc_copy_item->m_folder=folder;
		doc_copy_item->m_classifier=classifier;
		contents.Add(inst);
		new_item=doc_copy_item;
	}
	else if(doc_data.IsKindOf(inst,doc->m_api.m_message_mgr.e_message))
	{
		//Сообщение
		CString buf;
		doc_data.GetAttr(inst, doc->m_api.m_message_mgr.a_message_status, buf);
		
		CaplInstance* person= doc->m_api.m_appr_mgr.GetCurrentPerson();
		CaplInstance 	*sender, *recipient;
		
		doc_data.GetAttr(inst, doc->m_api.m_message_mgr.a_message_sender, sender);
		doc_data.GetAttr(inst, doc->m_api.m_message_mgr.a_message_recipient, recipient);
		
		bool bKill= false;

		if(sender==person)
		{
			doc_data.GetAttr(inst, doc->m_api.m_message_mgr.a_message_sender_kill, bKill);

			if(!bKill)
			{
/*если сообщение помещено в папку  - его показываем всегда до удаления 
				doc_data.GetAttr(inst, doc->m_api.m_message_mgr.a_message_sender_folder, inst0);
				if(!inst0 || inst0!=folder)//не он помещал сообщение
					bKill= true;*/
			}
		}
		else if(recipient==person)
		{
			doc_data.GetAttr(inst, doc->m_api.m_message_mgr.a_message_recipient_kill, bKill);
			if(!bKill)
			{
/*если сообщение помещено в папку  - его показываем всегда до удаления 
				doc_data.GetAttr(inst, doc->m_api.m_message_mgr.a_message_recipient_folder, inst0);
				if(!inst0 || inst0!=folder)//не он помещал сообщение
					bKill= true;*/
			}

			if(buf!=_T("draft"))
			{
				doc_data.GetAttr(inst, doc->m_api.m_message_mgr.a_message_date_received, buf);
				if(buf.IsEmpty())//записываем дату получения сообщения
				{
					COleDateTime odt;
					doc_data.NET_GetServerDateTime(odt);
					aplDate2String(odt, buf);
					doc_data.PutAttr(inst, doc->m_api.m_message_mgr.a_message_date_received, buf);
					doc_data.NET_SaveChanges();
				}
			}
		}
		else //смотрит не понятно кто...
		{
			
		}
		
		if(!bKill)
		{
			//меняем отправителю на рассылку, если кто-то из получателей
			//положил копию.
// Непонятный кусок кода - я так и не смог понять, зачем вызыватся функция ReplaceMesInstance. DIV
// 			CaplInstance* fld;
// 			doc_data.GetAttr(inst, doc->m_api.m_message_mgr.a_message_sender_folder, fld);
// 			if(fld!=folder)//это не он тута запихнул
// 				CaplMessageTreeItem::ReplaceMesInstance(doc, &inst);


			CaplMessageTreeItem *mes_item= new CaplMessageTreeItem
				(tree, doc, inst);
			mes_item->CreateTreeItem(item);
			mes_item->m_classifier=classifier;
			if(TVI_ROOT!=item)
			{
				CaplTreeItem* fldItem= (CaplTreeItem*)tree->GetItemData(item);
				if(fldItem->m_type==APL_TREE_ITEM_FOLDER)
				{			
					mes_item->m_folder= folder;
					mes_item->m_folderItem= (CaplFolderTreeItem*)fldItem;
				}
			}
			contents.Add(inst);
			new_item= mes_item;


// Непостижимый кусок кода - я так и не смог понять, за что папкам такие тормоза. DIV
// 			//создали
// 			if(-1==contents.Find(inst))
// 			{
// 				CaplMessageTreeItem *mes_item= new CaplMessageTreeItem
// 					(tree, doc, inst);
// 				mes_item->CreateTreeItem(item);
// 				mes_item->m_classifier=classifier;
// //				contents.Add(inst);
// 				//на всякий случай только для папок
// 				CaplTreeItem* fldItem= (CaplTreeItem*)tree->GetItemData(item);
// 				if(fldItem->m_type==APL_TREE_ITEM_FOLDER)
// 				{
// 					mes_item->m_folder= folder;
// 					mes_item->m_folderItem= (CaplFolderTreeItem*)fldItem;
// 					
// 					//после new... inst может быть != mes_item->m_message				
// /*					for(int n= 0; n<mes_item->m_copyMessages.GetSize(); n++)
// 					{
// 						
// 					}
// 
// 					if(inst!=mes_item->m_message) 
// 						((CaplFolderTreeItem*)fldItem)->m_hided_messages.Add(inst);
// */
// 					if(-1!=contents.Find(mes_item->m_message))
// 					{
// 						//чтобы не дублировались сообщения в папке 
// 						doc->m_items.Remove(doc->m_items.Find(mes_item));
// 					}
// 					else
// 					{
// 						contents.Add(mes_item->m_message);
// 						new_item= mes_item;
// 					}
// 				}
// 				
// 			}
		}
	}else{
		retval=false;
	}

	if(new_item!=0)
	{
		new_item->m_bWOForNote= bShowNoteIcon;
		new_item->RefreshItem();
		if(result_item!=0) *result_item=new_item;
	}
	return retval;
}
//*********************************************************************
void CaplTreeItem::Sort(bool bRefreshParent)
{
	if(m_tree==0) return;
	if(m_item==0) return;

	if(bRefreshParent)
	{
		if (m_tree->ItemHasChildren(m_item))
		{
		   HTREEITEM hChildItem = m_tree->GetChildItem(m_item);

		   while (hChildItem != NULL)
		   {
				CaplTreeItem *item=(CaplTreeItem*)m_tree->GetItemData(hChildItem);
				if(item!=0)item->RefreshItem();
				hChildItem = m_tree->GetNextItem(hChildItem, TVGN_NEXT);
		   }
		}
	}
	TVSORTCB sortcb;
	sortcb.hParent=m_item;
	sortcb.lpfnCompare=CompareHtreeItem;
	sortcb.lParam=1;
	m_tree->SortChildrenCB(&sortcb);
}
//****************************************************************
void CaplTreeItem::AppendAddIn(CMenu *popupMenu)
{
	if(!popupMenu) return;
	
	CMenu* pSubMenu= NULL;
	
/*	for(int i= 0; i<m_sub_menu.GetSize(); i++)
	{
		if(m_sub_menu[i])
		{
			m_sub_menu[i]->DestroyMenu();
			delete m_sub_menu[i];
		}
	}
	m_sub_menu.RemoveAll();*/

	for(int i= 0; i<m_doc->m_addin_menu_items.GetSize(); i++)
	{
		CaplAddInMenuItem &addinitem=m_doc->m_addin_menu_items[i];
		//наш или не наш клиент?
		if(m_type==addinitem.m_itemType && addinitem.m_mEnable)
		{
			CString tmp, name, buf= addinitem.m_menuName;			
			
			buf.Remove(_T('&'));

			pSubMenu=popupMenu;
			while(true)
			{
				int index= buf.Find(_T('\\'));
				if(-1==index)//корневой элемент
				{
					int iPos= buf.Find(_T(']'));
					if(-1!=iPos)
					{
						int n= buf.Find(_T('['));
						if(-1==n){iPos= -1;}
						else 
						{
							tmp= buf.Mid(n+1, iPos-n-1);
							buf= buf.Right(buf.GetLength()-iPos-1);
							iPos= _atoi(tmp);
						}
					}		
					
					int smCnt = pSubMenu->GetMenuItemCount();
					iPos = iPos>smCnt ? smCnt : iPos;
					if(!buf.IsEmpty())
					{
						pSubMenu->InsertMenu(iPos, MF_BYPOSITION|MF_STRING, m_doc->m_addin_menu_items[i].m_id, buf);
						
						aplExtent ext;
						GetMainInstances(ext);
						
						if(m_type==APL_TREE_ITEM_PRODUCT)
						{
							CaplProductTreeItem* prod_item= (CaplProductTreeItem*)m_tree->GetItemData(m_item);
							if(prod_item->m_nauo)
								ext.Add(prod_item->m_nauo);
						}
						
						bool bUI= true, bEnable=false;;

						if(addinitem.m_iFuncParamType<=0)
						{
							bEnable=addinitem.m_pFunc(&m_doc->m_api, ext, bUI);
						}
						else if(1==addinitem.m_iFuncParamType)
						{
							aplExtent ext_out;
							int iCmd=aplPluginCommandNo;
							LPADDINFUNCTION_v1 FuncV1=(LPADDINFUNCTION_v1) addinitem.m_pFunc;
							bEnable=FuncV1(&m_doc->m_api, ext, bUI,ext_out,iCmd);
						}
						else if(2==addinitem.m_iFuncParamType)
						{
							aplExtent ext_out;
							int iCmd=aplPluginCommandNo;
							CString sStr;
							LPADDINFUNCTION_v2 FuncV2=(LPADDINFUNCTION_v2) addinitem.m_pFunc;
							bEnable=FuncV2(&m_doc->m_api, ext, bUI,ext_out,iCmd,sStr);
						}
						if(!bEnable)	pSubMenu->EnableMenuItem(addinitem.m_id, MF_BYCOMMAND|MF_GRAYED);
					}
					else 
					{
						pSubMenu->InsertMenu(iPos, MF_BYPOSITION|MF_SEPARATOR, 0, _T(""));
					}
					break;
				}
				else
				{
					CString str;
					name= buf.Left(index);
					tmp= buf.Right(buf.GetLength()-index-1);
					buf= tmp;
					
					int iPos= name.Find(_T(']'));
					if(-1!=iPos)
					{
						int n= name.Find(_T('['));
						if(-1==n){iPos= -1;}
						else 
						{
							tmp= name.Mid(n+1, iPos-n-1);
							name= name.Right(name.GetLength()-iPos-1);
							iPos= _atoi(tmp);
						}
					}

					CMenu *found_menu=0;

					int count= pSubMenu->GetMenuItemCount();
					for (int pos= 0; pos<count; pos++)
					{
						pSubMenu->GetMenuString(pos, str, MF_BYPOSITION);
						str.Remove(_T('&'));
						if(str.CompareNoCase(name)==0)
						{
							found_menu=(CMenu*)pSubMenu->GetSubMenu(pos);
							if(found_menu==0)
							{
/*								found_menu= new CMenu;
								m_sub_menu.Add(found_menu);

								found_menu->CreateMenu();
								UINT id= pSubMenu->GetMenuItemID(pos);
								found_menu->InsertMenu(-1, MF_BYPOSITION|MF_STRING, 
									id, str);
								pSubMenu->ModifyMenu(pos, MF_BYPOSITION|MF_POPUP, 
									(UINT)found_menu->GetSafeHmenu(), b1);*/
								continue;
							}
							
							break;
						}
					}
					if(found_menu==0)
					{
						found_menu= new CMenu;
						found_menu->CreateMenu();

						if(iPos<0) iPos=iPos+pSubMenu->GetMenuItemCount();
						if(iPos<0) iPos=0;

						pSubMenu->InsertMenu(iPos,MF_BYPOSITION|MF_POPUP,(UINT)found_menu->m_hMenu,name);

						found_menu->Detach();
						delete found_menu; found_menu=0;
						found_menu= pSubMenu->GetSubMenu(iPos); 

						if(0==found_menu) // На всякий случай
							found_menu= pSubMenu->GetSubMenu(pSubMenu->GetMenuItemCount()-1); 
					}
					pSubMenu=found_menu;
				}
			}
		}
	}

	//AppendForms(popupMenu); Убрана поддержка форм им. Орлова
	AppendAccessPattern(popupMenu);
}

void CaplTreeItem::AppendAccessPattern(CMenu* popupMenu)
{
	int pos,i,count;
	CString str;
	CMenu *found_menu, *popup_menu;
	aplExtent ext;
	GetAccessedInstances(ext);
	if(ext.GetSize()==0){return;}
	if(ext[0]->GetTemporary()){return;}
	if(ext[0]->GetType()==0){return;}

	m_doc_data.GetEntityExtent(m_doc->m_api.m_appr_mgr.e_apl_acc_pat,m_doc->m_AccessPatterns);
	if(m_doc->m_AccessPatterns.GetSize()==0) return;
	count = popupMenu->GetMenuItemCount();
	for (pos= 0; pos<count; pos++)
	{
		popupMenu->GetMenuString(pos, str, MF_BYPOSITION);
		str.Remove(_T('&'));
		if(str.CompareNoCase( APL_NO_T("Доступ"))==0 )
		{
			found_menu=(CMenu*)popupMenu->GetSubMenu(pos);
			if(found_menu==0)
			{
				continue;
			}
			
			popup_menu= new CMenu;
			popup_menu->CreateMenu();
			//found_menu->InsertODMenu(1,APL_T("Назначить доступ по шаблону.."),MF_BYPOSITION|MF_POPUP,(UINT)popup_menu->m_hMenu);
			found_menu->InsertMenu(1,MF_BYPOSITION|MF_POPUP,(UINT)popup_menu->m_hMenu, APL_T("Назначить доступ по шаблону.."));
			for(i=0;i<m_doc->m_AccessPatterns.GetSize();i++)
			{
				m_doc_data.GetAttr(m_doc->m_AccessPatterns.GetAt(i),
					m_doc->m_api.m_appr_mgr.a_apl_acc_pat_name,str);
				popup_menu->InsertMenu(i, MF_BYPOSITION|MF_STRING,ID_ACCESS_PATTERN_00+i, str);
			}
			popup_menu->Detach();
			delete popup_menu;
			break;
		}
	}
}
/* 
void CaplTreeItem::AppendForms(CMenu* popupMenu)
{
Убрана поддержка форм им. Орлова
	CMenu*		pm			=NULL;

	aplExtent		aeInsts;
	CaplInstance*	cit			=NULL;

	CStringArray	csaBase;
	CString			csBase;

	FormMenuItem	item;

	int				i,j,iPos=0,iItemCnt=0;

	GetMainInstances(aeInsts);
	if(0==aeInsts.GetSize())
		return;
	cit=aeInsts.GetAt(0);

	if(cit->GetType()==0)
		return;

	if(cit->GetType()==m_doc->m_api.m_folder_mgr.e_folder)
	{
		
		 Убрана поддержка форм им. Орлова
		for(i=0;i<m_doc->m_caFormMenuItems.GetSize();i++)
		{
			item=m_doc->m_caFormMenuItems.GetAt(i);
			if(item.m_ciForm->GetType()==0)
				continue;
			iItemCnt++;
		}
		if(0==iItemCnt)
			return;

		pm=new CMenu;
		pm->CreateMenu();

		iPos=popupMenu->GetMenuItemCount();
		iPos--;
		//popupMenu->InsertODMenu(iPos,_T(""),MF_BYPOSITION|MF_SEPARATOR);
		//popupMenu->InsertODMenu(iPos,APL_T("Создать с помощью форм.."),MF_BYPOSITION|MF_STRING|MF_POPUP,(UINT)pm->m_hMenu);
		popupMenu->InsertMenu(iPos,MF_BYPOSITION|MF_SEPARATOR,123,_T(""));
		popupMenu->InsertMenu(iPos,MF_BYPOSITION|MF_STRING|MF_POPUP,(UINT)pm->m_hMenu, APL_T("Создать с помощью форм.."));

		for(i=0;i<m_doc->m_caFormMenuItems.GetSize();i++)
		{
			item=m_doc->m_caFormMenuItems.GetAt(i);
			if(item.m_ciForm->GetType()==0)
				continue;
			//pm->InsertODMenu(-1,item.m_csFormName,MF_BYPOSITION,item.m_iID);
			pm->AppendMenu(MF_STRING,item.m_iID,item.m_csFormName);
		}

	}
	else
	{

		/* Убрана поддержка форм им. Орлова
		// проверяем - есть ли чего добавлять
		for(i=0;i<m_doc->m_caFormMenuItems.GetSize();i++)
		{
			item=m_doc->m_caFormMenuItems.GetAt(i);
			if(item.m_ciForm->GetType()==0)
				continue;
			if(item.m_csBaseInstEntName==cit->GetType()->name)
				iItemCnt++;
		}

		m_doc->m_form_mgr_dlg.GetBaseForLinked(_T(""),cit->GetType()->name,csaBase);
		for(i=0;i<csaBase.GetSize();i++)
		{
			csBase=csaBase.GetAt(i);
			for(j=0;j<m_doc->m_caFormMenuItems.GetSize();j++)
			{
				item=m_doc->m_caFormMenuItems.GetAt(j);
				if(item.m_ciForm->GetType()==0)
					continue;
				if(item.m_csBaseInstEntName==csBase)
				{
					iItemCnt++;
				}
			}
		}


		if(0==iItemCnt /*&& 0==csaBase.GetSize()*//*)
			return;

		pm=new CMenu;
		pm->CreateMenu();

		iPos=popupMenu->GetMenuItemCount();
		iPos--;

		//popupMenu->InsertODMenu(iPos,_T(""),MF_BYPOSITION|MF_SEPARATOR);
		//popupMenu->InsertODMenu(iPos,APL_T("Формы"),MF_BYPOSITION|MF_STRING|MF_POPUP,(UINT)pm->m_hMenu);
		popupMenu->InsertMenu(iPos,MF_BYPOSITION|MF_SEPARATOR,123,_T(""));
		popupMenu->InsertMenu(iPos,MF_BYPOSITION|MF_STRING|MF_POPUP,(UINT)pm->m_hMenu, APL_T("Формы"));
		for(i=0;i<m_doc->m_caFormMenuItems.GetSize();i++)
		{
			item=m_doc->m_caFormMenuItems.GetAt(i);
			if(item.m_ciForm->GetType()==0)
				continue;
			if(item.m_csBaseInstEntName==cit->GetType()->name)
				//pm->InsertODMenu(-1,item.m_csFormName,MF_BYPOSITION,item.m_iID);
				pm->AppendMenu(MF_STRING,item.m_iID,item.m_csFormName);
		}
		
		//	добавляем формы со связкой

		for(i=0;i<csaBase.GetSize();i++)
		{
			csBase=csaBase.GetAt(i);
			for(j=0;j<m_doc->m_caFormMenuItems.GetSize();j++)
			{
				item=m_doc->m_caFormMenuItems.GetAt(j);
				if(item.m_ciForm->GetType()==0)
					continue;
				if(item.m_csBaseInstEntName==csBase)
				{
					CString cst;
					cst.Format(_T("*%s"),item.m_csFormName);
					//pm->InsertODMenu(-1,cst,MF_BYPOSITION,item.m_iID);
					pm->AppendMenu(MF_STRING,item.m_iID,cst);
				}
			}
		}
		
	}
	
}
*/

//****************************************************************
int CALLBACK CaplTreeItem::CompareHtreeItem(LPARAM lParam1, LPARAM lParam2,LPARAM lParamSort)
{
	if(lParam1==0) return 0;
	if(lParam2==0) return 0;
	CTreeCtrl *tree=((CaplTreeItem*)lParam1)->m_tree;
	if(tree==0) return 0;
	HTREEITEM item1=((CaplTreeItem*)lParam1)->m_item;
	HTREEITEM item2=((CaplTreeItem*)lParam2)->m_item;
	int img1,img2,img0;
	tree->GetItemImage(item1,img1,img0);
	tree->GetItemImage(item2,img2,img0);

	CaplAPI* api = &((CaplTreeItem*)lParam2)->m_doc->m_api;

	int rel1=0,rel2=0;
	int eff1=0,eff2=0;
	int state1=0,state2=0;
	
	CaplTreeItemData *itemdata1=(CaplTreeItemData*) tree->GetItemData(item1);
	if(itemdata1!=0)
	{
		if(itemdata1->icons[IDX_IL_TREE_ITEM]>0)
			img1=itemdata1->icons[IDX_IL_TREE_ITEM];
		if(itemdata1->icons[IDX_IL_TREE_REL_TYPE]>=0)
			rel1=itemdata1->icons[IDX_IL_TREE_REL_TYPE];
		//if(itemdata1->icons[IDX_IL_TREE_EFF]>=0)
		//	eff1=itemdata1->icons[IDX_IL_TREE_EFF];
		//if(itemdata1->icons[IDX_IL_TREE_STATE]>=0)
		//	state1=itemdata1->icons[IDX_IL_TREE_STATE];
	}
	
	CaplTreeItemData *itemdata2=(CaplTreeItemData*) tree->GetItemData(item2);
	if(itemdata2!=0)
	{
		if(itemdata2->icons[IDX_IL_TREE_ITEM]>0)
			img2=itemdata2->icons[IDX_IL_TREE_ITEM];
		if(itemdata2->icons[IDX_IL_TREE_REL_TYPE]>=0)
			rel2=itemdata2->icons[IDX_IL_TREE_REL_TYPE];
		//if(itemdata2->icons[IDX_IL_TREE_EFF]>=0)
		//	eff2=itemdata2->icons[IDX_IL_TREE_EFF];
		//if(itemdata2->icons[IDX_IL_TREE_STATE]>=0)
		//	state2=itemdata2->icons[IDX_IL_TREE_STATE];
	}
	
	int compare = api->aplCompareItemsImage(img1, img2);
	
	if(compare==0)
	{
		if((itemdata1!=0) && (itemdata2!=0))
		{
			CaplTreeItem *treeitem1=(CaplTreeItem*)itemdata1;
			CaplTreeItem *treeitem2=(CaplTreeItem*)itemdata2;

			if(treeitem1->m_type==_T("Approval"))
			{
				// сравниваем 2 статуса
				CaplAPI *api=&(treeitem1->m_doc->m_api);

				CString date1, date2;
				api->m_data.GetAttr(((CaplApprovalTreeItem*)treeitem1)->m_appr,api->m_appr_mgr.a_appr_appr_date_time_s,date1);
				api->m_data.GetAttr(((CaplApprovalTreeItem*)treeitem2)->m_appr,api->m_appr_mgr.a_appr_appr_date_time_s,date2);
				return date1.Compare(date2);
			}
			if(treeitem1->m_type==_T("Task"))
			{
				// сравниваем 2 задания
				return CaplProcessTreeItem::CompareTaskTreeItem(lParam1,lParam2,lParamSort);
			}
			else if(treeitem1->m_type==APL_TREE_ITEM_PROJECT)
			{
				// сравниваем 2 проекта 
				if(CPSMDoc::m_bSortPrjByNumzak==TRUE)
				{
					CaplAPI *api=&(treeitem1->m_doc->m_api);
					CString snum1, snum2;
					api->m_data.GetAttr(((CaplProjectTreeItem*)treeitem1)->m_inst,api->m_project_mgr->a_project_number,snum1);
					api->m_data.GetAttr(((CaplProjectTreeItem*)treeitem2)->m_inst,api->m_project_mgr->a_project_number,snum2);
					int inum1=_atoi(snum1);
					int inum2=_atoi(snum2);
					if(inum1!=inum2) {return (inum1>inum2);}
				}
				return aplCompareNumericStr(LPCTSTR(tree->GetItemText(item1)),LPCTSTR(tree->GetItemText(item2)));
			}
			else if(treeitem1->m_type==APL_TREE_ITEM_DOCUMENT)
			{
				if(((CaplDocTreeItem*)treeitem1)->m_rev!=0 && ((CaplDocTreeItem*)treeitem2)->m_rev!=0)
				{
					// Сравниваем версии
					CaplAPI *api=&(treeitem1->m_doc->m_api);
					CString v1, v2;
					api->m_data.GetAttr(((CaplDocTreeItem*)treeitem1)->m_rev,api->m_doc_mgr.a_apl_doc_rev_id,v1);
					api->m_data.GetAttr(((CaplDocTreeItem*)treeitem2)->m_rev,api->m_doc_mgr.a_apl_doc_rev_id,v2);
					int inum1=_atoi(v1);
					int inum2=_atoi(v2);
					return (inum1>inum2);
				}
			}
			else if(treeitem1->m_type==treeitem2->m_type && treeitem1->m_type==_T("ClassifierLevel"))
			{
				return aplCompare2StringAsClassifier(tree->GetItemText(item1),tree->GetItemText(item2));
			}
		}
		
		if(rel1<rel2) return -1;
		if(rel1>rel2) return  1;
		if(eff1>eff2) return 1;
		if(eff1<eff2) return -1;
		if(state1<state2) return -1;
		if(state1>state2) return 1;
		return (tree->GetItemText(item1)).Compare(tree->GetItemText(item2));
	}
	else
	{
		return compare;
	}
} 
//****************************************************************
void CaplTreeItem::ExpandAll(int &level, bool showdlg, CWinThread *par_trd, BOOL contents, BOOL doc, BOOL appr, 
			                   BOOL charact, BOOL material, BOOL lot, BOOL prdinst, BOOL act, BOOL res,BOOL subst, BOOL req)
{
	if(m_doc==0) return;

	DWORD tick1;
	bool show_time=false;
	
	aplExtent ext;
	GetAccessedInstances(ext);
	if(ext.Size>0)
	{
		if(ext[0]->GetAccessmode()>aplRO) return;
	}
	
	static bool bEndExpand=false;
	static int cur_level=0;
	static bool bIsActive=true;
	
	CWinThread* trd=0, *trd1=0;
	if(showdlg)
	{
		CExpandAllDlg dlg;
		if( dlg.DoModal()!=IDOK) return;
		contents=dlg.m_contents; doc=dlg.m_doc; appr=dlg.m_appr;
		charact=dlg.m_charact;	material=dlg.m_mater; 
		lot=dlg.m_lot; prdinst=dlg.m_prdinst; req=dlg.m_req;
		level=dlg.m_levels; res=dlg.m_res; act=dlg.m_act;
		subst=dlg.m_subst; 
		show_time=dlg.m_show_time;
		if(show_time)
		{
			// запускаем на сервере трассировку
			m_doc_data.NET_Test(0,1);
			tick1=GetTickCount();
		}
		bEndExpand=false;
	}

	if(bEndExpand) return;
	
	if(level<1) return;
	level--;
	cur_level++;
	if(par_trd==0)
	{
// DIV 06_05_02	trd=AfxBeginThread(CancelDlgThreadProc,&bEndExpand);
		trd=AfxBeginThread(RUNTIME_CLASS(CCancelDlgThread), THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
		((CCancelDlgThread*)trd)->m_bEndExpand=&bEndExpand;
		((CCancelDlgThread*)trd)->m_cur_level=&cur_level;
		((CCancelDlgThread*)trd)->m_bIsActive=&bIsActive;
		trd->ResumeThread();

		trd1=trd;
	} else trd1=par_trd;
	

	m_tree->SetRedraw(FALSE);
	try{
		bool bOldVal=m_bShowNoFoundMessage;
		m_bShowNoFoundMessage=false;
		if(contents)ShowCmd(ID_SHOW_ALL_CONTENTS);
		if(bEndExpand) {throw (int)0;}
		if(doc)		ShowCmd(ID_SHOW_ALL_DOCS);
		if(bEndExpand) {throw (int)0;}
		if(material)ShowCmd(ID_PRODUCT_SHOW_ALL_ZAGOTOV);
		if(bEndExpand) {throw (int)0;}
		if(charact)ShowCmd(ID_SHOW_ALL_CHARACTERISTIC);
		if(bEndExpand) {throw (int)0;}
		if(appr)ShowCmd(ID_SHOW_ALL_APPROVAL);
		if(bEndExpand) {throw (int)0;}
		if(lot)ShowCmd(ID_SHOW_ALL_LOT);
		if(bEndExpand) {throw (int)0;}
		if(prdinst)ShowCmd(ID_SHOW_ALL_PRD_INST);
		if(bEndExpand) {throw (int)0;}
		if(act)ShowCmd(ID_SHOW_ALL_BP);
		if(bEndExpand) {throw (int)0;}
		if(res)ShowCmd(ID_SHOW_ALL_BP_RESOURCE);
		if(bEndExpand) {throw (int)0;}
		if(subst)ShowCmd(ID_SHOW_ALL_SUBSTITUTES);
		if(bEndExpand) {throw (int)0;}
		if(req)ShowCmd(ID_SHOW_CHILDS);

		m_tree->SetRedraw(TRUE);
		PumpTimerPaint();
		
		m_bShowNoFoundMessage=bOldVal;
		if(bEndExpand) {throw (int)0;}
		
		CArray <HTREEITEM,HTREEITEM> treeitems;
		
		HTREEITEM item=m_tree->GetChildItem(m_item);
		while (item != NULL)
		{
			if(bEndExpand) {throw (int)0;}
			treeitems.Add(item);
			item = m_tree->GetNextSiblingItem(item);
		}
		
		int i;
		for(i=0;i<treeitems.GetSize();i++)
		{
			PumpTimerPaint();
			if(bEndExpand) {throw (int)0;}
			item=treeitems[i];
			CaplTreeItem *treeitem=(CaplTreeItem*)m_tree->GetItemData(item);
			if(treeitem==this) continue;
			if(treeitem!=0)  
				treeitem->ExpandAll(level, false,trd1, contents, doc, appr, charact, material, lot, prdinst, act,res,subst);
		}
	}
	catch(int )
	{
		m_tree->SetRedraw(TRUE);
	}

	
	level++;
	// DIV 06_06_02
	cur_level--;
	CWnd *wnd=AfxGetMainWnd();
	PumpTimerPaint();
	bIsActive=wnd==wnd->GetForegroundWindow();
//	CString str;str.Format(_T("wnd 0x%x ct 0x%x\n"),wnd,wnd->GetActiveWindow());
//	OutputDebugString(str);
	
	if(trd!=0){
		if(trd->m_hThread!=0){
			trd->PostThreadMessage(WM_QUIT,0,0);
		}
	}
	if(showdlg)
	{
		if(show_time)
		{
			// останавливаем на сервере трассировку+выводим ее в лог
			m_doc_data.NET_Test(0,0);

			CString str;
			str.Format( APL_T("Выполнено за %i миллисекунд"),GetTickCount()-tick1);
			AfxMessageBox(str);
		}
	}

}

CaplTreeItem* CaplTreeItem::GetParentItem(CaplTreeItem *item)
{
	if(m_tree ==0)return 0;
	if(::IsWindow(m_tree->m_hWnd)==FALSE)return 0;
	HTREEITEM par_item=	m_tree->GetParentItem(item->m_item);
	for(int i=0;i<m_doc->m_items.Size;i++)
	{
		if(m_doc->m_items[i]->m_item==par_item)
		{
			return m_doc->m_items[i];
		}
	}
	return 0;
}


void CaplTreeItem::ShowInstanceInfoInListCtrl(aplExtent &ext, CListCtrl *list,CStringArray *comment)
{
	if(ext.Size==0) return;
	if(list==0) return;
	if(CPSMDoc::m_show_inst_info!=TRUE) return;

	//m_doc_data.NET_ViewInstUserDataTimeInfo(ext,comment);
	
	CaplInstance* inst;
	CaplTAggr<SInstInfo*,SInstInfo*,APLAGGR_AUTOKILLREF> data;
	SInstInfo* el;
	COleDateTime odt;
	CString buf,buf1;
	int i,j,k;
	bool res;
	CUIntArray comment_map;

	if(ext.GetSize()==0){return;}
	for(i=0;i<ext.GetSize();i++){
		inst=ext.GetAt(i);
		if(inst==0)continue;
		if(inst->GetAccessmode()==aplNO)continue;
		
		el=new SInstInfo(ext.GetAt(i));
		data.Add(el);
		comment_map.Add(i);
	}
	if(data.GetSize()==0)return;
	res=m_doc_data.NET_LoadInstUserDataTimeInfo(data);
	if(!res){
		return;
	}

	for(i=0;i<data.Size;i++)
	{
		k=comment_map.GetAt(i);
		if(k>=ext.GetSize())
			continue;
		inst=ext.GetAt(k);
		j=list->InsertItem(list->GetItemCount(),_T(""));
		
		if(comment!=0){
			if(comment->GetSize()>k){
				j=list->InsertItem(list->GetItemCount(), APL_T("Комментарий"));
				list->SetItemText(j,1,comment->GetAt(k));
			}
		}
		j=list->InsertItem(list->GetItemCount(),_T("id"));
		if(inst==0){
			buf= APL_T("пустой объект");
			list->SetItemText(j,1,buf);
		}else{
			buf.Format(_T("%i (0x%0x) (temporary() = %s)"),inst->GetId(),inst,(inst->GetTemporary())?_T("yes"):_T("no"));
			list->SetItemText(j,1,buf);
			
			j=list->InsertItem(list->GetItemCount(),_T("type"));
			if(inst->GetType()==0) buf= APL_T("Удален");
			else buf=inst->GetType()->name;
			list->SetItemText(j,1,buf);
		}
		

		el=data.GetAt(i);
		if(el==0)continue;
		if(el->inst!=inst)continue;
		
		CaplInstance *person=0;

		inst=el->create_user;
		j=list->InsertItem(list->GetItemCount(), APL_T("Создан:"));
		if(inst!=0){
			m_doc_data.GetAttr(inst,m_doc->m_api.m_appr_mgr.a_apl_user_name,buf1);
			buf= _T("");

			m_doc_data.GetAttr(inst,m_doc->m_api.m_appr_mgr.a_apl_user_po,person);
			if(person) {m_doc->m_api.m_appr_mgr.GetPersonName(person,buf);  buf+=_T(" (");}
	
			buf+=APL_T("Пользователь: \""); buf+=buf1; buf+=_T("\" ");
			if(person) buf+=_T(" )");
		}else{
			buf= APL_T("Пользователь: возможно удален ");
		}
		if(el->create_date==0){
			buf+= APL_T("(неизвестно когда)");
		}else{
			odt=el->create_date;
			buf+=odt.Format( APL_T(" Дата: %d.%m.%Y  %H:%M:%S"));
		}
		list->SetItemText(j,1,buf);
		if(0!=person) list->SetItemData(j,(long)person);
		person=0;

		j=list->InsertItem(list->GetItemCount(), APL_T("Изменен"));
		inst=el->update_user;
		if(inst!=0){
			m_doc_data.GetAttr(inst,m_doc->m_api.m_appr_mgr.a_apl_user_name,buf1);
			buf= _T("");

			m_doc_data.GetAttr(inst,m_doc->m_api.m_appr_mgr.a_apl_user_po,person);
			if(person) {m_doc->m_api.m_appr_mgr.GetPersonName(person,buf);  buf+=_T(" (");}

			buf+=APL_T("Пользователь: \""); buf+=buf1; buf+=_T("\" ");
			if(person) buf+=_T(" )");
		}else{
			buf= APL_T("Пользователь: возможно удален ");
		}
		if(el->update_date==0){
			buf+= APL_T("(неизвестно когда)");
		}else{
			odt=el->update_date;
			buf+=odt.Format( APL_T(" Дата: %d.%m.%Y  %H:%M:%S"));
		}
		list->SetItemText(j,1,buf);
		if(0!=person) list->SetItemData(j,(long)person);
		person=0;
	}
}

//****************************************************************
void CaplTreeItem::CreateCharacteristic(CaplInstance *inst,CaplInstance *val)
{
	if(!inst) return;
	CaplInstance *new_val=0;
	if(m_doc->m_api.m_charact_mgr.CreateCharacteristic(inst,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 CaplTreeItem::CreateCharacteristicGroup(CaplInstance *inst,CaplInstance *group)
{
	if(!inst) return;
	CaplInstance *group_new=0;
	if(m_doc->m_api.m_charact_mgr.CreateCharacteristicGroup(inst,&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);
	}
}
bool CaplTreeItem::CreateNote()
{
	aplExtent ext;
	GetAccessedInstances(ext);
	if(m_doc->m_api.m_appr_mgr.CreateNote(ext[0]))
	{
		RefreshItem();
		return true;
	}

	return false;
}
void CaplTreeItem::ShowNotes()
{
	aplExtent ext;
	GetAccessedInstances(ext);
	m_doc->m_api.m_appr_mgr.ShowNotes(ext[0]);
}

CaplInstance *CaplTreeItem::GetItemInstance(CaplTreeItem *item)
{
	CaplInstance *res=0;
	if(!item) return 0;
	if(item->m_type == APL_TREE_ITEM_PRODUCT)
	{
		res=((CaplProductTreeItem*)item)->m_prd;
		if(((CaplProductTreeItem*)item)->m_pdf) res=((CaplProductTreeItem*)item)->m_pdf;
	}
	else if(item->m_type == APL_TREE_ITEM_PRDINST) res=((CaplPrdInstTreeItem*)item)->m_inst;
	else if (item->m_type == APL_TREE_ITEM_BP)
	{
		res=((CaplBPTreeItem*)item)->m_inst;
		if(((CaplBPTreeItem*)item)->m_rev) res=((CaplBPTreeItem*)item)->m_rev;
	}
	else if(item->m_type == APL_TREE_ITEM_DOCUMENT)
	{
		res=((CaplDocTreeItem*)item)->m_inst;
		if(((CaplDocTreeItem*)item)->m_rev) res=((CaplDocTreeItem*)item)->m_rev;
	}
	else if (item->m_type == APL_TREE_ITEM_BPINST) res=((CaplBPInstTreeItem*)item)->m_inst;
	else if (item->m_type == APL_TREE_ITEM_BPRES) res=((CaplBPResourceTreeItem*)item)->m_inst;
	else if(item->m_type == APL_TREE_ITEM_LOT)  res=((CaplLotTreeItem*)item)->m_lot;
	else if(item->m_type == APL_TREE_ITEM_PERSON) res=((CaplPersonTreeItem*)item)->m_person;
	else if(item->m_type == APL_TREE_ITEM_ORGANIZATION)  res=((CaplOrganizationTreeItem*)item)->m_inst;
	else if(item->m_type == APL_TREE_ITEM_FOLDER)  res=((CaplFolderTreeItem*)item)->m_inst;
	else if(item->m_type == APL_TREE_ITEM_CATEGORIES)  res=((CaplCategoryTreeItem*)item)->m_inst;
	else if(item->m_type == APL_TREE_ITEM_CLASSIFIERSYSTEM)  res=((CaplClassifierTreeItem*)item)->m_inst;
	else if(item->m_type == APL_TREE_ITEM_CLASSIFIERLEVEL)  res=((CaplClassifierTreeItem*)item)->m_inst;

	return res;

}

DWORD CaplTreeItem::GetAddInType()
{
	DWORD res= 0;

	if(m_type == APL_TREE_ITEM_PRODUCT)
	{
		if(((CaplProductTreeItem*)this)->m_pdf) res=APL_PDF_ITEM;
		else res= APL_PRD_ITEM;
	}
	else if(m_type == APL_TREE_ITEM_CHARACTERISTIC) res=APL_CHARACT_ITEM;
	else if(m_type == APL_TREE_ITEM_FOLDER) res= APL_FOLDER_ITEM;
	else if(m_type == APL_TREE_ITEM_DOCUMENT)
	{
		if(((CaplDocTreeItem*)this)->m_rev) res= APL_DOC_REVISION_ITEM;
		else res= APL_DOC_ITEM;
	}
	else if(m_type == APL_TREE_ITEM_CATEGORIES) res= APL_CATEG_ITEM;
//	else if(m_type == _T("")) res= APL_CATEG_REVISION_ITEM;
	else if(m_type == APL_TREE_ITEM_BP)
	{
		if(((CaplBPTreeItem*)this)->m_rev) res= APL_BP_REVISION_ITEM;
		else res= APL_BP_ITEM;
	}
	else if(m_type == APL_TREE_ITEM_ORGANIZATION) res= APL_ORG_ITEM;
	else if(m_type == APL_TREE_ITEM_PERSON) res= APL_PERSON_ITEM;
	else if(m_type == APL_TREE_ITEM_ACTIVITY) res= APL_ACTIVITY_ITEM;
	else if(m_type == APL_TREE_ITEM_TASK) res= APL_TASK_ITEM;
	else if(m_type == APL_TREE_ITEM_PROCESSTMPL) res= APL_PROCESS_TMPL_ITEM;
	else if(m_type == APL_TREE_ITEM_PROCESS) res= APL_PROCESS;	
	else if(m_type == APL_TREE_ITEM_MESSAGE) res= APL_MESSAGE;
	else if(m_type == APL_TREE_ITEM_MESSAGEFOLDER) res= APL_MESSAGE_FOLDER;
	else if(m_type == APL_TREE_ITEM_PROJECT) res= APL_PROJECT;
	else if(m_type == APL_TREE_ITEM_CLASSIFIERSYSTEM) res= APL_CLASSIFIER_SYS_ITEM;
	else if(m_type == APL_TREE_ITEM_CLASSIFIERLEVEL) res= APL_CLASSIFIER_LEVEL_ITEM;
	else if(m_type == APL_TREE_ITEM_PRDINST) res= APL_PRD_INST_ITEM;

	return res;
}

void CaplTreeItem::UpdateMenu(CMenu** menu, UINT view_mode)
{
	CString sMenuText, str;

	switch(view_mode)
	{
		case APLICM_INSERT: sMenuText=  APL_T("Создать"); break;
		case APLICM_DELETE: sMenuText=  APL_T("Удалить"); break;
		case APLICM_REFERENCES: sMenuText=  APL_T("Показать"); break;
		default: return;
	}

	CMenu *orig_menu= (*menu);
	CMenu *found_menu=0;

	int count= orig_menu->GetMenuItemCount();
	for (int pos= 0; pos<count; pos++)
	{
		orig_menu->GetMenuString(pos, str, MF_BYPOSITION);
		str.Remove(_T('&'));
		if(!str.CompareNoCase(sMenuText))
		{
			found_menu=(CMenu*)orig_menu->GetSubMenu(pos);
			break;
		}
	}

	if(found_menu) *menu= found_menu;
}

bool CaplTreeItem::RefreshAllChildItem()
{
	if(m_tree ==0)return false;
	if(::IsWindow(m_tree->m_hWnd)==FALSE)return false;
	for(int i=0;i<m_doc->m_items.Size;i++)
	{
		if(m_tree->GetParentItem(m_doc->m_items[i]->m_item)==m_item)
		{
			m_doc->m_items[i]->RefreshItem();
			m_doc->m_items[i]->RefreshAllChildItem();
		}
	}
	return true;
}