// prd_inst_mgr.cpp

#include "stdafx.h"
#include <aplNetStepData.h>
#include "apl_api.h"
#include "dictionary.h"
#include "PrdInstDlg.h"
#include "aplLotDlg.h"
#include "PrdInstChangeDlg.h"
#include "ProgramModuleDlg.h"

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

	CHECK_ZERO_ATTR(e_prd_inst, m_data->GetEntityBN(_T("apl_product_instance")));
	CHECK_ZERO_ATTR(a_prd_inst_id, m_data->GetAttrDefinition(e_prd_inst,S::id));
	CHECK_ZERO_ATTR(a_prd_inst_descr, m_data->GetAttrDefinition(e_prd_inst,S::description));
	CHECK_ZERO_ATTR(a_prd_inst_pdf, m_data->GetAttrDefinition(e_prd_inst,S::formation));
	CHECK_ZERO_ATTR(a_prd_inst_sn, m_data->GetAttrDefinition(e_prd_inst,_T("serial_number")));
	CHECK_ZERO_ATTR(a_prd_inst_lot, m_data->GetAttrDefinition(e_prd_inst,_T("lot")));

	CHECK_ZERO_ATTR(a_prd_inst_datetime, m_data->GetAttrDefinition(e_prd_inst,_T("date_time")));
	CHECK_ZERO_ATTR(a_prd_inst_state, m_data->GetAttrDefinition(e_prd_inst,_T("state")));
	CHECK_ZERO_ATTR(a_prd_inst_baseitem, m_data->GetAttrDefinition(e_prd_inst,_T("base_item")));
	CHECK_ZERO_ATTR(a_prd_inst_additional_data, m_data->GetAttrDefinition(e_prd_inst,_T("additional_data")));
	CHECK_ZERO_ATTR(a_prd_inst_rfid, m_data->GetAttrDefinition(e_prd_inst,_T("rfid")));
	CHECK_ZERO_ATTR(a_prd_inst_guid, m_data->GetAttrDefinition(e_prd_inst, _T("guid")));
	CHECK_ZERO_ATTR(a_prd_inst_seria, m_data->GetAttrDefinition(e_prd_inst, _T("seria")));
	CHECK_ZERO_ATTR(a_prd_inst_ils_product_instance, m_data->GetAttrDefinition(e_prd_inst, _T("ils_product_instance")));
	CHECK_ZERO_ATTR(a_prd_inst_code, m_data->GetAttrDefinition(e_prd_inst, _T("code")));
