Package beans.report.register

Source Code of beans.report.register.RegisterBean

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans.report.register;

import beans.directory.lpu.entity.Lpu;
import beans.directory.simple.entities.Dvr;
import beans.user.client.entity.Client;
import framework.beans.SecuredBean;
import framework.beans.address.entities.AddressObject;
import framework.beans.client.clientDocument.ClientDocument;
import framework.beans.security.BeanRights;
import beans.contract.entity.Contract;
import beans.service.ServiceRender;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.ejb.Stateless;
import javax.persistence.Query;
import framework.generic.ClipsServerException;
import beans.UserRightsSet;
import beans.contract.entity.Polis;
import beans.contract.entity.ServicePrice;
import beans.directory.enterprise.Enterprise;
import beans.directory.simple.entities.CityDistrictOkato;
import beans.directory.simple.entities.DiagnosisEncounter;
import beans.directory.simple.entities.DiagnosisType;
import beans.directory.simple.entities.ServiceClass;
import beans.directory.simple.entities.SocialStatus;
import beans.doctor.diagnosis.Diagnosis;
import beans.user.client.ClientBean;
import beans.user.collaborator.entities.Collaborator;
import framework.beans.address.entities.Address;
import framework.beans.directory.simple.entities.ClientDocumentType;
import framework.generic.EDataIntegrity;
import framework.utils.Converter;
import framework.utils.DateTimeUtils;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

