/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans.user.client;
import beans.cec.entity.CommitteeDetails;
import beans.doctor.recommendation.RecommendationDetails;
import beans.user.client.entity.ClientDetails;
import framework.beans.EntityDetails;
import beans.doctor.emc.EmcDetails;
import framework.beans.FacadeBean;
import framework.beans.client.clientDocument.ClientDocumentDetails;
import framework.beans.security.BeanRights;
import beans.contract.entity.Contract;
import beans.contract.entity.Polis;
import beans.contract.entity.PolisDetails;
import framework.beans.address.entities.AddressDetails;
import beans.discount.entity.DiscountCard;
import beans.discount.entity.DiscountCardDetails;
import beans.directory.simple.entities.SocialStatus;
import beans.directory.simple.entities.UserGroup;
import beans.doctor.certificate.Certificate;
import beans.doctor.certificate.CertificateDetails;
import beans.doctor.contraindication.Contraindication;
import beans.doctor.contraindication.ContraindicationDetails;
import beans.doctor.diagnosis.Diagnosis;
import beans.doctor.diagnosis.DiagnosisDetails;
import beans.doctor.direction.Direction;
import beans.doctor.direction.DirectionDetails;
import beans.doctor.emc.Emc;
import beans.doctor.prescription.Prescription;
import beans.doctor.prescription.PrescriptionDetails;
import beans.doctor.recommendation.Recommendation;
import beans.service.ServiceRender;
import beans.service.ServiceRenderDetails;
import beans.doctor.sicklist.entity.Sicklist;
import beans.doctor.sicklist.entity.SicklistDetails;
import beans.user.client.entity.Client;
import beans.user.job.entity.Job;
import beans.user.job.entity.JobDetails;
import framework.beans.address.entities.Address;
import framework.beans.address.entities.AddressObject;
import framework.beans.directory.simple.entities.Name;
import framework.beans.directory.simple.entities.Patronymic;
import framework.beans.directory.simple.entities.Sex;
import framework.beans.directory.simple.entities.Surname;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import framework.generic.ClipsServerException;
import framework.generic.EDataIntegrity;
import java.util.GregorianCalendar;
import javax.ejb.Stateful;
import javax.persistence.Query;
import beans.UserRightsSet;
import beans.cec.entity.CommitteeDirection;
import beans.directory.district.entity.AddressDistrict;
import beans.directory.district.entity.District;
import framework.audit.AuditDoc;
import beans.directory.simple.entities.BloodGroup;
import beans.profcheckup.entity.ProfcheckupItem;
import beans.user.client.updater.UpdaterClientBean;
import beans.directory.simple.entities.DiagnosisType;
import beans.directory.simple.entities.Insurer;
import beans.directory.simple.entities.RegionIdCode;
import beans.directory.simple.entities.RepresentativeStatus;
import beans.doctor.prescriptiondlo.PrescriptionDlo;
import beans.doctor.prescriptiondlo.PrescriptionDloDetails;
import beans.user.client.facilityClient.FacilityClient;
import beans.user.client.facilityClient.FacilityClientChunk;
import beans.user.client.facilityClient.FacilityDocument;
import beans.user.collaborator.entities.Collaborator;
import framework.audit.AuditDetails;
import framework.beans.FindEntity;
import framework.beans.ModificationInfo;
import framework.beans.client.clientDocument.ClientDocument;
import framework.beans.directory.simple.entities.ClientDocumentType;
import framework.beans.directory.simple.entities.DocumentGivenPlace;
import framework.generic.ESecurity;
import framework.security.RightChecker;
import framework.security.UserRight;
import framework.security.UserRightsSetAbstract;
import framework.utils.FormatChecker;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.regex.Pattern;
import javax.persistence.EntityManager;
/**
* @security - Ok.
* @author axe
*/
@Stateful(mappedName="clips-beans/ClientBean")
public class ClientBean extends FacadeBean<Client>
implements ClientBeanRemote {
public static final UserRight RIGHT_CREATION = UserRightsSet.WRITE_CLIENT_PUBLIC_INFO;
public static int COMMAND_READ_EMC = 4;
public static int COMMAND_WRITE_EXCEMPTION = 5;
public static int COMMAND_READ_CONTRACT = 6;
public static int COMMAND_READ_CONTRAINDICATION = 7;
public static int COMMAND_READ_CERTIFICATE = 8;
public ClientBean() {
super(Client.class);
}
@Override
protected void initBeanRights() {
int [] r = new int[9];
r[COMMAND_READ] = RightPresence(UserRightsSet.READ_CLIENT_PUBLIC_INFO.id);
int cmr = RightPresence(UserRightsSet.WRITE_CLIENT_PUBLIC_INFO.id);
r[COMMAND_CREATE] = cmr;
r[COMMAND_MODIFY] = cmr;
r[COMMAND_REMOVE] = cmr;
r[COMMAND_READ_EMC] = RightPresence(UserRightsSet.READ_MEDICAL_DATA.id);
r[COMMAND_WRITE_EXCEMPTION] = RightPresence(UserRightsSet.WRITE_CLIENT_EXCEMPTION.id);
r[COMMAND_READ_CONTRACT] = RightPresence(UserRightsSet.READ_CONTRACT.id);
r[COMMAND_READ_CERTIFICATE] = RightPresence(UserRightsSet.READ_CERTIFICATE.id);
//Чтение непереносимостей завязано на права чекапов (так проще см. комменты в UserRights)
r[COMMAND_READ_CONTRAINDICATION] = RightPresence(UserRightsSet.READ_MEDICAL_DATA.id);
if (r[COMMAND_READ_CONTRAINDICATION] <= 0){
r[COMMAND_READ_CONTRAINDICATION] = RightPresence(UserRightsSet.WRITE_ANALYSE_ANY_TIME.id);
}
if (r[COMMAND_READ_CONTRAINDICATION] <= 0){
r[COMMAND_READ_CONTRAINDICATION] = RightPresence(UserRightsSet.WRITE_ANALYSE_DURING_DAY.id);
}
if (r[COMMAND_READ_CONTRAINDICATION] <=0) {
r[COMMAND_READ_CONTRAINDICATION] = RightPresence(UserRightsSet.READ_ANALYSE_LIST.id);
}
rights = new BeanRights(r);
}
/**
* Обновляет данные клиента.
* @param details новые детали клиента
* @throws ClipsServerException
*/
@Override
protected void onUpdate(Client entity, EntityDetails details,
AuditDoc auditDoc, List<AuditDoc> auditDocList) throws ClipsServerException {
//Проверка - возможно это сотрудник, его изменять всем нельзя
if (getId() != 0) {
List<Collaborator> list = findEntityList(Collaborator.class, "client.id", getId());
if (list.size() > 0
&& (RightPresence(UserRightsSetAbstract.WRITE_COLLABORATOR.getID()) <= 0)
&& !isSuperUser()) {
throw new ESecurity("Отсутствует право изменять данные сотрудников");
}
}
ClientDetails d = (ClientDetails) details;
String msg = FormatChecker.checkEmail(d.email);
if(msg == null) {
msg = FormatChecker.checkPhones(d.telephones);
}
if(msg == null) {
msg = FormatChecker.checkSNILS(d.snils);
}
if(msg != null) {
throw new ClipsServerException(msg);
}
try {
FormatChecker.checkINN(d.inn);
} catch (ParseException ex) {
throw new ClipsServerException("Некорректный код ИНН", ex);
}
if (d.representativeId != 0 && d.representativeStatusId == 0) {
throw new ClipsServerException("При указании представителя необходимо указать его статус");
}
entity.setSurname(d.surnameId == 0 ? null : findEntity(Surname.class, d.surnameId));
entity.setName(d.nameId == 0 ? null : findEntity(Name.class, d.nameId));
entity.setPathronymic(d.pathronId == 0 ? null : findEntity(Patronymic.class, d.pathronId));
entity.setSex(findEntity(Sex.class, d.sexId));
entity.setUserGroup(d.userGroupId == 0 ? null : findEntity(UserGroup.class, d.userGroupId));
entity.setSocialStatus(d.socialStatusId == 0 ? null : findEntity(SocialStatus.class, d.socialStatusId));
entity.setBorn(d.born);
entity.setRemarks(d.remarks);
entity.setPassword(d.keyword);
entity.setSocialCardId(d.socialCardCode);
entity.setEmail(d.email);
entity.setInn(d.inn);
entity.setSnils(d.snils);
entity.setTelephones(d.telephones);
entity.setMother(d.motherId == 0 ? null : checkNotSelf(d.motherId));
entity.setFather(d.fatherId == 0 ? null : checkNotSelf(d.fatherId));
entity.setRepresentative(d.representativeId == 0 ? null : checkNotSelf(d.representativeId));
entity.setRepresentativeStatus(d.representativeStatusId == 0 ? null
: findEntity(RepresentativeStatus.class, d.representativeStatusId));
entity.setDistrict(d.districtId == 0 ? null : findEntity(District.class, d.districtId));
entity.setBloodGroup(d.bloodGroupId == 0 ? null : findEntity(BloodGroup.class, d.bloodGroupId));
entity.setAddressCashe("");
}
private Client checkNotSelf(int mother) throws ClipsServerException {
Client m = findEntity(Client.class, mother);
if (getId() != 0){
Client entity = getExistentEntity();
if (m.getId() == entity.getId()) {
throw new EDataIntegrity("Нельзя указать в качестве родителей " +
"или представителя пациента его самого");
}
}
return m;
}
@Override
protected void afterUpdate(Client entity, boolean isNewEntity,
EntityDetails details, List<AuditDoc> auditDocList) throws ClipsServerException {
Emc emc = null;
if (UpdaterClientBean.emcMap != null) {
emc = UpdaterClientBean.emcMap.get(entity.getId());
} else {
List<Emc> list = findEntityList(Emc.class, "client", entity);
if (list.size() != 0) {
emc = list.get(0);
}
}
AuditDoc<Emc> auditDoc;
if (emc == null) {
auditDoc = new AuditDoc<Emc>(null, getCollaborator());
emc = new Emc();
emc.setClient(entity);
} else {
auditDoc = new AuditDoc<Emc>(emc, getCollaborator());
}
ClientDetails d = (ClientDetails)details;
if (d.numberEmc != null && !d.numberEmc.isEmpty() && !d.noCheckEmcNum) {
int entityCount = getEntityCount(Emc.class, new Field[]{new Field("number", d.numberEmc),
new Field("client", entity, Field.OPERATOR_NOT_EQUAL)});
if (entityCount > 0) {
throw new ClipsServerException("Уже существует ЭМК с данным номером");
}
}
emc.setNumber(d.numberEmc);
saveEntity(emc);
if (UpdaterClientBean.emcMap != null) {
UpdaterClientBean.emcMap.put(entity.getId(), emc);
}
checkAudit(auditDocList, auditDoc, emc);
}
/**
* Возвращает детали адреса клиента.
* В системе безопасности это комманда COMMAND_READ.
* @return AddressDetails детали адреса клиента
* @throws ClipsServerException
*/
@Override
public AddressDetails getAddress() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ);
Client entity = getExistentEntity();
Address addr = entity.getAddress();
if (addr == null) {
addr = new Address();
}
return addr.getDetails((RightChecker) this);
}
/**
* Обновляет данные адреса клиента.
* В системе безопасности это комманда COMMAND_MODIFY.
* @param details новые детали адреса клиента
* @throws ClipsServerException в случае если обновление отвергнуто системой
* безопастности либо произошла ошибка
*/
@Override
public ModificationInfo setAddress(AddressDetails details) throws ClipsServerException {
checkCommandAccessibility(COMMAND_MODIFY);
Client entity = getExistentEntity();
AuditDoc<Client> auditDoc = new AuditDoc<Client>(entity, getCollaborator());
Address addr = entity.getAddress();
boolean newAddr = false;
if (addr == null) {
addr = new Address();
newAddr = true;
}
addr.setBuilding(details.building);
addr.setFlat(details.flat);
addr.setAddressObject(findEntity(AddressObject.class, details.objectId));
// addr.setId(details.id);
saveEntity(addr);
if(newAddr) {
entity.setAddress(addr);
saveEntity(entity);
}
if (auditDoc.check(entity)) {
return new ModificationInfo(persistAudit(auditDoc));
} else {
return new ModificationInfo(null);
}
}
/**
* Возвращает ЕМС клиента, если ЕМС не существует, оно создается.
* @param manager
* @param client
* @return ЕМС клиента
*/
public static Emc getEmcByClient(EntityManager manager, Client client){
Query qery = manager.createQuery("select a from " + Emc.class.getSimpleName() + " a where a.client.id = :clientid");
qery.setParameter("clientid", client.getId());
@SuppressWarnings("unchecked")
List<Emc> list = qery.getResultList();
Emc emc;
if (list.size() != 0) {
emc = list.get(0);
} else {
emc = new Emc();
emc.setClient(client);
manager.persist(emc);
manager.flush();
manager.refresh(emc);
}
return emc;
}
/**
* Возвращает ЕМС клиента, если ЕМС не существует, оно создается.
* @throws ClipsServerException
* @return ЕМС клиента
*/
@Override
public EmcDetails getEmc() throws ClipsServerException {
//Не надо запрещать доступ - просто затереть поле анамнеза
//checkCommandAccessibility(COMMAND_READ_EMC);
Client entity = getExistentEntity();
EmcDetails details = getEmcByClient(manager, entity).getDetails(this);
return details;
}
/**
* Возвращает список работ клиента
* В системе безопасности это комманда COMMAND_READ.
* @return список работ
*/
@Override
public List<JobDetails> getJobList() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ);
Client entity = getExistentEntity();
List jobs = findEntityList(Job.class, "client", entity, "ORDER BY a.begin");
List<JobDetails> res = new ArrayList<JobDetails>();
Iterator i = jobs.iterator();
while (i.hasNext()) {
Job j = (Job) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает последнюю работу клиента
* @return список работ
* @throws ClipsServerException
*/
@Override
public JobDetails getLastJob() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ);
Client entity = getExistentEntity();
List jobs = findEntityList(Job.class, "client", entity, " AND a.end IS NULL ORDER BY a.begin DESC");
if (jobs.isEmpty()) {
return null;
}
Job job = (Job) jobs.get(0);
return job.getDetails(this);
}
/**
* Вовзвращает список договоров, в которых учавствует данный клиент.
* В системе безопасности это комманда COMMAND_READ_CONTRACT.
* @return список договоров
*/
@Override
public List<PolisDetails> getPolisList() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_CONTRACT);
Client entity = getExistentEntity();
List<Polis> ps = findEntityList(Polis.class, "client", entity);
List<PolisDetails> res = new ArrayList<PolisDetails>();
Iterator<Polis> i = ps.iterator();
while (i.hasNext()) {
Polis j = i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает список услуг, которые еще не оказаны
* В системе безопасности это комманда COMMAND_READ.
* @return список услуг
*/
@Override
public List<ServiceRenderDetails> getServiceRendersToRender() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ);
Client entity = getExistentEntity();
Field fields[] = {
new Field("polis.client", entity),
new Field("renderedDate", "", Field.OPERATOR_IS_NULL),
new Field("cancelled", false)
};
List contracts = findEntityList(ServiceRender.class, fields);
List<ServiceRenderDetails> res = new ArrayList<ServiceRenderDetails>();
Iterator i = contracts.iterator();
while (i.hasNext()) {
ServiceRender sr = (ServiceRender) i.next();
res.add(sr.getDetails(this));
}
return res;
}
/**
* Возвращает список услуг, которые еще не закреплены в стататлонах
* В системе безопасности это комманда COMMAND_READ.
* @return список договоров
*/
@Override
public List<ServiceRenderDetails> getServiceRendersNotInDisease() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ);
Client entity = getExistentEntity();
Field fields[] = {
new Field("polis.client", entity),
new Field("disease", "", Field.OPERATOR_IS_NULL),
new Field("cancelled", false)
};
List contracts = findEntityList(ServiceRender.class, fields);
List<ServiceRenderDetails> res = new ArrayList<ServiceRenderDetails>();
Iterator i = contracts.iterator();
while (i.hasNext()) {
ServiceRender sr = (ServiceRender) i.next();
res.add(sr.getDetails(this));
}
return res;
}
/**
* Возвращает список услуг, и закрепленных и не закрепленных,
* назначенных в заданном промежутке дат. присутствует фильтр по контракту
* если contractID == 0 то по любому контракту
* @return список договоров
*/
@Override
public List<ServiceRenderDetails> getServiceRenders(Date begin, Date end, int contractID) throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ);
Client entity = getExistentEntity();
Field fields[] = {
new Field("polis.client", entity),
new Field("date", begin, Field.OPERATOR_EQUAL_OR_MORE),
new Field("date", end, Field.OPERATOR_EQUAL_OR_LESS),
new Field("cancelled", false)
};
Field fields1[] = {
new Field("polis.contract.id", contractID),
new Field("polis.client", entity),
new Field("date", begin, Field.OPERATOR_EQUAL_OR_MORE),
new Field("date", end, Field.OPERATOR_EQUAL_OR_LESS),
new Field("cancelled", false)
};
List serRens;
if (contractID != 0) {
serRens = findEntityList(ServiceRender.class, fields1);
} else {
serRens = findEntityList(ServiceRender.class, fields);
}
List<ServiceRenderDetails> res = new ArrayList<ServiceRenderDetails>();
Iterator i = serRens.iterator();
while (i.hasNext()) {
ServiceRender sr = (ServiceRender) i.next();
res.add(sr.getDetails(this));
}
return res;
}
/**
* Возвращает список дисконтных карт, закрепленных за клиентом.
* В системе безопасности это комманда COMMAND_READ.
* @return список дисконтных карт
*/
@Override
public List<DiscountCardDetails> getDiscountCards() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ);
Client entity = getExistentEntity();
List cards = findEntityList(DiscountCard.class, "client", entity);
List<DiscountCardDetails> res = new ArrayList<DiscountCardDetails>();
Iterator i = cards.iterator();
while (i.hasNext()) {
DiscountCard j = (DiscountCard) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает список направлений клиента.
* В системе безопасности это комманда COMMAND_READ_EMC.
* @return список направлений
*/
@Override
public List<DirectionDetails> getDirectionList() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_EMC);
Client entity = getExistentEntity();
Field fields[] = {
new Field("serviceRender.disease.emc.client", entity),
new Field("serviceRender.cancelled", false)
};
List list = findEntityList(Direction.class, fields);
List<DirectionDetails> res = new ArrayList<DirectionDetails>();
Iterator i = list.iterator();
while(i.hasNext()) {
Direction j = (Direction) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает список справок клиента.
* В системе безопасности это комманда COMMAND_READ_EMC.
* @return список справок
*/
@Override
public List<CertificateDetails> getCertificateList() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_CERTIFICATE);
Client entity = getExistentEntity();
List list = findEntityList(Certificate.class, "client", entity);
List<CertificateDetails> res = new ArrayList<CertificateDetails>();
Iterator i = list.iterator();
while(i.hasNext()) {
Certificate j = (Certificate) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает список противопоказаний клиента.
* В системе безопасности это комманда COMMAND_READ_EMC.
* @return список противопоказаний
*/
@Override
public List<ContraindicationDetails> getContraindicationList() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_CONTRAINDICATION);
Client entity = getExistentEntity();
Field fields[] = {
new Field("serviceRender.disease.emc.client", entity),
new Field("serviceRender.cancelled", false)
};
List list = findEntityList(Contraindication.class, fields);
List<ContraindicationDetails> res = new ArrayList<ContraindicationDetails>();
Iterator i = list.iterator();
while(i.hasNext()) {
Contraindication j = (Contraindication) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает список диагнозов клиента (исключая сопутствующие).
* В системе безопасности это комманда COMMAND_READ_EMC.
* @return список диагнозов
*/
@Override
public List<DiagnosisDetails> getDiagnosisList() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_EMC);
Client entity = getExistentEntity();
Field fields[] = {
new Field("serviceRender.disease.emc.client", entity),
new Field("referenced","",Field.OPERATOR_IS_NULL),
new Field("serviceRender.cancelled", false)
};
List list = findEntityList(Diagnosis.class, fields);
List<DiagnosisDetails> res = new ArrayList<DiagnosisDetails>();
Iterator i = list.iterator();
while(i.hasNext()) {
Diagnosis j = (Diagnosis) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает список диагнозов клиента (включая сопутствующие).
* В системе безопасности это комманда COMMAND_READ_EMC.
* Если diseaseID != 0 то вернет только диагнозы из заболевания
* @return список диагнозов
*/
@Override
public List<DiagnosisDetails> getFullDiagnosisList(int diseaseID) throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_EMC);
Client entity = getExistentEntity();
List list;
if (diseaseID == 0) {
Field[] fields = {
new Field("serviceRender.disease.emc.client", entity),
new Field("serviceRender.cancelled", false)
};
list = findEntityList(Diagnosis.class, fields);
} else {
Field[] fields = {
new Field("serviceRender.disease.id", diseaseID),
new Field("serviceRender.cancelled", false)
};
list = findEntityList(Diagnosis.class, fields);
}
List<DiagnosisDetails> res = new ArrayList<DiagnosisDetails>();
Iterator i = list.iterator();
while(i.hasNext()) {
Diagnosis j = (Diagnosis) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает список назначений клиента.
* В системе безопасности это комманда COMMAND_READ_EMC.
* @return список рецептов
*/
@Override
public List<PrescriptionDetails> getPrescriptionList() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_EMC);
Client entity = getExistentEntity();
Field fields[] = {
new Field("serviceRender.disease.emc.client", entity),
new Field("serviceRender.cancelled", false)
};
List list = findEntityList(Prescription.class, fields);
List<PrescriptionDetails> res = new ArrayList<PrescriptionDetails>();
Iterator i = list.iterator();
while(i.hasNext()) {
Prescription j = (Prescription) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает список льготных рецептов.
* В системе безопасности это комманда COMMAND_READ_EMC.
* @return список рецептов
*/
@Override
public List<PrescriptionDloDetails> getPrescriptionDloList() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_EMC);
Client entity = getExistentEntity();
Field fields[] = {
new Field("serviceRender.disease.emc.client", entity),
new Field("serviceRender.cancelled", false)
};
List list = findEntityList(PrescriptionDlo.class, fields);
List<PrescriptionDloDetails> res = new ArrayList<PrescriptionDloDetails>();
Iterator i = list.iterator();
while(i.hasNext()) {
PrescriptionDlo j = (PrescriptionDlo) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* @return список рекомендаций пациента
* @throws generic.ClipsServerException
*/
@Override
public List<RecommendationDetails> getRecommedationList() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_EMC);
Client entity = getExistentEntity();
Field fields[] = {
new Field("serviceRender.disease.emc.client", entity),
new Field("serviceRender.cancelled", false)
};
List list = findEntityList(Recommendation.class, fields);
List<RecommendationDetails> res = new ArrayList<RecommendationDetails>();
Iterator i = list.iterator();
while(i.hasNext()) {
Recommendation j = (Recommendation) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает список больничных клиента.
* В системе безопасности это комманда COMMAND_READ_EMC.
* @return список больничных
*/
@Override
public List<SicklistDetails> getSicklistList() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_EMC);
Client entity = getExistentEntity();
List list = findEntityList(Sicklist.class, "diagOpen.serviceRender.disease.emc.client", entity, "order by a.dateOpen");
List<SicklistDetails> res = new ArrayList<SicklistDetails>();
Iterator i = list.iterator();
while(i.hasNext()) {
Sicklist j = (Sicklist) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
* Возвращает список больничных клиента в текущем году.
* В системе безопасности это комманда COMMAND_READ.
* @return список больничных
* @throws ClipsServerException
*/
@Override
public List<SicklistDetails> getSicklistsInCurrentYear() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ_EMC);
Client entity = getExistentEntity();
Calendar cal = GregorianCalendar.getInstance();
cal.set(cal.get(Calendar.YEAR), 1, 1, 0, 0, 0);
Date yearBegin = cal.getTime();
Field fields[] = {
new Field("diagOpen.serviceRender.disease.emc.client", entity),
new Field("dateOpen", yearBegin, Field.OPERATOR_EQUAL_OR_MORE)
};
List list = findEntityList(Sicklist.class, fields, " order by a.dateOpen");
List<SicklistDetails> res = new ArrayList<SicklistDetails>();
Iterator i = list.iterator();
while(i.hasNext()) {
Sicklist j = (Sicklist) i.next();
res.add(j.getDetails((RightChecker) this));
}
return res;
}
/**
*
* @return
*/
public static Polis findPolisOMI(Client entity, EntityManager manager) throws ClipsServerException {
Query q = manager.createQuery("SELECT a FROM Polis a WHERE "
+ "(a.contract.type = :ctype) "
+ "AND a.trash = false "
+ "AND (a.client = :client) "
+ "AND (a.contract.begin <= :current) "
+ "AND ((a.contract.end IS NULL) OR (a.contract.end > :current))");
q.setParameter("ctype", Contract.TYPE_OMI);
q.setParameter("current", GregorianCalendar.getInstance().getTime());
q.setParameter("client", entity);
List list = q.getResultList();
if (list.size() == 0) {
return null;
} else if (list.size() > 1) {
throw new ClipsServerException("Найдено " + list.size() + " полисов в действующем договоре ОМС");
} else {
return (Polis) list.get(0);
}
}
/**
* Возвращает номер полиса обязательного медицинского страхования
* @return
* @throws generic.ClipsServerException
*/
@Override
public PolisDetails getPolisOMI() throws ClipsServerException {
Polis polis = findPolisOMI(getExistentEntity(), manager);
if (polis != null) {
return polis.getDetails(this);
} else {
return null;
}
}
/**
* Записывает номер полиса обязательного медициенского страхования в действующий договор ОМС
* при необходимости создает новый полис
* @param value
* @throws generic.ClipsServerException
*/
@Override
public ModificationInfo setPolisOMI(PolisDetails polisDetails) throws ClipsServerException {
Polis polis = findPolisOMI(getExistentEntity(), manager);
ArrayList<AuditDetails> auditDetailsList = new ArrayList<AuditDetails>(2);
if (polis != null && polisDetails.id == 0) {
//замена полиса
AuditDetails auditRemovePolis = removePolisOMI(polis);
auditDetailsList.add(auditRemovePolis);
polis = null;
}
if (polis == null) {
//Создание полиса - либо небыло либо был, но заменяется
polis = new Polis();
}
//и в любом случае заполнение и сохранение
AuditDoc<Polis> auditDoc = new AuditDoc<Polis>(polis, getCollaborator());
fillPolisOMI(polis, polisDetails);
saveEntity(polis);
if (auditDoc.check(polis)) {
AuditDetails auditChangePolis = persistAudit(auditDoc);
auditDetailsList.add(auditChangePolis);
}
return new ModificationInfo(polis.getId(), auditDetailsList);
}
@Override
public ClientDocumentDetails getClientDocument() throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ);
Client entity = getExistentEntity();
ClientDocument doc = entity.getClientDocument();
if (doc == null) {
doc = new ClientDocument();
}
return doc.getDetails(this);
}
@Override
public ModificationInfo setClientDocument(ClientDocumentDetails details) throws ClipsServerException {
checkCommandAccessibility(COMMAND_MODIFY);
Client entity = getExistentEntity();
AuditDoc<Client> auditDoc = new AuditDoc<Client>(entity, getCollaborator());
ClientDocument doc = entity.getClientDocument();
if (details.typeID == 0) {
if (doc != null) {
entity.setClientDocument(null);
saveEntity(entity);
removeEntity(doc);
}
}
else {
boolean newDoc = false;
if (doc == null) {
doc = new ClientDocument();
newDoc = true;
}
doc.setNumber(details.number);
doc.setSeries(details.series);
doc.setDate(details.date);
doc.setDoctype(findEntity(ClientDocumentType.class, details.typeID));
doc.setGivenPlace(details.enterpriseID == 0 ? null : findEntity(DocumentGivenPlace.class, details.enterpriseID));
saveEntity(doc);
if(newDoc) {
entity.setClientDocument(doc);
saveEntity(entity);
}
}
if (auditDoc.check(entity)) {
return new ModificationInfo(persistAudit(auditDoc));
} else {
return new ModificationInfo(null);
}
}
private void fillPolisOMI(Polis polis, PolisDetails details) throws ClipsServerException {
polis.setClient(getExistentEntity());
polis.setContract(findEntity(Contract.class, details.contractID));
polis.setSeries(details.series);
polis.setNumber(details.number);
polis.setTillDate(details.tillDate);
polis.setFromDate(details.fromDate);
polis.setRegionCode(findEntity(RegionIdCode.class, details.regionCodeId));
polis.setCollaborator(findEntity(Collaborator.class, getCollaboratorId()));
polis.setInsurer(findEntity(Insurer.class, details.insurerID));
Address address = polis.getAddress();
AddressDetails ad = details.addressDetail;
if (ad != null && ad.objectId != 0) {
if (address == null){
address = new Address();
}
address.setAddressObject(findEntity(AddressObject.class, ad.objectId));
address.setBuilding(ad.building);
address.setFlat(ad.flat);
saveEntity(address);
polis.setAddress(address);
}else{
if (address != null) {
removeEntity(address);
}
polis.setAddress(null);
}
}
private AuditDetails removePolisOMI(Polis polis) throws ClipsServerException {
AuditDoc<Polis> auditDoc = new AuditDoc<Polis>(polis, getCollaborator());
int count = getEntityCount(ServiceRender.class, new Field[]{new Field("polis", polis)});
count += getEntityCount(ProfcheckupItem.class, new Field[]{new Field("polis", polis)});
if (count > 0) {
polis.setTrash(true);
saveEntity(polis);
auditDoc.check(polis);
return persistAudit(auditDoc);
} else {
Address address = polis.getAddress();
if (address != null) {
removeEntity(address);
}
removeEntity(polis);
auditDoc.check(null);
return persistAudit(auditDoc);
}
}
@Override
public ArrayList<DiagnosisDetails> getLastDiagnosis() throws ClipsServerException {
Field[] fields = new Field[] {
new Field("referenced", null, Field.OPERATOR_IS_NULL),
new Field("serviceRender.disease.emc.client", getExistentEntity())};
List<Diagnosis> diagnosisList = findEntityList(Diagnosis.class, fields, "order by a.date desc");
ArrayList<Diagnosis> temp = new ArrayList<Diagnosis>();
//Заболевания в которых есть заключительные диагнозы
HashSet<Integer> setDisease = new HashSet<Integer>();
for (Diagnosis diagnosis : diagnosisList) {
if (diagnosis.getType().getId() == DiagnosisType.DIAGNOSIS_TYPE_FINAL) {
setDisease.add(diagnosis.getServiceRender().getDisease().getId());
}
temp.add(diagnosis);
}
//Пробежимся по временному массиву и исключим предварительные диагнозы если есть заключительные
for (int i = temp.size() -1 ; i >= 0; i--) {
Diagnosis diagnosis = temp.get(i);
int disID = diagnosis.getServiceRender().getDisease().getId();
if (setDisease.contains(disID)
&& diagnosis.getType().getId() == DiagnosisType.DIAGNOSIS_TYPE_PRELIMINARY) {
temp.remove(i);
}
}
//преобразование и возврат деталей
ArrayList<DiagnosisDetails> target = new ArrayList<DiagnosisDetails>();
for (int i = 0; i < temp.size(); i++) {
Diagnosis diagnosis = temp.get(i);
target.add(diagnosis.getDetails(this));
}
return target;
}
@Override
public FacilityClientChunk getClientExemption() throws ClipsServerException {
Client client = getExistentEntity();
Field[] fs = new Field[4];
fs[0] = new Field("surname.id", client.getSurname() != null ? client.getSurname().getId() : null);
fs[1] = new Field("name.id", client.getName() != null ? client.getName().getId() : null);
fs[2] = new Field("pathronymic.id", client.getPathronymic() != null ? client.getPathronymic().getId() : null);
fs[3] = new Field("born", client.getBorn());
List<FacilityClient> list = findEntityList(FacilityClient.class, fs);
if (list.isEmpty()) {
return null;
}
FacilityClient facClient = list.get(0);
FacilityClientChunk res = new FacilityClientChunk();
res.snils = facClient.getSnils();
res.clientId = client.getId();
boolean both = (facClient.getExcemption1() != null)
&& (facClient.getExcemption2() != null);
int ex1 = facClient.getExcemption1() != null ? facClient.getExcemption1().getId() : 0;
int ex2 = facClient.getExcemption2() != null ? facClient.getExcemption2().getId() : 0;
if (!both) {
res.exempId = ex1 + ex2;
}
else {
res.exempId = ex1;
}
res.nsuBegin = facClient.getNsuBegin();
res.nsuEnd = facClient.getNsuEnd();
res.nsuFlag = facClient.getFlagNSU();
res.regBegin = facClient.getRegBegin();
res.regEnd = facClient.getRegEnd();
FacilityDocument doc = null;
List<FacilityDocument> docList =
findEntityList(FacilityDocument.class, new Field[]{new Field("snils", facClient.getSnils())});
if (docList.isEmpty()) {
return res;
}
Collections.sort(docList, new Comparator<FacilityDocument>() {
@Override
public int compare(FacilityDocument o1, FacilityDocument o2) {
if (o1.getGspEnd()==null) {
return 1;
}
if (o2.getGspEnd()==null) {
return -1;
}
return o1.getGspEnd().compareTo(o2.getGspEnd());
}
});
for (int i = 0; i < docList.size(); i++) {
doc = docList.get(i);
if (doc.getExcemption() != null) {
int ex = doc.getExcemption().getId();
if ((!both && ex == res.exempId)
|| (both && (ex == ex1 || ex == ex2))
|| (ex1 + ex2 == 0)) {
res.docName = doc.getDocumentName();
res.docSN = doc.getDocumentSN();
res.gspBegin = doc.getGspBegin();
res.gspEnd = doc.getGspEnd();
res.exempId = ex;
}
}
}
return res;
}
@Override
public ArrayList<CommitteeDetails> getClientCommittees() throws ClipsServerException {
ArrayList<CommitteeDetails> res = new ArrayList<CommitteeDetails>();
Client client = getExistentEntity();
Field[] field = new Field[]{new Field("direction.serviceRender.polis.client", client)};
List<CommitteeDirection> comDirs = findEntityList(CommitteeDirection.class, field);
for (CommitteeDirection dir : comDirs) {
res.add(dir.getCommittee().getDetails(this));
}
return res;
}
@Override
public int getDefaultDistrict(int streetID, String buildingNumberString) throws ClipsServerException{
AddressObject object = findEntity(AddressObject.class, streetID);
if (object.getType().getLevel() != 5) {
throw new ClipsServerException("Поиск возможен только по улице");
}
List<AddressDistrict> adList = findEntityList(AddressDistrict.class, "addressObject", object);
for (AddressDistrict ad : adList) {
if (include(ad, buildingNumberString)) {
return ad.getDistrict().getId();
}
}
return 0;
}
/**
* Проверяет входит ли дом с данным номером в квартал
* @param block
* @param buildingNumber
* @return
*/
private boolean include(AddressDistrict block, String buildingNumberString) throws ClipsServerException{
int buildingNumber = 0;
if (Pattern.matches("[0-9]+", buildingNumberString)){
buildingNumber = Integer.parseInt(buildingNumberString);
}
ArrayList<String> numbers = createNumbers(block);
if (numbers.size() == 1 && numbers.get(0).isEmpty()) {
return true;
}
String s;
for (int i = 0; i < numbers.size(); i++) {
s = numbers.get(i);
if (buildingNumber > 0){//только в этом случае есть смысл искать по диапазонам
if (Pattern.matches(AddressObject.pattern1, s)) {//указана сторона
int breakPos = s.indexOf("-");
int start = Integer.parseInt(s.substring(2, breakPos));
int end = Integer.parseInt(s.substring(breakPos + 1, s.length() - 1));
if (buildingNumber % 2 == start % 2 && start <= buildingNumber && buildingNumber <= end){
return true;
}
} else if (Pattern.matches(AddressObject.pattern3, s)) {//без указания стороны
int breakPos = s.indexOf("-");
int start = Integer.parseInt(s.substring(0, breakPos));
int end = Integer.parseInt(s.substring(breakPos + 1, s.length()));
if (start <= buildingNumber && buildingNumber <= end){
return true;
}
}
} else if (!Pattern.matches(AddressObject.pattern1, s) && !Pattern.matches(AddressObject.pattern3, s)) {//s не диапазон
if (s.equalsIgnoreCase(buildingNumberString)){
return true;
}
}
}
return false;
}
private ArrayList<String> createNumbers(AddressDistrict block) throws ClipsServerException {
String title = block.getTitle().trim();
ArrayList<String> res = new ArrayList<String>(0);
String s = "";
for (int i = 0; i < title.length(); i++) {
if (title.charAt(i) == ',') {
res.add(s.trim());
s = "";
} else {
s += title.charAt(i);
}
}
res.add(s.trim());
return res;
}
}