//	a_prd_inst_place ,  m_data->GetAttrDefinition(e_prd_inst,_T("place")));
	// Это атрибуты для ВНИИС.  Для остальных будут нули !!!!
	a_prd_inst_vniis_shipment_date=m_data->GetAttrDefinition(e_prd_inst, _T("vniis_shipment_date"));
	a_prd_inst_vniis_customer=m_data->GetAttrDefinition(e_prd_inst, _T("vniis_customer"));

	CHECK_ZERO_ATTR(e_prd_inst_rel, m_data->GetEntityBN(_T("apl_product_instance_relationship")));
	CHECK_ZERO_ATTR(e_apl_component, m_data->GetEntityBN(_T("apl_component")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_id, m_data->GetAttrDefinition(e_prd_inst_rel,S::id));
	CHECK_ZERO_ATTR(a_prd_inst_rel_name, m_data->GetAttrDefinition(e_prd_inst_rel,S::name));
	CHECK_ZERO_ATTR(a_prd_inst_rel_descr, m_data->GetAttrDefinition(e_prd_inst_rel,S::description));
	CHECK_ZERO_ATTR(a_prd_inst_rel_pdr, m_data->GetAttrDefinition(e_prd_inst_rel,_T("base")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_relating, m_data->GetAttrDefinition(e_prd_inst_rel,_T("relating_product_instance")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_related, m_data->GetAttrDefinition(e_prd_inst_rel,_T("related_product_instance")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_date_installed, m_data->GetAttrDefinition(e_apl_component,_T("date_installed_s")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_date_removed, m_data->GetAttrDefinition(e_apl_component,_T("date_removed_s")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_frames_of_reference, m_data->GetAttrDefinition(e_apl_component,_T("apl_frames_of_reference")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_position ,  m_data->GetAttrDefinition(e_prd_inst_rel,_T("position")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_place ,  m_data->GetAttrDefinition(e_prd_inst_rel,_T("place")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_person ,  m_data->GetAttrDefinition(e_apl_component,_T("person")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_guid ,  m_data->GetAttrDefinition(e_apl_component,_T("guid")));
	CHECK_ZERO_ATTR(a_prd_inst_rel_prototipe,  m_data->GetAttrDefinition(e_prd_inst_rel, _T("prototipe")));

	CHECK_ZERO_ATTR(e_lot, m_data->GetEntityBN(_T("apl_lot")));
	CHECK_ZERO_ATTR(a_lot_id, m_data->GetAttrDefinition(e_lot,S::id));
	CHECK_ZERO_ATTR(a_lot_descr, m_data->GetAttrDefinition(e_lot,S::description));
	CHECK_ZERO_ATTR(a_lot_pdf, m_data->GetAttrDefinition(e_lot,S::formation));
	CHECK_ZERO_ATTR(a_lot_size, m_data->GetAttrDefinition(e_lot,_T("size")));
	CHECK_ZERO_ATTR(a_lot_parent, m_data->GetAttrDefinition(e_lot,_T("parent")));

	CHECK_ZERO_ATTR(e_mwu, m_data->GetEntityBN(S::measure_with_unit));
	CHECK_ZERO_ATTR(a_mwu_val, m_data->GetAttrDefinition(e_mwu,S::value_component));
	CHECK_ZERO_ATTR(a_mwu_unit, m_data->GetAttrDefinition(e_mwu,S::unit_component));


	CHECK_ZERO_ATTR(e_pi_subst, m_data->GetEntityBN(_T("product_instance_substitution")));
	CHECK_ZERO_ATTR(a_pi_subst_predecessor, m_data->GetAttrDefinition(e_pi_subst,_T("predecessor")));
	CHECK_ZERO_ATTR(a_pi_subst_successor, m_data->GetAttrDefinition(e_pi_subst,_T("successor")));
	CHECK_ZERO_ATTR(a_pi_subst_reason, m_data->GetAttrDefinition(e_pi_subst,_T("reason")));
	CHECK_ZERO_ATTR(a_pi_subst_bp, m_data->GetAttrDefinition(e_pi_subst,_T("business_process")));
	CHECK_ZERO_ATTR(a_pi_subst_description, m_data->GetAttrDefinition(e_pi_subst,_T("description")));
	CHECK_ZERO_ATTR(a_pi_subst_job,  m_data->GetAttrDefinition(e_pi_subst,_T("job")));
	CHECK_ZERO_ATTR(a_pi_subst_date,  m_data->GetAttrDefinition(e_pi_subst,_T("date")));
	CHECK_ZERO_ATTR(a_pi_subst_guid, m_data->GetAttrDefinition(e_pi_subst, _T("guid")));

	int i;
	m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("Экземпляры изделий\\Отображать экземпляры изделий ILS"),i,0);
	if(1==i) m_bUseIlsProducrInstance=true;  else m_bUseIlsProducrInstance=false;

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

void CaplPrdInstManager::Detach()
{
	m_data=0;
	e_prd_inst=0;
	a_prd_inst_id=0; a_prd_inst_descr=0; a_prd_inst_pdf=0; a_prd_inst_sn=0;
	a_prd_inst_lot=0;

	a_prd_inst_state = 0;
	a_prd_inst_datetime = 0;
	a_prd_inst_baseitem = 0;
	a_prd_inst_additional_data = NULL;
//	a_prd_inst_place = 0;
	a_prd_inst_guid = 0;
	a_prd_inst_seria = NULL;
	a_prd_inst_code = NULL;
	a_prd_inst_ils_product_instance=0;
	a_prd_inst_vniis_shipment_date=0;
	a_prd_inst_vniis_customer=0;

	 e_prd_inst_rel=0; e_apl_component=0;
	 a_prd_inst_rel_id=0; a_prd_inst_rel_name=0; a_prd_inst_rel_descr=0;a_prd_inst_rel_pdr=0;
	 a_prd_inst_rel_relating=0; a_prd_inst_rel_related=0;
	 a_prd_inst_rel_date_installed=0; a_prd_inst_rel_date_removed=0;
	 a_prd_inst_rel_frames_of_reference=NULL;
	 a_prd_inst_rel_position = NULL;
	 a_prd_inst_rel_place = NULL;
	 a_prd_inst_rel_person = NULL;
	 a_prd_inst_rel_guid = 0;
	 e_prd_inst_rel = NULL;

	e_lot=0; a_lot_size=0; a_lot_pdf=0; a_lot_parent=0;
	a_lot_descr=0; a_lot_id=0; 
	e_mwu=0; a_mwu_val=0; a_mwu_unit=0;

	e_pi_subst=0;
	a_pi_subst_predecessor=0;
	a_pi_subst_successor=0;
	a_pi_subst_reason=0;
	a_pi_subst_bp = 0;
	a_pi_subst_description = NULL;
	a_pi_subst_job= NULL;
	a_pi_subst_date= NULL;
	a_pi_subst_guid = 0;

	m_bUseIlsProducrInstance=false;
}

// *************************************************************************
CaplInstance *CaplPrdInstManager::CreatePrdInst(CaplInstance *pdf,CaplInstance *lot)
{
	CString sVal;
	m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Роли\\Роль для создания экземпляров изделий"), sVal, _T(""));
	if(!sVal.IsEmpty() && !m_api->m_data.IsAdmin())
	{
		if(!m_api->m_appr_mgr.CheckPersonRole(0,sVal)) {AfxMessageBox(APL_T("Вы не обладаете нужной ролью!"));	return 0;	}
	}

	if(e_prd_inst==0)
		return 0;


	CaplSetResourceHandle setres(module_inst);

	CPrdInstDlg dlg;
	dlg.m_api	=m_api;
	dlg.m_pdf	=pdf;
	dlg.m_lot	=lot;

	int k=dlg.DoModal();
	if(k==IDOK) 
	{
		if(m_AutoSave) 
			m_api->SaveChanges();

		if(NULL!=dlg.m_inst && true==m_AutoSave)
		{
			CString csAccPat;
			aplExtent aet;

			aet.Add(dlg.m_inst);
			if(_T("")!=dlg.m_csAccessString)
				apidata.NET_SetAccessFromPattern(&aet,dlg.m_csAccessString);
			else
			if(true==m_AutoUsurpire)
				if(TRUE==m_api->m_options_mgr.GetDefPatern(e_prd_inst,csAccPat))
					apidata.NET_SetAccessFromPattern(&aet,csAccPat);
		}

		return dlg.m_inst;
	}
	return 0;
}

// *************************************************************************
CaplInstance *CaplPrdInstManager::CopyPrdInst(CaplInstance *base_inst)
{
	if(e_prd_inst==0)
		return 0;

	CaplSetResourceHandle setres(module_inst);

	CPrdInstDlg dlg;
	dlg.m_api	=m_api;
	dlg.m_base_inst	=base_inst;
	dlg.m_lot	=0;

	int k=dlg.DoModal();
	if(k==IDOK) 
	{
		if(m_AutoSave) 
			m_api->SaveChanges();

		return dlg.m_inst;
	}
	return 0;
}

//*************************************************************
bool CaplPrdInstManager::LoadPrdInstInfo(CaplInstance *inst)
{
	if(e_prd_inst==0) return false;
	if(m_data==0)return false;
	if(inst==0)return false;
	if(inst->GetId()==0)return true;
	if(inst->GetType()==0)return false;
	aplExtent ext; ext.Unique=false; ext.Add(inst);
	return LoadPrdInstInfo(ext);
}
//*************************************************************
bool CaplPrdInstManager::LoadPrdInstInfo(aplExtent &ext)
{
	if(e_prd_inst==0) return false;
	if(m_data==0)return false;

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

	CaplLoadData ld(m_data,DEF_SOURCE);
	int iLoad=0;
	int i;
	for(i=0;i<ext.Size;i++)
	{
		CaplInstance *inst=ext[i];
		if (inst==0) continue;
		if (inst->GetType()==0) continue;
		if(inst->GetId()==0) continue;
	
		ld.AddQuery(0,inst,true);
		iLoad++;
		if(iLoad==m_MaxItemsLoad || (i==(ext.Size-1) && iLoad>0))
		{ 
			iLoad=0;
			ld.AddQuery(_T('d'), 0, 0, a_prd_inst_lot, true, true);	
			int i1=	ld.AddQuery(_T('d'), 0, 0, a_prd_inst_pdf, true, true);
			ld.AddQuery(_T('d'), i1, 0, m_api->m_prd_mgr.a_pdf_prd, true, true);
			if(!ld.LoadEx()){
				if(apidata.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
					if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
				}
			}
		}
	}
	return true;
}
//*************************************************************
bool CaplPrdInstManager::ShowPrdInstProperties(CaplInstance *inst,CaplInstance *pi_rel)
{
	CString		csAcc;

	int			k;
	bool		b_prg_m		=false;

	if(e_prd_inst==0)
		return false;
	if(inst==0)
		return false;
	if(inst->GetType()==0)
		return false;

	CaplSetResourceHandle setres(module_inst);
	
	if(!pi_rel || !m_api->m_data.IsKindOf(inst, m_api->m_doc_mgr.e_apl_doc_rev))
	{
		CPrdInstDlg dlg;

		dlg.m_api		=m_api;
		dlg.m_inst		=inst;
		dlg.m_inst_rel	=pi_rel;

		k=dlg.DoModal();
		csAcc=dlg.m_csAccessString;
	}
	else
	{
		CProgramModuleDlg dlg;

		b_prg_m=true;
	
		dlg.m_api	=m_api;
		dlg.m_rev	=inst;
		dlg.m_rel	=pi_rel;

		k=dlg.DoModal();
	}
	if(k==IDOK)
	{
		if(m_AutoSave)
			m_api->SaveChanges();
		if(false==b_prg_m && inst->GetAccessmode()==aplOWN)
		{
			aplExtent aet;
			aet.Add(inst);
			apidata.NET_SetAccessFromPattern(&aet,csAcc);
		}
		return true;
	}
	return false;
}
//*************************************************************
bool CaplPrdInstManager::DeletePrdInst(CaplInstance *inst)
{
	if(inst==0) return false;
	if(inst->GetType()==0) return false;
	if(inst->GetAccessmode()>aplOWN) return false;
	//удалим ассоциации со справочником
	m_api->m_classifier_mgr.DeleteClassifierAssociation(inst,0);
	// удаляем статусы и характеристики объекта
	m_api->m_appr_mgr.DeleteAllApproval(inst);
	m_api->m_charact_mgr.DeleteAllAssociatedCharacteristic(inst);
	
	m_data->DeleteInstance(inst);
	if(m_AutoSave) m_api->SaveChanges();
	return true;
}
//*************************************************************
bool CaplPrdInstManager::FindAllPdfInstances(aplExtent &pdf, aplExtent &out_ext)
{
	out_ext.Clear();
	if(e_prd_inst==0) return false;
	if(m_data==0) return false;
	if(pdf.GetSize()==0) return false;
	if(!m_data->IsDictLoad()) return false;
	int i;
	if(m_data->IsConnected())
	{
		CaplLoadData ld(m_data,DEF_SOURCE);
		for(i=0; i<pdf.Size; i++)
			ld.AddQuery(0, pdf[i]);
		ld.AddQuery(_T('r'), 0, e_prd_inst,a_prd_inst_pdf, true,true);
		ld.LoadEx();
	}

	aplExtent ext;
	CaplInstance *inst0;
	CaplAggr aggr;
	m_data->GetEntityExtent(e_prd_inst,ext);
	for(i=0;i<ext.Size;i++)
	{
		if(ext[i]==0) continue;
		if(ext[i]->GetAccessmode()>aplRO) continue;
		m_data->GetAttr(ext[i],a_prd_inst_pdf,inst0);
		if(pdf.Find(inst0)>-1)
		{
			if(inst0!=0)out_ext.Add(ext[i]);
		}
	}
	return true;
}
//*************************************************************
bool CaplPrdInstManager::FindAllPdfInstances(CaplInstance *pdf, aplExtent &out_ext)
{
	out_ext.Clear();
	if(e_prd_inst==0) return false;
	if(m_data==0) return false;
	if(pdf==0) return false;

	int i;
	if(pdf->GetId()!=0)
	{
		// Чтение из базы
		if(m_data->IsConnected())
		{
			CaplLoadData ld(m_data,DEF_SOURCE);
			// ссылка
			ld.AddQuery(_T('b'), pdf->GetId(), e_prd_inst,a_prd_inst_pdf, true,true);
			ld.LoadEx();
		}
	}
	aplExtent ext;
	CaplInstance *inst0;
	CaplAggr aggr;
	m_data->GetEntityExtent(e_prd_inst,ext);
	for(i=0;i<ext.Size;i++)
	{
		if(ext[i]==0) continue;
		if(ext[i]->GetAccessmode()>aplRO) continue;
		m_data->GetAttr(ext[i],a_prd_inst_pdf,inst0);
		if(pdf==inst0)
		{
			if(inst0!=0)out_ext.Add(ext[i]);
		}
	}
	return true;
}
//**************************************************************************
bool CaplPrdInstManager::LoadInsertedInstances(aplExtent &prdinsts, aplExtent &out_rel, aplExtent &out_ext)
{
	out_rel.Clear();
	out_ext.Clear();
	if(prdinsts.Size==0) return false;

	if(m_data->IsConnected())
	{
		CaplLoadData ld(m_data,DEF_SOURCE);
		// ссылка
		for(int i=0; i<prdinsts.Size;i++){
			if(prdinsts[i]==0) continue;
			if(prdinsts[i]->GetId()==0) continue;
			if(prdinsts[i]->GetType()==0) continue;
			ld.AddQuery(0, prdinsts[i]);
		}
		ld.AddQuery(_T('r'), 0, e_prd_inst_rel, a_prd_inst_rel_relating, true,true);
		ld.LoadEx();
	}
	aplExtent ext;
	CaplInstance *inst;
	m_data->GetEntityExtent(e_prd_inst_rel,ext);
	for(int i=0;i<ext.Size;i++)
	{
		m_data->GetAttr(ext[i],a_prd_inst_rel_relating,inst);
		if(prdinsts.Find(inst)<0) continue;
		m_data->GetAttr(ext[i],a_prd_inst_rel_related,inst);
		if(inst==0) continue;
		out_rel.Add(ext[i]);
		out_ext.Add(inst);
	}
	LoadExtentInfo(out_ext);
	return true;
}
//**************************************************************************
bool CaplPrdInstManager::LoadInsertedInstances(CaplInstance *prdinst, aplExtent &out_rel, aplExtent &out_ext)
{
	out_rel.Clear();
	out_ext.Clear();
	if(prdinst==0) return false;
	if(prdinst->GetType()==0) return false;
	if(prdinst->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight()); return false;}

	int i;
	if(prdinst->GetId()!=0)
	{
		// Чтение из базы
		if(m_data->IsConnected())
		{
			CaplLoadData ld(m_data,DEF_SOURCE);
			// ссылка
			i=ld.AddQuery(_T('b'), prdinst->GetId(), e_prd_inst_rel,a_prd_inst_rel_relating, true,true);
				ld.LoadEx();
		}
	}
	aplExtent ext;
	CaplInstance *inst;
	m_data->GetEntityExtent(e_prd_inst_rel,ext);
	for(i=0;i<ext.Size;i++)
	{
		m_data->GetAttr(ext[i],a_prd_inst_rel_relating,inst);
		if(inst!=prdinst) continue;
		m_data->GetAttr(ext[i],a_prd_inst_rel_related,inst);
		if(inst==0) continue;
		out_rel.Add(ext[i]);
		out_ext.Add(inst);
	}
	LoadExtentInfo(out_ext);
	return true;
}
//**************************************************************************
bool CaplPrdInstManager::WhereUsedPIinPI(CaplInstance *prdinst, aplExtent &out_rel, aplExtent &out_ext)
{
	out_rel.Clear();
	out_ext.Clear();
	if(prdinst==0) return false;
	if(prdinst->GetType()==0) return false;
	if(prdinst->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight()); return false;}

	int i;
	if(prdinst->GetId()!=0)
	{
		// Чтение из базы
		if(m_data->IsConnected())
		{
			CaplLoadData ld(m_data,DEF_SOURCE);
			// ссылка
			ld.AddQuery(_T('b'), prdinst->GetId(), e_prd_inst_rel,a_prd_inst_rel_related, true,true);
			ld.LoadEx();
		}
	}
	aplExtent ext;
	CaplInstance *inst;
	m_data->GetEntityExtent(e_prd_inst_rel,ext);
	for(i=0;i<ext.Size;i++)
	{
		m_data->GetAttr(ext[i],a_prd_inst_rel_related,inst);
		if(inst!=prdinst) continue;
		m_data->GetAttr(ext[i],a_prd_inst_rel_relating,inst);
		out_rel.Add(ext[i]);
		out_ext.Add(inst);
	}
	LoadExtentInfo(out_ext);
	return true;
}
//**************************************************************************
CaplInstance *CaplPrdInstManager::ChangePIinPI(CaplInstance *old_rel, CaplInstance *new_pi)
{
	if(old_rel==0) return 0;
	if(old_rel->GetType()==0) return 0;
	if(old_rel->GetAccessmode()>aplRW) {aplErrorMessage(S::NoAccessRight()); return 0;}

	if(new_pi!=0)
	{
		if(new_pi->GetType()==0) return 0;
		if(new_pi->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight()); return 0;}
	}

	CaplInstance *par_pi;
	m_data->GetAttr(old_rel,a_prd_inst_rel_relating,par_pi);

	if(par_pi==0) return 0;
	if(par_pi->GetType()==0) return 0;
	if(par_pi->GetAccessmode()>aplRW) {aplErrorMessage(S::NoAccessRight()); return 0;}

	CString buf;
	m_data->GetAttr(old_rel,m_api->m_prd_inst_mgr.a_prd_inst_rel_date_removed,buf);
	if(buf!=_T(""))
	{
		if(m_api->m_ModeInteractive) AfxMessageBox( APL_T("Нельзя заменить демонтированное изделие"),MB_OK|MB_ICONSTOP);
		return 0;
	}

	CaplSetResourceHandle setres(module_inst);

	CPrdInstChangeDlg dlg;
	dlg.m_api=m_api;
	dlg.m_src_pi_rel=old_rel;
	dlg.m_new_pi=new_pi;
	int k=dlg.DoModal();
	if(k==IDOK) {if(m_AutoSave) m_api->SaveChanges();return dlg.m_new_pi_change;}

	return 0;
}
//**************************************************************************
CaplInstance *CaplPrdInstManager::InsertInPI(CaplInstance *parent_prdinst, CaplInstance *sub_prdinst, CaplInstance *pdr)
{
	if(parent_prdinst==0)
		return 0;
	if(parent_prdinst->GetType()==0)
		return 0;
	if(parent_prdinst->GetAccessmode()>aplRW)
	{
		aplErrorMessage(S::NoAccessRight());
		return 0;
	}

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

	if(!m_data->IsKindOf(parent_prdinst,e_prd_inst) && !m_data->IsKindOf(parent_prdinst,m_api->m_appr_mgr.e_org))
		return 0;
	
	if(m_data->IsKindOf(sub_prdinst,e_prd_inst))
	{
		CPrdInstDlg dlg;
		CaplSetResourceHandle setres(module_inst);		
		
		dlg.m_api		=m_api;
		dlg.m_inst		=sub_prdinst;
		dlg.m_par_inst	=parent_prdinst;
		
		int r=dlg.DoModal();
		if(r!=IDOK)
			return 0;
			
		m_api->SaveChanges();

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

		return dlg.m_inst_rel;
	}
	else if(m_data->IsKindOf(sub_prdinst,e_lot))
	{
		CaplInstance *inst_rel=m_data->CreateInstance(e_apl_component);
		m_data->PutAttr(inst_rel,a_prd_inst_rel_relating,parent_prdinst);
		m_data->PutAttr(inst_rel,a_prd_inst_rel_related,sub_prdinst);

		m_api->SaveChanges();
		
		return  inst_rel;
	}
	else return 0;
}

// *************************************************************************
CaplInstance *CaplPrdInstManager::CreateLot(CaplInstance *pdf, CaplInstance *parent_lot)
{
	if(e_lot==0) return 0;
	CaplSetResourceHandle setres(module_inst);

	CaplLotDlg dlg;
	dlg.m_api=m_api;
	dlg.m_pdf=pdf;
	dlg.m_parent_lot=parent_lot;
	if(dlg.DoModal()!=IDOK)
	{
		return 0;
	}

	if(m_AutoSave) 
		m_api->SaveChanges();

	if(NULL!=dlg.m_lot && true==m_AutoSave)
	{
		CString csAccPat;
		aplExtent aet;

		aet.Add(dlg.m_lot);
		if(_T("")!=dlg.m_csAccessString)
			apidata.NET_SetAccessFromPattern(&aet,dlg.m_csAccessString);
		else
		if(true==m_AutoUsurpire)
			if(TRUE==m_api->m_options_mgr.GetDefPatern(e_lot,csAccPat))
				apidata.NET_SetAccessFromPattern(&aet,csAccPat);
	}

	return dlg.m_lot;
}
//*************************************************************
bool CaplPrdInstManager::LoadLotInfo(CaplInstance *lot)
{
	if(m_data==0)return 0;
	if(e_lot==0) return 0;
	if(lot==0)return 0;
	if(lot->GetType()==0)return false;
	if(lot->GetId()==0)return true;
	aplExtent ext; ext.Unique=false; ext.Add(lot);
	return LoadLotInfo(ext);
}
//*************************************************************
bool CaplPrdInstManager::LoadLotInfo(aplExtent &ext)
{
	if(m_data==0)return 0;
	if(e_lot==0) return 0;
	int i,j;
	int iLoad=0;
	CaplLoadData ld(m_data,DEF_SOURCE);

	for(i=0;i<ext.Size;i++)
	{
		CaplInstance *lot=ext[i];
		if (lot==0) continue;
		if (lot->GetId()==0) continue;
		if (lot->GetType()==0) continue;
		ld.AddQuery(0,lot,true);
		iLoad++;
		if(iLoad==m_MaxItemsLoad || (i==(ext.Size-1) && iLoad>0))
		{ 
			iLoad=0;
			j=ld.AddQuery(_T('d'), 0, 0,a_lot_size, true);
			// версия
			  ld.AddQuery(_T('d'), j, 0,a_mwu_val, true);
			  ld.AddQuery(_T('d'), j, 0,a_mwu_unit, true);

			if(!ld.LoadEx()){
				if(apidata.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
					if(m_api->m_ModeInteractive)AfxMessageBox(S::ErrorLoadDataMgr(),MB_OK|MB_ICONSTOP);
				}
			}
		}
	}
	return true;
}
//*************************************************************
bool CaplPrdInstManager::ShowLotProperties(CaplInstance *lot)
{
	if(e_lot==0) return false;
	if(lot==0) return false;
	if(lot->GetType()==0) return false;
	CaplSetResourceHandle setres(module_inst);
	
	CaplLotDlg dlg;
	dlg.m_api=m_api;
	dlg.m_lot=lot;
	int k=dlg.DoModal();

	if(k!=IDOK)
		return false;
	if(m_AutoSave) 
		m_api->SaveChanges();
	if(lot->GetAccessmode()==aplOWN)
	{
		aplExtent aet;
		aet.Add(lot);
		apidata.NET_SetAccessFromPattern(&aet,dlg.m_csAccessString);
	}

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

bool CaplPrdInstManager::DeleteLot(CaplInstance *lot)
{
	if(e_lot==0) return false;
	if(lot==0) return false;
	if(lot->GetType()==0) return false;
	if(lot->GetAccessmode()>aplOWN) return false;
	CaplInstance *mwu=0;
	m_data->GetAttr(lot,a_lot_size,mwu);
	//удалим ассоциации со справочником
	m_api->m_classifier_mgr.DeleteClassifierAssociation(lot,0);
	// удаляем статусы и характеристики объекта
	m_api->m_appr_mgr.DeleteAllApproval(lot);
	m_api->m_charact_mgr.DeleteAllAssociatedCharacteristic(lot);
	
	m_data->DeleteInstance(lot);
	if(mwu) m_data->DeleteInstance(mwu);
	if(m_AutoSave) m_api->SaveChanges();
	return true;
}
//*************************************************************
bool CaplPrdInstManager::FindAllPdfLoot(CaplInstance *pdf, aplExtent &out_ext)
{
	out_ext.Clear();
	if(e_lot==0) return false;
	if(m_data==0) return false;
	if(pdf==0) return false;
	if(pdf->GetType()==0) return false;

	int i;
	if(pdf->GetId()!=0)
	{
		// Чтение из базы
		if(m_data->IsConnected())
		{
			CaplLoadData ld(m_data,DEF_SOURCE);
			// ссылка
			i=ld.AddQuery(_T('b'), pdf->GetId(), e_lot,a_lot_pdf, true);
			  ld.AddQuery(_T('d'), i, 0,a_lot_pdf, true);
			  ld.AddQuery(_T('d'), i, 0,a_lot_id, true);
			  ld.AddQuery(_T('d'), i, 0,a_lot_descr, true);
			i=ld.AddQuery(_T('d'), i, 0,a_lot_size, true);
			i=ld.AddQuery(_T('d'), i, 0,a_lot_parent, true);
			  ld.AddQuery(_T('d'), i, 0,a_mwu_val, true);
			  ld.AddQuery(_T('d'), i, 0,a_mwu_unit, true);
			ld.LoadEx();
		}
	}
	aplExtent ext_lot_ref;
	CaplInstance *inst0;
	CaplAggr aggr;
	m_data->GetEntityExtent(e_lot,ext_lot_ref);
	for(i=0;i<ext_lot_ref.Size;i++)
	{
		m_data->GetAttr(ext_lot_ref[i],a_lot_pdf,inst0);
		if(pdf==inst0)
		{
			if(inst0!=0)out_ext.Add(ext_lot_ref[i]);
		}
	}
	return true;
}
//*************************************************************
bool CaplPrdInstManager::FindAllLotProductInstance(aplExtent &lots, aplExtent &out_ext, bool bFromBalse)
{
	out_ext.Clear();
	if(m_api==NULL) return false;
	if(!m_api->m_data.IsDictLoad()) return false;
	if(lots.Size==0) return true;
	
	int i;
	// Чтение из базы
	if(m_data->IsConnected() && bFromBalse)
	{
		CaplLoadData ld(m_data,DEF_SOURCE);
		// ссылка
		for(i=0; i<lots.Size; i++)
		{
			if(lots[i]==NULL) continue;
			if(lots[i]->GetId()==0) continue;
			
			ld.AddQuery(0, lots[i]);
		}
		ld.AddQuery(_T('r'), 0, e_prd_inst,a_prd_inst_lot, true,true);
		ld.LoadEx();
	}
	aplExtent ext_lot_ref;
	CaplInstance *inst0;
	m_data->GetEntityExtent(e_prd_inst,ext_lot_ref);
	for(i=0;i<ext_lot_ref.Size;i++)
	{
		m_data->GetAttr(ext_lot_ref[i],a_prd_inst_lot,inst0);
		if(lots.Find(inst0)>-1)
		{
			if(inst0!=0)
				out_ext.Add(ext_lot_ref[i]);
		}
	}
	return true;
}
//*************************************************************
bool CaplPrdInstManager::FindAllLotProductInstance(CaplInstance *lot, aplExtent &out_ext, bool bFromBalse)
{
	out_ext.Clear();
	aplExtent lots;
	lots.Add(lot);
	return FindAllLotProductInstance(lots, out_ext, bFromBalse);
}
//*************************************************************
CaplInstance* CaplPrdInstManager::FindPrdInstByPDFSN(CaplInstance *pdf, LPCTSTR lpszSN)
{
	if(m_api==NULL) return NULL;
	if(!m_api->m_data.IsDictLoad()) return NULL;
	if(pdf==NULL) return NULL;

	aplExtent ext;
	CaplAttrValue tst_val[2];
	tst_val[0].attr = a_prd_inst_pdf;
	tst_val[0].value.Set(pdf);
	tst_val[1].attr = a_prd_inst_sn;
	tst_val[1].value.Set(lpszSN);
	if(m_api->m_data.NET_FindInstancesWithAttrValues(e_prd_inst, 2, &tst_val[0], ext, false)>0)
		return ext[0];
	return NULL;
}

//*************************************************************
bool CaplPrdInstManager::LoadIncomingLots(CaplInstance *lot, aplExtent &out_ext)
{
	out_ext.Clear();
	if(lot==0) return false;
	if(lot->GetType()==0) return false;
	if(lot->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight()); return false;}

	int i;
	if(lot->GetId()!=0)
	{
		// Чтение из базы
		if(m_data->IsConnected())
		{
			CaplLoadData ld(m_data,DEF_SOURCE);
			// ссылка
			i=ld.AddQuery(_T('b'), lot->GetId(), e_lot,a_lot_parent, true);
				ld.AddQuery(_T('d'), i, 0,a_lot_parent, true);
				
				ld.LoadEx();
		}
	}
	aplExtent ext;
	CaplInstance *inst;
	m_data->GetEntityExtent(e_lot,ext);
	for(i=0;i<ext.Size;i++)
	{
		m_data->GetAttr(ext[i],a_lot_parent,inst);
		if(inst!=lot) continue;
		out_ext.Add(ext[i]);
	}
	LoadExtentInfo(out_ext);
	return true;
}

