/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans.user.search;
import beans.user.client.entity.Client;
import beans.user.client.entity.ClientDetails;
import framework.audit.AuditDetails;
import framework.beans.SecuredBean;
import framework.beans.security.BeanRights;
import framework.generic.ClipsServerException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
/*
SELECT c.id FROM Client c WHERE
c.id in (SELECT DISTINCT a.client.id FROM SheduleReception a WHERE a.begin > '1-07-2008')
AND c.id in (SELECT DISTINCT b.client.id FROM SheduleReception b WHERE b.begin between '2008-05-01' and '2008-09-01')
AND c.id in (SELECT DISTINCT j.client.id from Job j where j.enterprise.id=3)
AND c.surname.title LIKE 'Рег%'
AND c.name.title LIKE 'Веталег'
AND c.pathronymic.title LIKE 'Ц%'
*/
import beans.UserRightsSet;
import beans.contract.entity.Contract;
import beans.contract.entity.Polis;
import beans.directory.enterprise.Enterprise;
import beans.discount.entity.DiscountCard;
import beans.doctor.disease.Disease;
import beans.doctor.emc.Emc;
import beans.profcheckup.entity.ProfcheckupItem;
import beans.service.ServiceRender;
import beans.shedule.reception.SheduleReception;
import beans.user.client.updater.ClientUniq;
import beans.user.collaborator.entities.Collaborator;
import beans.user.job.entity.Job;
import framework.audit.AuditDoc;
import framework.beans.ModificationInfo;
import framework.beans.address.entities.Address;
import framework.beans.address.entities.AddressDetails;
import framework.beans.address.entities.AddressObject;
import framework.beans.client.clientDocument.ClientDocument;
import framework.utils.DateTimeUtils;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import javax.ejb.Stateful;
/**
* @security - Ok.
* @author axe
*/
@Stateful(mappedName="clips-beans/ClientSearchBean")
public class ClientSearchBean extends SecuredBean implements ClientSearchBeanRemote {
public static int COMMAND_READ = 0;
@Override
protected void initBeanRights() {
int[] r = new int[1];
r[COMMAND_READ] = RightPresence(UserRightsSet.READ_CLIENT_SEARCH.id);
rights = new BeanRights(r);
}
/**
*
* @param filter
* @return
* @throws ClipsServerException
*/
@Override
public ClientListChunk getList(ClientFilter filter) throws ClipsServerException {
checkCommandAccessibility(COMMAND_READ);
ArrayList<Field> fields = new ArrayList<Field>();
if(filter.EMCnum != null/* && !filter.EMCnum.isEmpty()*/) {
FieldInSellect subQuery = new FieldInSellect("id", "client.id", Emc.class, FieldInSellect.OPERATOR_IN_SELLECT);
subQuery.add(new Field("number", filter.EMCnum.replace("%", ""), Field.OPERATOR_LIKE));
fields.add(subQuery);
}
if(filter.inReception) {
FieldInSellect subQuery = new FieldInSellect("id", "client.id", SheduleReception.class, FieldInSellect.OPERATOR_IN_SELLECT);
Date today = DateTimeUtils.getDateOnly(new Date());
subQuery.add(new Field("begin", today, Field.OPERATOR_EQUAL_OR_MORE));
if(filter.collId != 0){
subQuery.add(new Field("collaborator.id", filter.collId));
}
fields.add(subQuery);
}
if(filter.lastComingFrom != null && filter.lastComingTill != null) {
if (filter.lastComingByTap){
FieldInSellect subQuery = new FieldInSellect("id", "disease.emc.client.id", ServiceRender.class, FieldInSellect.OPERATOR_IN_SELLECT);
subQuery.add(new Field("date", filter.lastComingFrom, Field.OPERATOR_EQUAL_OR_MORE));
subQuery.add(new Field("date", filter.lastComingTill, Field.OPERATOR_LESS));
if (filter.collId != 0){
subQuery.add(new Field("functions.collaborator.id", filter.collId));
}
fields.add(subQuery);
}
else{
FieldInSellect subQuery = new FieldInSellect("id", "client.id", SheduleReception.class, FieldInSellect.OPERATOR_IN_SELLECT);
subQuery.add(new Field("begin", filter.lastComingFrom, Field.OPERATOR_EQUAL_OR_MORE));
subQuery.add(new Field("begin", filter.lastComingTill, Field.OPERATOR_LESS));
if (filter.collId != 0){
subQuery.add(new Field("collaborator.id", filter.collId));
}
fields.add(subQuery);
}
}
if(filter.enterpriseID != null) {
if(filter.includeSubEnterprises) {
FieldInSellect subQuery = new FieldInSellect("id", "client.id", Job.class, FieldInSellect.OPERATOR_IN_SELLECT);
Enterprise ent = findEntity(Enterprise.class, filter.enterpriseID);
subQuery.add(new Field("enterprise.treepath", ent.getTreePath() + "%", Field.OPERATOR_LIKE));
fields.add(subQuery);
}
else {
if (filter.enterpriseID != 0){
FieldInSellect subQuery = new FieldInSellect("id", "client.id", Job.class, FieldInSellect.OPERATOR_IN_SELLECT);
subQuery.add(new Field("enterprise.id", filter.enterpriseID));
fields.add(subQuery);
}
else{
FieldInSellect subQuery = new FieldInSellect("id", "client.id", Job.class, FieldInSellect.OPERATOR_NOT_IN_SELLECT);
fields.add(subQuery);
fields.add(subQuery);
}
}
}
if(filter.sexID != 0) {
fields.add(new Field("sex.id", filter.sexID));
}
if(filter.name != null && !filter.name.isEmpty()) {
fields.add(new Field("name.title", filter.name.replace("%", "") + "%", Field.OPERATOR_LIKE));
}
if(filter.surname != null && !filter.surname.isEmpty()) {
fields.add(new Field("surname.title", filter.surname.replace("%", "") + "%", Field.OPERATOR_LIKE));
}
if(filter.pathron != null && !filter.pathron.isEmpty()) {
fields.add(new Field("pathronymic.title", filter.pathron.replace("%", "") + "%", Field.OPERATOR_LIKE));
}
if (filter.ad != null && filter.ad.objectId != 0) {
AddressDetails ad = filter.ad;
AddressObject addressObject = findEntity(AddressObject.class, ad.objectId);
int level = addressObject.getType().getLevel();
if (addressObject.getId() == AddressObject.ADDRESS_OBJECT_RUSSIA){
//у буржундии код начинается с минуса
// TODO: выглядит очень странно, можте глюк?
fields.add(new Field("address.addressObject.kladrCode", "-%", Field.OPERATOR_NOT_LIKE));
}
else{
String code = addressObject.getKladrCode();
String subcode;
switch (level) {
case 1:
subcode = code.substring(0, 2);
break;
case 2:
subcode = code.substring(0, 5);
break;
case 3:
subcode = code.substring(0, 8);
break;
case 4:
subcode = code.substring(0, 11);
break;
case 5:
subcode = code.substring(0, 15);
break;
default:
subcode = code;
}
fields.add(new Field("address.addressObject.kladrCode", subcode + "%", Field.OPERATOR_LIKE));
}
if (filter.ad.building != null && !ad.building.isEmpty()) {
fields.add(new Field("address.building", filter.ad.building));
}
if (filter.ad.flat != null && !ad.flat.isEmpty()) {
fields.add(new Field("address.flat", filter.ad.flat));
}
}
if(filter.inn != null && !filter.inn.isEmpty()){
String inn = filter.inn.replaceAll("?", "_");
inn = inn.replaceAll("*", "%");
fields.add(new Field("c.inn", inn, Field.OPERATOR_LIKE));
}
if(filter.socialCardCode != null && !filter.socialCardCode.isEmpty()){
fields.add(new Field("socialCardId", filter.socialCardCode));
}
int count = getEntityCount(Client.class, fields);
ArrayList<Client> res = new ArrayList<Client>(findEntityListWithResCount(Client.class, fields, "", 100));
/*for (Client client : res) {
client.getEmcList().size(); //костыль для прогрузки ЕМЦ из-за глюка с LAZY коллекциями
manager.refresh(client);
}*/
Collections.sort(res);
ArrayList<ClientDetails> det = getEntytyDetailsList(res);
ClientListChunk chunk = new ClientListChunk();
chunk.clientList = det;
chunk.listSize = count;
return chunk;
}
@Override
public ModificationInfo unionPacients() throws ClipsServerException {
HashMap<Integer, Client> pacients = new HashMap<Integer, Client>();
String sql = "SELECT c1 from Client c1, Client c2 "
+ "WHERE c1.id <> c2.id "
+ "AND c1.surname.id = c2.surname.id "
+ "AND c1.name.id = c2.name.id "
+ "AND c1.pathronymic.id = c2.pathronymic.id "
+ "AND c1.born = c2.born ";
Query query = manager.createQuery(sql);
List<Client> res = query.getResultList();
for (int i = 0; i < res.size(); i++) {
Client c1 = res.get(i);
pacients.put(c1.getId(), c1);
}
ArrayList<Client> pacientsA = new ArrayList<Client>(pacients.values());
HashMap<ClientUniq, ArrayList<Client>> pacientsMap = new HashMap<ClientUniq, ArrayList<Client>>();
for (int i = 0; i < pacientsA.size(); i++) {
Client c = pacientsA.get(i);
ClientDetails det = c.getDetails(this);
ClientUniq p =
new ClientUniq(det.surnameId, det.nameId, det.pathronId, det.born);
ArrayList<Client> clA = pacientsMap.get(p);
if (clA == null) {
clA = new ArrayList<Client>();
}
clA.add(c);
pacientsMap.put(p, clA);
}
ArrayList<AuditDetails> auditDetailsList = new ArrayList<AuditDetails>();
Iterator<ArrayList<Client>> pacientsI = pacientsMap.values().iterator();
while (pacientsI.hasNext()) {
ArrayList<Client> array = pacientsI.next();
Client dst = array.get(0);
System.out.println("***************************************************************************");
System.out.println("ПАЦИЕНТ ГЛАВНЫЙ " + dst.getId() + " " + dst.getFio());
for (int i = 1; i < array.size(); i++) {
Client src = array.get(i);
System.out.println(" ПАЦИЕНТ " + src.getId() + " " + src.getFio());
AuditDetails unionCollab = unionCollab(dst, src);
if (unionCollab != null) {
auditDetailsList.add(unionCollab);
}
auditDetailsList.addAll(unionEMC(dst, src));
auditDetailsList.addAll(unionJob(dst, src));
auditDetailsList.addAll(unionDiscCard(dst, src));
auditDetailsList.addAll(unionPolis(dst, src, false));
auditDetailsList.addAll(unionPolis(dst, src, true));
auditDetailsList.addAll(fillClientDetails(dst, src));
}
}
return new ModificationInfo(pacientsMap.size(), auditDetailsList);
}
private AuditDetails unionCollab(Client dst, Client src) throws ClipsServerException {
Collaborator coll1 = null;
Collaborator coll2 = null;
List<Collaborator> collL = findEntityList(Collaborator.class, "client.id", dst.getId());
if (!collL.isEmpty()) {
coll1 = collL.get(0);
}
collL = findEntityList(Collaborator.class, "client.id", src.getId());
if (!collL.isEmpty()) {
coll2 = collL.get(0);
}
if (coll1 != null && coll2 != null) {
throw new ClipsServerException("На каждого из объединяемых пациентов ссылаются \"Сотрудники\"");
} else if (coll2 != null) {
AuditDoc<Collaborator> auditColl = new AuditDoc<Collaborator>(coll2, getCollaborator());
coll2.setClient(dst);
saveEntity(coll2);
auditColl.check(coll2);
System.out.println(" КОЛЛАБ " + coll2.getId());
return persistAudit(auditColl);
} else if (coll1 != null) {
System.out.println(" КОЛЛАБ " + coll1.getId());
}
return null;
}
private ArrayList<AuditDetails> unionEMC(Client dst, Client src) throws ClipsServerException {
Emc emc1 = null;
Emc emc2 = null;
List<Emc> emcL = findEntityList(Emc.class, "client.id", src.getId());
if (!emcL.isEmpty()) {
emc2 = emcL.get(0);
}
else {
return null;
}
emcL = findEntityList(Emc.class, "client.id", dst.getId());
if (emcL.isEmpty()) {
AuditDoc<Emc> auditEmc = new AuditDoc<Emc>(emc2, getCollaborator());
emc2.setClient(dst);
saveEntity(emc2);
System.out.println(" EMC2=" + emc2.getId() + "-->cl=" + emc2.getClient().getId());
auditEmc.check(emc2);
ArrayList<AuditDetails> target = new ArrayList<AuditDetails>(1);
target.add(persistAudit(auditEmc));
return target;
} else {
ArrayList<AuditDetails> target = new ArrayList<AuditDetails>();
emc1 = emcL.get(0);
AuditDoc<Emc> auditEmc = new AuditDoc<Emc>(emc1, getCollaborator());
System.out.println(" EMC1 id=" + emc1.getId() + " №" + emc1.getNumber() + " | EMC2 id=" + emc2.getId() + " №" + emc2.getNumber());
if (emc1.getNumber() == null || emc1.getNumber().isEmpty()) {
emc1.setNumber(emc2.getNumber());
}
if (emc1.getAnamnez() == null || emc1.getAnamnez().isEmpty()) {
emc1.setAnamnez(emc2.getAnamnez());
}
saveEntity(emc1);
auditEmc.check(emc1);
target.add(persistAudit(auditEmc));
List<Disease> disL = findEntityList(Disease.class, "emc.id", emc2.getId());
for (Disease d : disL) {
AuditDoc<Disease> auditDisease = new AuditDoc<Disease>(d, getCollaborator());
d.setEmc(emc1);
saveEntity(d);
System.out.println(" d.id=" + d.getId() + " d.emc.id" + d.getEmc().getId());
auditDisease.check(d);
target.add(persistAudit(auditDisease));
}
auditEmc = new AuditDoc<Emc>(emc2, getCollaborator());
removeEntity(emc2);
auditEmc.check(null);
target.add(persistAudit(auditEmc));
return target;
}
}
private ArrayList<AuditDetails> unionJob(Client dst, Client src) throws ClipsServerException {
System.out.println(" JOBS_2");
List<Job> jobL = findEntityList(Job.class, "client.id", src.getId());
ArrayList<AuditDetails> target = new ArrayList<AuditDetails>();
for (Job j : jobL) {
System.out.println(" id=" + j.getId() + " client_id=" + j.getClient().getId());
AuditDoc<Job> auditJob = new AuditDoc<Job>(j, getCollaborator());
j.setClient(dst);
saveEntity(j);
auditJob.check(j);
target.add(persistAudit(auditJob));
}
return target;
}
private ArrayList<AuditDetails> unionDiscCard(Client dst, Client src) throws ClipsServerException {
System.out.println(" DISCCARDS_2");
ArrayList<AuditDetails> target = new ArrayList<AuditDetails>();
List<DiscountCard> cardL = findEntityList(DiscountCard.class, "client.id", src.getId());
for (DiscountCard card : cardL) {
System.out.println(" id=" + card.getId() + " client_id=" + card.getClient().getId());
AuditDoc<DiscountCard> auditCard = new AuditDoc<DiscountCard>(card, getCollaborator());
card.setClient(dst);
saveEntity(card);
auditCard.check(card);
target.add(persistAudit(auditCard));
}
return target;
}
private ArrayList<AuditDetails> unionPolis(Client dst, Client src, boolean trash) throws ClipsServerException {
System.out.println(" POLISES trash=" + trash);
Field[] f1 = new Field[]{new Field("client.id", src.getId()), new Field("trash", trash)};
List<Polis> polisL2 = findEntityList(Polis.class, f1);
Field[] f2 = new Field[]{new Field("client.id", dst.getId()), new Field("trash", trash)};
List<Polis> polisL1 = findEntityList(Polis.class, f2);
ArrayList<AuditDetails> target = new ArrayList<AuditDetails>();
for (Polis polis2 : polisL2) {
Contract contract = polis2.getContract();
System.out.println(" CONTRACT id=" + contract.getId() + " №" + contract.getIndex());
Polis polis1 = null;
for (int i = 0; i < polisL1.size(); i++) {
if (polisL1.get(i).getContract().getId() == contract.getId()) {
polis1 = polisL1.get(i);
break;
}
}
if (polis1 == null) {
AuditDoc<Polis> auditPolis = new AuditDoc<Polis>(polis2, getCollaborator());
polis2.setClient(dst);
saveEntity(polis2);
System.out.println(" " + polis2.getId() + "--> client.id=" + polis2.getClient().getId());
auditPolis.check(polis2);
target.add(persistAudit(auditPolis));
} else {
System.out.println(" p2=" + polis2.getId() + "-->p1=" + polis1.getId());
int q1 = polisDetQuantity(polis1);
int q2 = polisDetQuantity(polis2);
if (q1 < q2) {
System.out.println(" polis2 has more details");
AuditDoc<Polis> auditPolis = new AuditDoc<Polis>(polis1, getCollaborator());
polis1.setNumber(polis2.getNumber());
polis1.setSeries(polis2.getSeries());
polis1.setInsurer(polis2.getInsurer());
polis1.setRegionCode(polis2.getRegionCode());
polis1.setTillDate(polis2.getTillDate());
polis1.setFromDate(polis2.getFromDate());
Address address = polis1.getAddress();
polis1.setAddress(polis2.getAddress());
manager.remove(address);
saveEntity(polis1);
auditPolis.check(polis1);
target.add(persistAudit(auditPolis));
} else {
System.out.println(" polis1 has more details");
Address address = polis2.getAddress();
manager.remove(address);
}
List<ProfcheckupItem> prchL = findEntityList(ProfcheckupItem.class, "polis.id", polis2.getId());
for (ProfcheckupItem prch : prchL) {
AuditDoc<ProfcheckupItem> auditDoc = new AuditDoc<ProfcheckupItem>(prch, getCollaborator());
prch.setPolis(polis1);
saveEntity(prch);
System.out.println(" pch=" + prch.getId() + " p=" + prch.getPolis().getId());
auditDoc.check(prch);
target.add(persistAudit(auditDoc));
}
List<ServiceRender> serL = findEntityList(ServiceRender.class, "polis.id", polis2.getId());
for (ServiceRender ser : serL) {
AuditDoc<ServiceRender> auditSerren = new AuditDoc<ServiceRender>(ser, getCollaborator());
ser.setPolis(polis1);
saveEntity(ser);
System.out.println(" srr=" + ser.getId() + " p=" + ser.getPolis().getId() + " d.id=" + ser.getDisease().getId());
auditSerren.check(ser);
target.add(persistAudit(auditSerren));
}
AuditDoc<Polis> auditPolis = new AuditDoc<Polis>(polis1, getCollaborator());
removeEntity(polis2);
auditPolis.check(null);
target.add(persistAudit(auditPolis));
}
}
return target;
}
private int polisDetQuantity(Polis polis) {
int q = 0;
String number = polis.getNumber();
if (number != null && !number.isEmpty() && !number.matches("^0+$")) {
q++;
}
String series = polis.getSeries();
if (series != null && !series.isEmpty() && !series.matches("^0+$")) {
q++;
}
if (polis.getInsurer() != null && polis.getInsurer().getId() != 0) {
q++;
}
if (polis.getRegionCode() != null && polis.getRegionCode().getId() != 0) {
q++;
}
if (polis.getTillDate() != null) {
q++;
}
if (polis.getFromDate() != null) {
q++;
}
if (polis.getAddress() != null) {
q++;
}
return q;
}
private ArrayList<AuditDetails> fillClientDetails(Client dst, Client src) throws ClipsServerException {
ArrayList<AuditDetails> target = new ArrayList<AuditDetails>();
System.out.println(" details");
ClientDetails detailsDst = dst.getDetails(this);
ClientDetails detailsSrc = src.getDetails(this);
AuditDoc<Client> auditDst = new AuditDoc<Client>(dst, getCollaborator());
if (detailsDst.socialCardCode == null || detailsDst.socialCardCode.isEmpty()) {
dst.setSocialCardId(detailsSrc.socialCardCode);
System.out.println(" change socialСardCode");
}
if (detailsDst.remarks == null || detailsDst.remarks.isEmpty()) {
dst.setRemarks(detailsSrc.remarks);
System.out.println(" change remarks");
}
if (detailsDst.email == null || detailsDst.email.isEmpty()) {
dst.setEmail(detailsSrc.email);
System.out.println(" change email");
}
if (detailsDst.telephones == null || detailsDst.telephones.isEmpty()) {
dst.setTelephones(detailsSrc.telephones);
System.out.println(" change telephones");
}
if (detailsDst.snils == null || detailsDst.snils.isEmpty() || detailsDst.snils.matches("^[0 -]+$")) {
dst.setSnils(detailsSrc.snils);
System.out.println(" change snils");
}
if (detailsDst.inn == null || detailsDst.inn.isEmpty() || detailsDst.inn.matches("^0+$")) {
dst.setInn(detailsSrc.inn);
System.out.println(" change inn");
}
if (detailsDst.motherId == 0 && detailsSrc.motherId != 0) {
dst.setMother(src.getMother());
System.out.println(" change mother");
}
if (detailsDst.fatherId == 0 && detailsSrc.fatherId != 0) {
dst.setFather(src.getFather());
System.out.println(" change father");
}
if (detailsDst.socialStatusId == 0 && detailsSrc.socialStatusId != 0) {
dst.setSocialStatus(src.getSocialStatus());
System.out.println(" change socialStatus");
}
if (detailsDst.userGroupId == 0 && detailsSrc.userGroupId != 0) {
dst.setUserGroup(src.getUserGroup());
System.out.println(" change userGroup");
}
if (detailsDst.districtId == 0 && detailsSrc.districtId != 0) {
dst.setDistrict(src.getDistrict());
System.out.println(" change district");
}
if (detailsDst.bloodGroupId == 0 && detailsSrc.bloodGroupId != 0) {
dst.setBloodGroup(src.getBloodGroup());
System.out.println(" change bloodGroup");
}
if ((dst.getPassword() == null || dst.getPassword().isEmpty())
&& src.getPassword() != null && !src.getPassword().isEmpty()) {
dst.setPassword(src.getPassword());
System.out.println(" change password");
}
Address address1 = dst.getAddress();
Address address2 = src.getAddress();
if (address1 == null) {
if (address2 != null) {
System.out.println(" cl1 set address2");
dst.setAddress(address2);
}
}
else {
if (address2 != null) {
manager.remove(address2);
System.out.println(" remove address2. cl1 has already address1");
}
}
ClientDocument doc1 = dst.getClientDocument();
ClientDocument doc2 = src.getClientDocument();
if (doc1 == null) {
if (doc2 != null) {
dst.setClientDocument(doc2);
System.out.println(" cl1 set doc2");
}
}
else {
if (doc2 != null) {
manager.remove(doc2);
System.out.println(" remove doc2. cl1 has already doc1");
}
}
saveEntity(dst);
auditDst.check(dst);
target.add(persistAudit(auditDst));
AuditDoc<Client> auditSrc = new AuditDoc<Client>(src, getCollaborator());
removeEntity(src);
auditSrc.check(null);
target.add(persistAudit(auditSrc));
return target;
}
}