/**
*
* @author axe
*/
@Stateless(mappedName="clips-beans/RegisterBean")
public class RegisterBean extends SecuredBean
        implements RegisterBeanRemote {

    public static final String REGION_CODE = "61";
    public static final int TYPE = 1;

    public static final int COMMAND_READ = 0;

    @Override
    protected void initBeanRights() throws ClipsServerException {
        int[] r = new int[1];
        r[COMMAND_READ] = RightPresence(UserRightsSet.READ_REPORT_STRUCTURE.id);
        rights = new BeanRights(r);
    }
   


    @Override
    public List<RegisterData> getRegisterDataList(Date begin, Date end) throws ClipsServerException {
        System.out.println("Получение результатов выгрузки реестра...");
        //Мап по ОКАТО
        List<CityDistrictOkato> okatoList = findEntityList(CityDistrictOkato.class);
        //Мап <код окато, название района>
        HashMap<String, String> okatoMap = new HashMap<String, String>();
        for (CityDistrictOkato cdo : okatoList) {
            if (!cdo.getExtKey().isEmpty()) {
                okatoMap.put(cdo.getExtKey(), cdo.getTitle());
            }
        }

        checkCommandAccessibility(COMMAND_READ);
        begin = DateTimeUtils.getDateOnly(begin);
        end = DateTimeUtils.getDateOnly(end);
        if (end.before(begin)) {
            throw new ClipsServerException("Дата окончания выборки меньше даты начала");
        }
        Calendar cal = GregorianCalendar.getInstance();
        cal.setTime(end);
        cal.add(Calendar.DAY_OF_YEAR, 1);
        end = cal.getTime();
        Lpu lpu = findEntity(Collaborator.class, getCollaboratorId()).getLpu();
        //HashMap<String, Integer> priceMap = getPriceMap();

        String sqlSr = "SELECT sr FROM ServiceRender sr " +
                "WHERE sr.disease.closed IS NOT NULL " +
                "AND sr.disease.dateReg >= :begin " +
                "AND sr.disease.dateReg < :end " +
                "AND sr.polis.contract.type = :typeOMI " +
                "AND sr.service.serviceClass.id = :visit " +
                "AND sr.functions.collaborator.lpu.id = :lpuID"; //Клиника текущего сотрудника
        Query qSr = manager.createQuery(sqlSr);
        qSr.setParameter("begin", begin);
        qSr.setParameter("end", end);
        qSr.setParameter("typeOMI", Contract.TYPE_OMI);
        qSr.setParameter("visit", ServiceClass.SERVICE_CLASS_VISIT);
        qSr.setParameter("lpuID", lpu.getId());
        List<ServiceRender> resultList = qSr.getResultList(); //Все посещения

        //Подгрузка и маппирование мест работы
        HashMap<Integer, Enterprise> jobMap = createJobMap(begin, end);

        //Подгрузка и маппирование диагнозов
        //HashMap<Integer, DiagInfo> diagMap1 = createDiagMap1(resultList);
        HashMap<Integer, DiagInfo> diagMap = createDiagMap(begin, end);
        //equalsResult(diagMap1, diagMap);

        //Подгрузка и маппирование больничных
        HashMap<Integer, SickInfo> sickListMap = createSickListMap(begin, end);

        System.out.println("Получение результатов выгрузки реестра завершено");

        sortResult(resultList);
        List<RegisterData> target = new ArrayList<RegisterData>(resultList.size());
        for (ServiceRender sr : resultList) {
            RegisterData rd = new RegisterData();
            Client client = sr.getPolis().getClient();
            Address address = sr.getPolis().getAddress();
            if (address == null) {
                address = client.getAddress();
            }
            rd.id = sr.getId();
            rd.uuid = sr.getUuid();
            //rd.depart = sr.getFunctions().getReceptionType().getId();
            rd.history = sr.getDisease().getEmc().getNumber();
            if (rd.history == null) {
                rd.history = "";
            }
            rd.fam = client.getSurname() == null ? 0 : client.getSurname().getId();
            rd.nam = client.getName() == null ? 0 : client.getName().getId();
            rd.fnam = client.getPathronymic() == null ? 0 : client.getPathronymic().getId();
            rd.bday = client.getBorn();
            rd.sex = client.getSex().getId();
            rd.status = client.getSocialStatus() == null ? 0 : client.getSocialStatus().getId();
            Client representative = null;
            if (sr.getPolis().getNumber().equals(Polis.FICTIVE_POLIS_NUMBER)) {
                representative = client.getRepresentative();
            }

            ClientDocument doc;
            Polis polis;
            if (representative != null) {
                rd.p_status = client.getRepresentativeStatus().getId();
                rd.p_fam = representative.getSurname() == null ? 0 : representative.getSurname().getId();
                rd.p_nam = representative.getName() == null ? 0 : representative.getName().getId();
                rd.p_fnam = representative.getPathronymic() == null ? 0 : representative.getPathronymic().getId();
                rd.pred = 1;
                doc = representative.getClientDocument();
                polis = ClientBean.findPolisOMI(representative, manager);
            } else {
                rd.p_status = 0;
                rd.p_fam = 0;
                rd.p_nam = 0;
                rd.p_fnam = 0;
                rd.pred = 0;
                doc = client.getClientDocument();
                polis = sr.getPolis();
            }
            rd.pol_ser = polis.getSeries();
            rd.pol_num = polis.getNumber();
            if (rd.pol_num.equals(Polis.FICTIVE_POLIS_NUMBER)) {
                rd.pol_num = "";
                rd.pol_ser = "";
            }
            if (address != null) {
                AddressObject country = address.getAddressObject();
                while (country.getParent() != null) {
                    country = country.getParent();
                }
                rd.c_oksm = country.getKladrCode();
            } else {
                //Если указан российский пасспорт считаем что гражданство российское
                if (doc != null && doc.getDoctype().getId() == ClientDocumentType.TYPE_PASSPORT_RF) {
                    rd.c_oksm = "643";
                } else {
                    rd.c_oksm = "";
                }
            }
            rd.type_doc = doc != null ? doc.getDoctype().getId() : 0;
            rd.doc_ser = doc != null ? doc.getSeries() : "";
            rd.doc_num = doc != null ? doc.getNumber() : "";
            //Обрезание до 20 символов
            if (rd.doc_num.length() > 20) {
                rd.doc_num = rd.doc_num.substring(0, 20);
            }
           
            rd.ins_id_ar = polis.getRegionCode().getId();
            rd.id_ins_org = polis.getInsurer().getId();
            if (address != null) {
                rd.kladr = address.getAddressObject().getKladrCode();
//                rd.zip = address.getAddressObject().getPostIndex();
            } else {
                rd.kladr = "";
//                rd.zip = 0;
            }
            if (address != null) {
                //Субъект РФ
                AddressObject srf = address.getAddressObject();
                while (srf.getType().getLevel() != 1) {
                    srf = srf.getParent();
                }
                rd.area = srf.getId();
            } else {
                rd.area = 0;
            }
            /** REGION на уровне 5 находятся улицы - берем 4 уровень смотрим
             * если это не деревня, значит это город - берем его.
             * если это деревня, то она лежит в каком-то районе берем значит на 1 уровень выше*/
            if (address != null) {
                AddressObject reg = address.getAddressObject();
                while (reg.getType().getLevel() >= 5) {
                    reg = reg.getParent();
                }
                if (reg.getType().isVillage()) {
                    rd.region = reg.getParent().getTitle();
                    rd.type_item = reg.getParent().getType().getId();
                } else {
                    rd.region = reg.getTitle();
                    rd.type_item = reg.getType().getId();
                }
            } else {
                rd.region = "";
            }
            //Районы городов отсутствуют в кладре - надо прикрутить
            rd.reg_city = "";
            if (address != null) {
                AddressObject item = address.getAddressObject();
                if (item.getType().getLevel() == 5 || item.getType().getLevel() == 6) {
                    if (item.getOkato() > 0) {
                        //У объекта есть окато
                        String okato = fixOkato(item.getOkato());
                        if (okatoMap.containsKey(okato)) {
                            rd.reg_city = okatoMap.get(okato);
                        }
                    } else {
                        /*У объекта нет окато - смотрим у всех детей если первые восемь
                        цифр окато начинаются одинаково то берем окато детей */
                        List<AddressObject> children = findEntityList(AddressObject.class, "parent.id", item.getId());
                        boolean equals = true;
                        String okato = "";
                        for (AddressObject chield : children) {
                            if (chield.getOkato() > 0) {
                                if (okato.isEmpty()) {
                                    okato = fixOkato(chield.getOkato());
                                } else {
                                    if (!okato.equals(fixOkato(chield.getOkato()))) {
                                        equals = false;
                                    }
                                }
                            }
                        }
                        if (equals && !okato.isEmpty() && okatoMap.containsKey(okato)) {
                            rd.reg_city = okatoMap.get(okato);
                        }
                    }
                }
            }

            /** ITEM на уровне 5 находятся улицы - берем 4 уровень смотрим
             * если это деревня то этот итем и нужен
             */
            if (address != null) {
                AddressObject item = address.getAddressObject();
                while (item.getType().getLevel() >= 5) {
                    item = item.getParent();
                }
                if (item.getType().isVillage()) {
                    rd.item = item.getTitle();
                    rd.type_item = item.getType().getId();
                } else {
                    rd.item = "";
                }
            } else {
                rd.item = "";
                rd.type_item = 0;
            }

            /** STREET на последнем уровне может находиться не улица а квартал,
             * поэтому идем вверх до 5 уровня */
            AddressObject street = null;
            if (address != null) {
                street = address.getAddressObject();
                while (street.getType().getLevel() > 5) {
                    street = street.getParent();
                }
            }
            if (street != null && street.getType().getLevel() == 5) {
                rd.street = street.getTitle();
                Integer typeUl = street.getType().getTypeUl();
                rd.type_ul = typeUl == null ? 14 : typeUl;
            } else {
                rd.street = "";
                rd.type_ul = 0;
            }
            if (address!= null && address.getBuilding() != null && !address.getBuilding().trim().isEmpty()) {
                String building = address.getBuilding().trim();
                rd.house = Converter.getBuildingNumber(building);
                String corp = Converter.getBuildingCorpus(building);
                String letter = Converter.getBuildingLetter(building);
                if (!corp.isEmpty() && !letter.isEmpty() ) {
                    rd.liter = corp + "/" + letter;
                } else {
                    rd.liter = letter + corp;
                }
                rd.flat = address.getFlat();
            } else {
                rd.house = "";
                rd.liter = "";
                rd.flat = "";
            }

            Enterprise ent = jobMap.get(sr.getId());
            rd.work = ent == null ? "" : ent.getTitle();

            rd.date_begin = sr.getRenderedDate();

            rd.mes = sr.getFunctions().getReceptionType().getExtKey() + sr.getService().getCode();


            rd.out = sr.getDisease().getDiseaseResult().getId();
           
            DiagInfo diagInfo = diagMap.get(sr.getDisease().getId());
            if (diagInfo == null) {
                throw new EDataIntegrity("Не было обработано заболеваниe id = " + sr.getDisease().getId());
            }
            rd.mkb = diagInfo.diag;

            rd.mkb_s = "";
            for (String ref : diagInfo.referList) {
                rd.mkb_s = rd.mkb_s + ref + ", ";
            }
            if (!rd.mkb_s.isEmpty()) {
                rd.mkb_s = rd.mkb_s.substring(0, rd.mkb_s.length()-2);
            }

            rd.inn = client.getInn() == null ? "" : client.getInn();

            if (sr.getFunctions().getReceptionType().getExtKey().contains("29")) {
                //стоматологическое посещение
                rd.c_mu = 4;
                rd.k_mu = sr.getUet();
            } else {

                rd.c_mu = 1; //В соответствии с примечаниями к приказу
                rd.k_mu = 100; //В соответствии с примечаниями к приказу
            }

            /*
            float price = priceMap.get(rd.mes)/((float) 100);
            rd.tariff = String.format("%.2f", price).replace(',', '.');
            rd.sum = String.format("%.2f", price * rd.k_mu/100.0).replace(',', '.');
            rd.sumall = String.format("%.2f", price * rd.k_mu/100.0).replace(',', '.');
             */

            rd.ss = client.getSnils() == null ? "" : client.getSnils();
            rd.ssd = sr.getFunctions().getCollaborator().getClient().getSnils();
            if (rd.ssd == null) {
                rd.ssd = "";
            } else if (rd.ssd.equals(Client.EMPTY_SNILS)) {
                rd.ssd = "";
            }

            rd.vr_spec = sr.getFunctions().getReceptionType().getId();

            Dvr dvr = sr.getFunctions().getDvr();
            rd.vr_dol = dvr == null ? 0 : dvr.getId();

            rd.qz = diagInfo.diagEncID;

            rd.vmu = sr.getFunctions().getFirstMedicalAid().getId();

            //Даты больничного
            SickInfo sl = sickListMap.get(sr.getId());
            if (sl != null) {
                rd.d_listin = sl.dateOpen;
                if (sl.dateToWork != null) {
                    Calendar out = GregorianCalendar.getInstance();
                    out.setTime(sl.dateToWork);
                    out.add(Calendar.DAY_OF_YEAR, -1);
                    rd.d_listout = out.getTime();
                }
            }

            /*Инотерриториальный признак
             * В ТАЛе инотерриториальный признак ставится если ID_INS_AR != текущий регион
             * сделал также
             */
            if (!polis.getRegionCode().getExtKey().equals(REGION_CODE)) {
                rd.is_ext = 1;
            } else {
                rd.is_ext = 0;
            }

            //DF_CODES (коды источников дополнительного финансирования) в ТАЛ не заполняются
            rd.df_codes = "";

            /*
            SocialStatus socialStatus = client.getSocialStatus();
            int stId = socialStatus == null ? 0 : socialStatus.getId();
            if (stId == SocialStatus.STATUS_MILITARY || stId == SocialStatus.STATUS_WORKER) {
                rd.kateg = 1;
            } else {
                rd.kateg = 0;
            }
            */

            //COD_IF (код источника финансирования) в ТАЛ стоит 1
            rd.cod_if = 1;

            //RES_G (код результата диспансеризации в ТАЛ не проставлено)
            rd.resd = 0;

            //CODE_GOAL
            //по положению от 23.11.2009 не заполняется
            //rd.code_goal = sr.getDisease().getVisitingPurpose().getId();
            rd.code_goal = 0;

            rd.okved = ent == null ? "" : ent.getOkved();
            if (rd.okved == null) {
                rd.okved = "";
            }

            //DAT_N
            rd.dat_e = polis.getFromDate();
            //DAT_E
            rd.dat_n = polis.getTillDate();

            target.add(rd);
        }
        return target;
    }

    private void sortResult(List<ServiceRender> resultList) {
        System.out.println("Сортировка результатов выгрузки реестра...");
        Collections.sort(resultList, new Comparator<ServiceRender>() {

            @Override
            public int compare(ServiceRender sr1, ServiceRender sr2) {
                Client c1 = sr1.getPolis().getClient();
                Client c2 = sr2.getPolis().getClient();

                //по фамилии
                String fam1 = c1.getSurname() == null ? "" : c1.getSurname().getTitle();
                String fam2 = c2.getSurname() == null ? "" : c2.getSurname().getTitle();
                int r = fam1.compareTo(fam2);
                if (r != 0) return r;

                //по имени
                String nam1 = c1.getName() == null ? "" : c1.getName().getTitle();
                String nam2 = c2.getName() == null ? "" : c2.getName().getTitle();
                r = nam1.compareTo(nam2);
                if (r != 0) return r;

                //по отчеству
                String ot1 = c1.getPathronymic() == null ? "" : c1.getPathronymic().getTitle();
                String ot2 = c2.getPathronymic() == null ? "" : c2.getPathronymic().getTitle();
                r = ot1.compareTo(ot2);
                if (r != 0) return r;

                //По дате оказания
                return sr1.getRenderedDate().compareTo(sr2.getRenderedDate());
            }

        });
        System.out.println("Сортировка результатов выгрузки реестра завершена");
    }

    private HashMap<Integer, Enterprise> createJobMap(Date begin, Date end) {
        String sqlJob = "SELECT sr.id,  j.enterprise  FROM ServiceRender sr, Job j " +
                "WHERE  ((j.client.id = sr.polis.client.id) " +
                "AND sr.disease.closed IS NOT NULL " +
                "AND sr.disease.dateReg >= :begin " +
                "AND sr.disease.dateReg < :end " +
                "AND sr.polis.contract.type = :typeOMI " +
                "AND sr.service.serviceClass.id = :visit " +
                "AND (j.end IS NULL OR j.end >= :end)) ORDER BY sr.id, j.begin DESC";
        Query qJob = manager.createQuery(sqlJob);
        qJob.setParameter("begin", begin);
        qJob.setParameter("end", end);
        qJob.setParameter("typeOMI", Contract.TYPE_OMI);
        qJob.setParameter("visit", ServiceClass.SERVICE_CLASS_VISIT);
        List<Object[]> resultList = qJob.getResultList(); //Посещения пациентов имеющих работу и тайтл предприятия где работает пациент
        //Посещения пациентов имеющих работу и тайтл предприятия где работает пациент
        HashMap<Integer, Enterprise> target = new HashMap<Integer, Enterprise>();
        System.out.println("FULL SIZE = " + resultList.size());
        for (Iterator<Object[]> it = resultList.iterator(); it.hasNext();) {
            Object[] line = it.next();
            Integer srID = (Integer) line[0];
            if (!target.containsKey(srID)) {
                target.put(srID, (Enterprise) line[1]);
            }
        }
        System.out.println("COMPRESS SIZE = " + target.size());
        manager.clear();
    System.gc();
        return target;
    }




    private HashMap<Integer, DiagInfo> createDiagMap(Date begin, Date end) throws ClipsServerException {
        /* Замаппироваться должны все диагнозы ссылающиеся на заболевания, для всех
         * заболеваний, на которые есть ссылки из серренов, подходящих под
         */
        Lpu lpu = findEntity(Collaborator.class, getCollaboratorId()).getLpu();
        System.out.println("Запрос диагнозов...");
        String sql = "SELECT d.serviceRender.disease.id, " +
                "d.referenced, " +
                "d.type.id, " +
                "d.mkb10.code, " +
                "d.encounter, " +
                "d.id " +
                "from Diagnosis d " +
                "WHERE d.serviceRender.disease.id in (SELECT sr.disease.id FROM ServiceRender sr " +
                    "WHERE sr.disease.closed IS NOT NULL " +
                    "AND sr.disease.dateReg >= :begin " +
                    "AND sr.disease.dateReg < :end " +
                    "AND sr.polis.contract.type = :typeOMI " +
                    "AND sr.service.serviceClass.id = :visit " +
                    "AND sr.functions.collaborator.lpu.id = :lpuID) " + //Клиника текущего сотрудника
                "ORDER BY d.serviceRender.disease.id ASC, d.id DESC";
        Query q = manager.createQuery(sql);
        q.setParameter("begin", begin);
        q.setParameter("end", end);
        q.setParameter("typeOMI", Contract.TYPE_OMI);
        q.setParameter("visit", ServiceClass.SERVICE_CLASS_VISIT);
        q.setParameter("lpuID", lpu.getId());
        List<Object[]> resultList = q.getResultList();
        HashMap<Integer, DiagInfo> target = new HashMap<Integer, DiagInfo>();
        for (Object[] line : resultList) {
            Integer disID = (Integer) line[0];
            Diagnosis referced = (Diagnosis) line[1];
            Integer typeID = (Integer) line[2];
            String mkbCode = (String) line[3];
            mkbCode = fixMkbCode(mkbCode);
            DiagnosisEncounter encounter = (DiagnosisEncounter) line[4];
            DiagInfo diagInfo = target.get(disID);
            if (diagInfo == null) {
                diagInfo = new DiagInfo();
                target.put(disID, diagInfo);
            }
            if (referced != null) {
                //Сопутствующий
                diagInfo.referList.add(mkbCode);
            } else if (typeID == DiagnosisType.DIAGNOSIS_TYPE_FINAL) {
                //заключительный
                if (diagInfo.diag != null) {
                    throw new EDataIntegrity("Повторный заключительный диагноз в заболевании id = " + disID);
                }
                diagInfo.diag = mkbCode;
                diagInfo.diagEncID = encounter == null ? 0 : encounter.getId();
            }
           
        }
        System.out.println("Запрос диагнозов завершен + " + resultList.size());
        manager.clear();
    System.gc();
        return target;
    }


    private HashMap<Integer, DiagInfo> createDiagMap1 (List<ServiceRender> serrenList) throws EDataIntegrity {
        //Создание мапа по дисизам
        //HashMap<DiseaseID, DIAGINFO>
        HashMap<Integer, DiagInfo> target = new HashMap<Integer, DiagInfo>();
        for (int i = 0; i < serrenList.size(); i++) {
            int disID = serrenList.get(i).getDisease().getId();
            if (target.get(disID) == null) {
                target.put(disID, new DiagInfo());
            }
        }
        /* Замаппироваться должны все диагнозы ссылающиеся на заболевания, для всех
         * заболеваний, на которые есть ссылки из серренов
         */
        System.out.println("Запрос диагнозов...");
        String sql = "SELECT d.serviceRender.disease.id, d.type.id, d.mkb10.code, ref.id, d.encounter from Diagnosis d left outer join d.referenced as ref " +
                "ORDER BY d.serviceRender.disease.id";
        Query q = manager.createQuery(sql);
        List<Object[]> list = q.getResultList();
        for (Object[] line : list) {
            Integer disID = (Integer) line[0];
            Integer diagType = (Integer) line[1];
            String code = (String) line[2];
            Integer refID = (Integer) line[3];
            DiagnosisEncounter enc = (DiagnosisEncounter) line[4];
            Integer diagEncID = enc == null ? 0 : enc.getId();
            DiagInfo diagInfo = target.get(disID);
            if (diagInfo != null) {
                if (refID != null && refID != 0) {
                    //Сопутствующий
                    diagInfo.referList.add(code);
                } else if (diagType == DiagnosisType.DIAGNOSIS_TYPE_FINAL) {
                    //заключительный
                    if (diagInfo.diag != null) {
                        throw new EDataIntegrity("Повторный заключительный диагноз в заболевании id = " + disID);
                    }
                    diagInfo.diag = code;
                    diagInfo.diagEncID = diagEncID;
                }
            }
        }
        Set<Entry<Integer, DiagInfo>> entrySet = target.entrySet();
        for (Iterator<Entry<Integer, DiagInfo>> it = entrySet.iterator(); it.hasNext();) {
            Entry<Integer, DiagInfo> entry = it.next();
            if (entry.getValue().diag == null) {
                it.remove();
            }
        }
        System.out.println("Запрос диагнозов завершен");
        return target;
    }

    //Сравнение результатов маппирования по диагнозам полученных 2 способами
    private void equalsResult(HashMap<Integer, DiagInfo> diagMap1, HashMap<Integer, DiagInfo> diagMap) throws EDataIntegrity {
        if (diagMap.size() != diagMap1.size()) {
            Set<Integer> keySet = diagMap.keySet();
            for (Integer id : keySet) {
                diagMap1.remove(id);
            }
            throw new EDataIntegrity("Несовпадение количества результатов");
        }
        Set<Integer> keySet = diagMap.keySet();
        for (Integer id : keySet) {
            if (!diagMap.get(id).equals(diagMap1.get(id))) {
                throw new EDataIntegrity("Несовпадение результатов в заболевании id = " + id);
            }
        }
    }



    private HashMap<Integer, SickInfo> createSickListMap(Date begin, Date end) throws EDataIntegrity, ClipsServerException {
        /* Заммаппироваться должны все больничные по серренам подходящим для
         выгрузки
         */
        System.out.println("Запрос больничных...");
        Lpu lpu = findEntity(Collaborator.class, getCollaboratorId()).getLpu();
        String sql = "SELECT sl.serren.id, sl.sicklist.id, sl.sicklist.dateOpen, sl.sicklist.dateToWork  from SickLong sl " +
                "WHERE sl.serren.disease.closed IS NOT NULL " +
                "AND sl.serren.disease.dateReg >= :begin " +
                "AND sl.serren.disease.dateReg < :end " +
                "AND sl.serren.polis.contract.type = :typeOMI " +
                "AND sl.serren.service.serviceClass.id = :visit " +
                "AND sl.serren.functions.collaborator.lpu.id = :lpuID "; //Клиника текущего сотрудника
        Query q = manager.createQuery(sql);
        q.setParameter("begin", begin);
        q.setParameter("end", end);
        q.setParameter("typeOMI", Contract.TYPE_OMI);
        q.setParameter("visit", ServiceClass.SERVICE_CLASS_VISIT);
        q.setParameter("lpuID", lpu.getId());
        List<Object[]> resultList = q.getResultList();
        HashMap<Integer, SickInfo> target = new HashMap<Integer, SickInfo>();
        for (Object[] line : resultList) {
            Integer srID = (Integer) line[0];
            Integer id = (Integer) line[1];
            Date d1 = (Date) line[2];
            Date d2 = (Date) line[3];
            SickInfo sl = new SickInfo(id, d1, d2);
            SickInfo oldMapped = target.get(srID);
            if (oldMapped != null && oldMapped.id != sl.id) {
                throw new EDataIntegrity("На услугу id = " + srID + " ссылаются несколько разных больничных");
            }
            target.put(srID, sl);
        }
        System.out.println("Запрос больничных завершен");
        manager.clear();
    System.gc();
        return target;
    }


    private String fixOkato(long value) {
        String okato = Long.toString(value);
        while (okato.length() < 11) {
            okato = "0" + okato;
        }
        return okato.substring(0, 8);

    }

    private String fixMkbCode(String mkbCode) {
        mkbCode = mkbCode.replace("*", "");
        return mkbCode.replace("+", "");
    }

    /**
     * для нового реестра(23.11.2009) не нужно
     * @return
     * @throws ClipsServerException
     */
    private HashMap<String, Integer> getPriceMap() throws ClipsServerException {
        Query q = manager.createQuery("SELECT a FROM Contract a WHERE "
                + "a.type = :ctype "
                + "AND (a.begin <= :current) "
                + "AND ((a.end IS NULL) OR (a.end > :current))");
        q.setParameter("ctype", Contract.TYPE_OMI);
        q.setParameter("current", GregorianCalendar.getInstance().getTime());
        List list = q.getResultList();

        Contract contract;
        if (list.size() == 0) {
            throw new ClipsServerException("Не найдено ни одного действующего договора ОМС");
        } else if (list.size() > 1) {
            throw new ClipsServerException("Найдено " + list.size() + " полисов в действующем договоре ОМС");
        } else {
            contract = (Contract) list.get(0);
        }


        String sql = "SELECT a FROM ServicePrice a WHERE " +
                 "a.contract=:contract " +
                 "AND a.receptionType IS NOT NULL";
        q = manager.createQuery(sql);
        q.setParameter("contract", contract);
        List<ServicePrice> servicePriceList = q.getResultList();

        HashMap<String, Integer> target = new HashMap<String, Integer>();
        for (ServicePrice sp : servicePriceList) {
            String code = sp.getReceptionType().getExtKey() + sp.getService().getCode();
            target.put(code, sp.getPrice());
        }
        return target;
    }
}
TOP

Related Classes of beans.report.register.RegisterBean

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.