Package beans.followup

Source Code of beans.followup.FollowupBean

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package beans.followup;

import framework.beans.EntityDetails;
import framework.beans.FacadeBean;
import framework.beans.security.BeanRights;
import beans.followup.entity.Followup;
import beans.followup.entity.FollowupDetails;
import beans.followup.entity.FollowupEvent;
import beans.followup.entity.FollowupEventDetails;
import beans.directory.simple.entities.FollowDownReason;
import beans.directory.simple.entities.FollowupReason;
import beans.user.collaborator.entities.Collaborator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import framework.generic.ClipsServerException;
import framework.generic.EDataIntegrity;
import javax.ejb.EJBException;
import javax.ejb.Stateful;
import beans.UserRightsSet;
import beans.directory.simple.entities.DiagnosisType;
import beans.directory.simple.entities.VisitingPurpose;
import beans.doctor.diagnosis.Diagnosis;
import beans.doctor.diagnosis.DiagnosisDetails;
import beans.doctor.disease.Disease;
import beans.service.ServiceRender;
import framework.audit.AuditDoc;
import framework.beans.ModificationInfo;
import framework.generic.ESecurity;
import framework.security.UserRight;
import framework.utils.DateTimeUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import javax.persistence.Query;

/**
* Security - Ok.
* @author axe
*/
@Stateful(mappedName="clips-beans/FollowupBean")
public class FollowupBean extends FacadeBean<Followup>
        implements FollowupBeanRemote {

    public static final UserRight RIGHT_CREATION = UserRightsSet.WRITE_MEDICAL_DATA_DURING_DAY;

    public static int COMMAND_READ_FOLLOWUP_EVENT = 4;
    public static int COMMAND_WRITE_FOLLOWUP_EVENT = 5;
   
    public FollowupBean() {
        super(Followup.class);
    }

    @Override
    protected void initBeanRights() {
        int [] r = new int[6];
        r[COMMAND_READ] = RightPresence(UserRightsSet.READ_MEDICAL_DATA.id);
        int cmr = RightPresence(UserRightsSet.WRITE_MEDICAL_DATA_DURING_DAY.id);
        r[COMMAND_CREATE] = cmr;
        r[COMMAND_MODIFY] = cmr;
        r[COMMAND_REMOVE] = cmr;
       
        if (r[COMMAND_READ] > 0) {
            r[COMMAND_READ_FOLLOWUP_EVENT] = r[COMMAND_READ];
        } else {
            r[COMMAND_READ_FOLLOWUP_EVENT] = RightPresence(UserRightsSet.READ_FOLLOWUP_EVENT.id);
        }
        if (r[COMMAND_MODIFY] > 0) {
            r[COMMAND_WRITE_FOLLOWUP_EVENT] = r[COMMAND_MODIFY];
        } else {
            r[COMMAND_WRITE_FOLLOWUP_EVENT] = RightPresence(UserRightsSet.WRITE_FOLLOWUP_EVENT.id);
        }
        rights = new BeanRights(r);
    }
   
    /**
     * Обновляет данные сущности.
     * @param details новые детали сущности
     * @throws EJBException в случае если обновление отвергнуто системой
     *          безопастности либо произошла ошибка
     * @return идентификатор сущности
     */
    @Override
    protected void onUpdate(Followup entity, EntityDetails details,
            AuditDoc auditDoc, List<AuditDoc> auditDocList)
            throws ClipsServerException {
        FollowupDetails d = (FollowupDetails) details;
        ServiceRender serviceRender = findEntity(ServiceRender.class, d.serrenUpID);
        Diagnosis diagnosis = findEntity(Diagnosis.class, d.diagnosisUpID);
        if (diagnosis.getServiceRender().getDisease().getId() != serviceRender.getDisease().getId()){
            throw new EDataIntegrity("Услуга, по которой пациент поставлен на учёт, " +
                    "и услуга, в рамках которой поставлен диагноз, должны находиться в одном заболевании");
        }
       
        entity.setDateup(d.dateUp);
        entity.setDatedown(d.dateDown);
        entity.setCollaboratorUp(findEntity(Collaborator.class, d.collaboratorUpID));
        entity.setCollaboratorDown(d.collaboratorDownID == 0 ? null : findEntity(Collaborator.class, d.collaboratorDownID));
        entity.setUpReason(findEntity(FollowupReason.class, d.reasonUp));
        entity.setDownReason(d.reasonDown == 0 ? null : findEntity(FollowDownReason.class, d.reasonDown));
        entity.setValue(d.value);
        entity.setDiagnosisUp(diagnosis);
        entity.setSerrenUp(serviceRender);
        entity.setSerrenDown(d.serrenDownID == 0 ? null : findEntity(ServiceRender.class, d.serrenDownID));
    }

   /**
     * Возвращает список евентов
     * @return список услуг договора
     */
    @Override
    public Map<FollowupEventDetails, Integer> getEventList() throws ClipsServerException {
        checkCommandAccessibility(COMMAND_READ_FOLLOWUP_EVENT);
        Followup entity = getExistentEntity();
        List<FollowupEvent> list = findEntityList(FollowupEvent.class, "follup", entity, " ORDER BY a.date");
        Map<FollowupEventDetails, Integer> res = new HashMap<FollowupEventDetails, Integer>();
        Iterator<FollowupEvent> i = list.iterator();

        HashSet<Integer> disIds = new HashSet<Integer>();
        for (FollowupEvent fed : list) {
            if (fed.getDisease() != null){
                disIds.add(fed.getDisease().getId());
            }
        }
        List<Diagnosis> diagList = findEntityList(Diagnosis.class, new Field[]{new Field("serviceRender.disease.id", disIds, Field.OPERATOR_IN), new Field("type.id", DiagnosisType.DIAGNOSIS_TYPE_FINAL), new Field("referenced", null, Field.OPERATOR_IS_NULL)});


//        String sql = "SELECT d.serviceRender.disease.id, d FROM Diagnosis d WHERE d.serviceRender.disease.id IN :disIDs AND d.type.id=:diagfinal AND d.referenced IS NULL";
//        Query q = manager.createQuery(sql);
//        q.setParameter("disIDs", disIds);
//        q.setParameter("diagfinal", DiagnosisType.DIAGNOSIS_TYPE_FINAL);
//        List resultList = q.getResultList();
        Map<Integer, Diagnosis> m = new HashMap<Integer, Diagnosis>();
//        for (Object object : resultList) {
//            Object[] arr = (Object[]) object;
//            m.put((Integer)arr[0], (Diagnosis)arr[2]);
//        }
        for (Diagnosis diagnosis : diagList) {
            m.put(diagnosis.getServiceRender().getDisease().getId(), diagnosis);
        }


        for (FollowupEvent followupEvent : list) {
            if (followupEvent.getDisease() != null){
                Diagnosis d = m.get(followupEvent.getDisease().getId());
                res.put(followupEvent.getDetails(this), d != null ? d.getMkb10().getId() : null);
            }else{
                res.put(followupEvent.getDetails(this), null);
            }
        }
        return res;
    }

     /**
     * Добавляет или обновляет эвент. Если details.id = 0 сущность создается,
     * иначе обновляется существующая с заданным идентификатором.
     * @param details данные
     * @return идентификатор сущности
     * @throws EJBException в случае если обновление отвергнуто системой
     *          безопастности либо произошла ошибка     *
     */
    @Override
    public ModificationInfo setEvent(FollowupEventDetails details) throws ClipsServerException {
        checkCommandAccessibility(COMMAND_WRITE_FOLLOWUP_EVENT);
        Followup entity = getExistentEntity();
       
        FollowupEvent event = null;
        if (details.date.before(DateTimeUtils.getDateOnly()) && !isSuperUser() && !hasRight(UserRightsSet.WRITE_STATISTIC_MEDICAL_DATA)) {
            throw new ESecurity("Недостаточно прав для записи о приеме по ДУ задним числом");
        }
        AuditDoc<FollowupEvent> auditFEvent;
        if(details.id != 0) {
            event = findEntity(FollowupEvent.class, details.id);
            checkTheSame(event.getFollup());
            auditFEvent = new AuditDoc<FollowupEvent>(event, getCollaborator());
        } else {
            event = new FollowupEvent();
            auditFEvent = new AuditDoc<FollowupEvent>(event, getCollaborator());
            event.setFollup(entity);
        }
        event.setDate(details.date);
        event.setCancelled(details.cancelled);
        event.setCalled(details.called);
        int id = saveEntity(event);
        auditFEvent.check(event);
        return new ModificationInfo(id, persistAudit(auditFEvent));
    }
   
    @Override
    protected void onRemove(Followup entity, List<AuditDoc> auditDocList) throws ClipsServerException {
        Field[] fields = new Field[]{
            new Field("follup", entity, Field.OPERATOR_EQUAL),
        };
        List<FollowupEvent> events = findEntityList(FollowupEvent.class, fields);
        for (FollowupEvent event : events) {
            AuditDoc<FollowupEvent> auditFEvent = new AuditDoc<FollowupEvent>(event, getCollaborator());
            auditDocList.add(auditFEvent);
            if (event.getDisease() != null) {
                throw new EDataIntegrity("Невозможно удалить запись о диспансерном наблюдении, в котором есть отмеченные посещения");
            }
            else {
                removeEntity(event);
                auditFEvent.check(null);
            }
        }

    }

    /**
     * @return Список диагнозов, назначенных в пределах данного диспансерного наблюдения
     * @throws framework.generic.ClipsServerException
     */
    @Override
    public List<DiagnosisDetails> getDiagnosisIn() throws ClipsServerException {
        checkCommandAccessibility(COMMAND_READ_FOLLOWUP_EVENT);
        int follupid = getExistentEntity().getId();

        List<DiagnosisDetails> res = new ArrayList<DiagnosisDetails>();

        String query = "SELECT d FROM Diagnosis d, FollowupEvent fe " +
                       "WHERE d.referenced IS NULL AND d.serviceRender.disease.id=fe.disease.id AND fe.follup.id=:follupid " +
                       "ORDER BY d.date";
        Query q = manager.createQuery(query);
        q.setParameter("follupid", follupid);
        List list = q.getResultList();
        for (int i = 0; i < list.size(); i++) {
            Diagnosis diag = (Diagnosis) list.get(i);
            res.add(diag.getDetails(this));
        }
        return res;
    }
   
    /**
     * Удаляет эвент.
     * @param id идентификатор члена
     * @throws EJBException в случае если обновление отвергнуто системой
     *          безопастности либо произошла ошибка     *
     */
    @Override
    public ModificationInfo removeEvent(int id) throws ClipsServerException {
        checkCommandAccessibility(COMMAND_WRITE_FOLLOWUP_EVENT);
        checkEntityExist();
       
        FollowupEvent event = findEntity(FollowupEvent.class, id);
        checkTheSame(event.getFollup());
        AuditDoc<FollowupEvent> auditFevent = new AuditDoc<FollowupEvent>(event, getCollaborator());
        manager.remove(event);
        auditFevent.check(null);
        return new ModificationInfo(0, persistAudit(auditFevent));
    }

    /**
     * Создаёт заболевание для прихода по диспансерному учету
     * @param details - евент, для которого будет создан заболевание
     * @return айдишнег заболевания
     */
    @Override
    public ModDisease createDisease(FollowupEventDetails detailsthrows ClipsServerException {
        checkCommandAccessibility(COMMAND_WRITE_FOLLOWUP_EVENT);
        checkEntityExist();
        if (details.id == 0) {
            throw new ClipsServerException("Необходимо сохранить приём");
        }
        ArrayList<AuditDoc> auditDoclList = new ArrayList<AuditDoc>();

        FollowupEvent event = findEntity(FollowupEvent.class, details.id);
        checkTheSame(event.getFollup());
        AuditDoc<FollowupEvent> auditFevent = new AuditDoc<FollowupEvent>(event, getCollaborator());
        auditDoclList.add(auditFevent);
        Disease disease = new Disease();//сделаем заболевание
        AuditDoc<Disease> auditDisease = new AuditDoc<Disease>(disease, getCollaborator());
        auditDoclList.add(auditDisease);
        Date current = new Date();
        disease.setCreated(current);//дата по первому созданию
        disease.setVisitingPurpose(findEntity(VisitingPurpose.class, VisitingPurpose.VP_FOLLOWUP));
        disease.setDateReg(details.date);
        disease.setEmc(getExistentEntity().getSerrenUp().getDisease().getEmc());
        disease.setCollaborator(findEntity(Collaborator.class, getCollaboratorId()));
        event.setDisease(disease);
        manager.persist(disease);
        manager.merge(event);
        manager.flush();
        manager.refresh(disease);
        manager.refresh(event);
        auditFevent.check(event);
        auditDisease.check(disease);
        return new ModDisease(persistAudit(auditDoclList), disease.getDetails(this));
    }
}
TOP

Related Classes of beans.followup.FollowupBean

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.