Search in sources :

Example 6 with FormDiscrepancyNotes

use of org.akaza.openclinica.control.form.FormDiscrepancyNotes in project OpenClinica by OpenClinica.

the class ListStudySubjectsServlet method createTable.

private void createTable() {
    ListStudySubjectTableFactory factory = new ListStudySubjectTableFactory(showMoreLink);
    factory.setStudyEventDefinitionDao(getStudyEventDefinitionDao());
    factory.setSubjectDAO(getSubjectDAO());
    factory.setStudySubjectDAO(getStudySubjectDAO());
    factory.setStudyEventDAO(getStudyEventDAO());
    factory.setStudyBean(currentStudy);
    factory.setStudyGroupClassDAO(getStudyGroupClassDAO());
    factory.setSubjectGroupMapDAO(getSubjectGroupMapDAO());
    factory.setStudyDAO(getStudyDAO());
    factory.setCurrentRole(currentRole);
    factory.setCurrentUser(ub);
    factory.setEventCRFDAO(getEventCRFDAO());
    factory.setEventDefintionCRFDAO(getEventDefinitionCRFDAO());
    factory.setStudyGroupDAO(getStudyGroupDAO());
    factory.setStudyParameterValueDAO(getStudyParameterValueDAO());
    String findSubjectsHtml = factory.createTable(request, response).render();
    request.setAttribute("findSubjectsHtml", findSubjectsHtml);
    // A. Hamid.
    // For event definitions and group class list in the add subject popup
    request.setAttribute("allDefsArray", super.getEventDefinitionsByCurrentStudy());
    request.setAttribute("studyGroupClasses", super.getStudyGroupClassesByCurrentStudy());
    FormDiscrepancyNotes discNotes = new FormDiscrepancyNotes();
    session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes);
    forwardPage(Page.LIST_STUDY_SUBJECTS);
}
Also used : FormDiscrepancyNotes(org.akaza.openclinica.control.form.FormDiscrepancyNotes)

Example 7 with FormDiscrepancyNotes

use of org.akaza.openclinica.control.form.FormDiscrepancyNotes in project OpenClinica by OpenClinica.

the class ViewDiscrepancyNoteServlet method processRequest.

@Override
@SuppressWarnings("unchecked")
protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    int eventCRFId = fp.getInt(CreateDiscrepancyNoteServlet.EVENT_CRF_ID);
    request.setAttribute(CreateDiscrepancyNoteServlet.EVENT_CRF_ID, new Integer(eventCRFId));
    request.setAttribute(DIS_TYPES, DiscrepancyNoteType.list);
    if (currentRole.getRole().equals(Role.RESEARCHASSISTANT) || currentRole.getRole().equals(Role.RESEARCHASSISTANT2) || currentRole.getRole().equals(Role.INVESTIGATOR)) {
        ArrayList<ResolutionStatus> resStatuses = new ArrayList();
        resStatuses.add(ResolutionStatus.UPDATED);
        resStatuses.add(ResolutionStatus.RESOLVED);
        request.setAttribute(RES_STATUSES, resStatuses);
        // it's for parentDNId is null or 0
        request.setAttribute(WHICH_RES_STATUSES, "22");
        ArrayList<ResolutionStatus> resStatuses2 = new ArrayList<ResolutionStatus>();
        resStatuses2.add(ResolutionStatus.OPEN);
        resStatuses2.add(ResolutionStatus.RESOLVED);
        request.setAttribute(RES_STATUSES2, resStatuses2);
        List<DiscrepancyNoteType> types2 = new ArrayList<DiscrepancyNoteType>(DiscrepancyNoteType.list);
        types2.remove(DiscrepancyNoteType.QUERY);
        request.setAttribute(DIS_TYPES2, types2);
    } else if (currentRole.getRole().equals(Role.MONITOR)) {
        ArrayList<ResolutionStatus> resStatuses = new ArrayList();
        resStatuses.add(ResolutionStatus.OPEN);
        resStatuses.add(ResolutionStatus.UPDATED);
        resStatuses.add(ResolutionStatus.CLOSED);
        request.setAttribute(RES_STATUSES, resStatuses);
        request.setAttribute(WHICH_RES_STATUSES, "1");
        ArrayList<DiscrepancyNoteType> types2 = new ArrayList<DiscrepancyNoteType>();
        types2.add(DiscrepancyNoteType.QUERY);
        request.setAttribute(DIS_TYPES2, types2);
    } else {
        // Role.STUDYDIRECTOR Role.COORDINATOR
        List<ResolutionStatus> resStatuses = new ArrayList<ResolutionStatus>(ResolutionStatus.list);
        resStatuses.remove(ResolutionStatus.NOT_APPLICABLE);
        request.setAttribute(RES_STATUSES, resStatuses);
        ;
        // it's for parentDNId is null or 0 and FVC
        request.setAttribute(WHICH_RES_STATUSES, "2");
        ArrayList<ResolutionStatus> resStatuses2 = new ArrayList<ResolutionStatus>();
        resStatuses2.add(ResolutionStatus.OPEN);
        resStatuses2.add(ResolutionStatus.RESOLVED);
        request.setAttribute(RES_STATUSES2, resStatuses2);
    }
    // logic from CreateDiscrepancyNoteServlet
    request.setAttribute("unlock", "0");
    fp.getBoolean(IS_REASON_FOR_CHANGE);
    fp.getBoolean(ERROR_FLAG);
    String monitor = fp.getString("monitor");
    // } else if ("1".equalsIgnoreCase(monitor)) {// change to allow user to
    if ("1".equalsIgnoreCase(monitor)) {
        // change to allow user to
        // enter note for all items,
        // not just blank items
        request.setAttribute(CAN_MONITOR, "1");
        request.setAttribute("monitor", monitor);
    } else {
        request.setAttribute(CAN_MONITOR, "0");
    }
    Boolean fromBox = fp.getBoolean(FROM_BOX);
    if (fromBox == null || !fromBox) {
        session.removeAttribute(BOX_TO_SHOW);
        session.removeAttribute(BOX_DN_MAP);
        session.removeAttribute(AUTOVIEWS);
    }
    Boolean refresh = fp.getBoolean("refresh");
    request.setAttribute("refresh", refresh + "");
    String ypos = fp.getString("y");
    if (ypos == null || ypos.length() == 0) {
        ypos = "0";
    }
    request.setAttribute("y", ypos);
    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
    int entityId = fp.getInt(ENTITY_ID, true);
    String name = fp.getString(ENTITY_TYPE, true);
    String column = fp.getString(ENTITY_COLUMN, true);
    String field = fp.getString(ENTITY_FIELD, true);
    String isLocked = fp.getString(LOCKED_FLAG);
    if (!StringUtil.isBlank(isLocked) && "yes".equalsIgnoreCase(isLocked)) {
        request.setAttribute(LOCKED_FLAG, "yes");
    } else {
        request.setAttribute(LOCKED_FLAG, "no");
    }
    DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
    int subjectId = fp.getInt(CreateDiscrepancyNoteServlet.SUBJECT_ID, true);
    int itemId = fp.getInt(CreateDiscrepancyNoteServlet.ITEM_ID, true);
    StudySubjectBean ssub = new StudySubjectBean();
    if (subjectId > 0) {
        StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
        ssub = (StudySubjectBean) ssdao.findByPK(subjectId);
        request.setAttribute("noteSubject", ssub);
    }
    ItemBean item = new ItemBean();
    if (itemId > 0) {
        ItemDAO idao = new ItemDAO(sm.getDataSource());
        item = (ItemBean) idao.findByPK(itemId);
        request.setAttribute("item", item);
        request.setAttribute("entityName", item.getName());
    }
    ItemDataBean itemData = new ItemDataBean();
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
    int preUserId = 0;
    if (!StringUtil.isBlank(name)) {
        if ("itemData".equalsIgnoreCase(name)) {
            ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
            itemData = (ItemDataBean) iddao.findByPK(entityId);
            request.setAttribute("entityValue", itemData.getValue());
            request.setAttribute("entityName", item.getName());
            EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());
            EventCRFBean ec = (EventCRFBean) ecdao.findByPK(itemData.getEventCRFId());
            preUserId = ec.getOwnerId() > 0 ? ec.getOwnerId() : 0;
            request.setAttribute("entityCreatedDate", sdf.format(ec.getCreatedDate()));
            StudyEventDAO sed = new StudyEventDAO(sm.getDataSource());
            StudyEventBean se = (StudyEventBean) sed.findByPK(ec.getStudyEventId());
            StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource());
            StudyEventDefinitionBean sedb = (StudyEventDefinitionBean) seddao.findByPK(se.getStudyEventDefinitionId());
            se.setName(sedb.getName());
            request.setAttribute("studyEvent", se);
            CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
            CRFVersionBean cv = (CRFVersionBean) cvdao.findByPK(ec.getCRFVersionId());
            CRFDAO cdao = new CRFDAO(sm.getDataSource());
            CRFBean crf = (CRFBean) cdao.findByPK(cv.getCrfId());
            request.setAttribute("crf", crf);
        } else if ("studySub".equalsIgnoreCase(name)) {
            StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
            ssub = (StudySubjectBean) ssdao.findByPK(entityId);
            SubjectDAO sdao = new SubjectDAO(sm.getDataSource());
            SubjectBean sub = (SubjectBean) sdao.findByPK(ssub.getSubjectId());
            request.setAttribute("noteSubject", ssub);
            if (!StringUtil.isBlank(column)) {
                if ("enrollment_date".equalsIgnoreCase(column)) {
                    if (ssub.getEnrollmentDate() != null) {
                        request.setAttribute("entityValue", dateFormatter.format(ssub.getEnrollmentDate()));
                    }
                    request.setAttribute("entityName", resword.getString("enrollment_date"));
                } else if ("gender".equalsIgnoreCase(column)) {
                    request.setAttribute("entityValue", sub.getGender() + "");
                    request.setAttribute("entityName", resword.getString("gender"));
                } else if ("date_of_birth".equalsIgnoreCase(column)) {
                    if (sub.getDateOfBirth() != null) {
                        request.setAttribute("entityValue", dateFormatter.format(sub.getDateOfBirth()));
                    }
                    request.setAttribute("entityName", resword.getString("date_of_birth"));
                } else if ("unique_identifier".equalsIgnoreCase(column)) {
                    if (sub.getUniqueIdentifier() != null) {
                        request.setAttribute("entityValue", sub.getUniqueIdentifier());
                    }
                    request.setAttribute("entityName", resword.getString("unique_identifier"));
                }
            }
            preUserId = ssub.getOwnerId() > 0 ? ssub.getOwnerId() : 0;
            request.setAttribute("entityCreatedDate", sdf.format(ssub.getCreatedDate()));
        } else if ("subject".equalsIgnoreCase(name)) {
            SubjectDAO sdao = new SubjectDAO(sm.getDataSource());
            SubjectBean sub = (SubjectBean) sdao.findByPK(entityId);
            // be caution: here for subject, noteSubject is SubjectBean and
            // label is unique_identifier
            sub.setLabel(sub.getUniqueIdentifier());
            request.setAttribute("noteSubject", sub);
            if (!StringUtil.isBlank(column)) {
                if ("gender".equalsIgnoreCase(column)) {
                    request.setAttribute("entityValue", ssub.getGender() + "");
                    request.setAttribute("entityName", resword.getString("gender"));
                } else if ("date_of_birth".equalsIgnoreCase(column)) {
                    if (sub.getDateOfBirth() != null) {
                        request.setAttribute("entityValue", dateFormatter.format(sub.getDateOfBirth()));
                    }
                    request.setAttribute("entityName", resword.getString("date_of_birth"));
                } else if ("unique_identifier".equalsIgnoreCase(column)) {
                    request.setAttribute("entityValue", sub.getUniqueIdentifier());
                    request.setAttribute("entityName", resword.getString("unique_identifier"));
                }
            }
            preUserId = sub.getOwnerId() > 0 ? sub.getOwnerId() : 0;
            request.setAttribute("entityCreatedDate", sdf.format(sub.getCreatedDate()));
        } else if ("studyEvent".equalsIgnoreCase(name)) {
            StudyEventDAO sed = new StudyEventDAO(sm.getDataSource());
            StudyEventBean se = (StudyEventBean) sed.findByPK(entityId);
            StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource());
            StudyEventDefinitionBean sedb = (StudyEventDefinitionBean) seddao.findByPK(se.getStudyEventDefinitionId());
            se.setName(sedb.getName());
            request.setAttribute("studyEvent", se);
            request.setAttribute("noteSubject", new StudySubjectDAO(sm.getDataSource()).findByPK(se.getStudySubjectId()));
            if (!StringUtil.isBlank(column)) {
                if ("location".equalsIgnoreCase(column)) {
                    request.setAttribute("entityValue", se.getLocation());
                    request.setAttribute("entityName", resword.getString("location"));
                } else if ("start_date".equalsIgnoreCase(column)) {
                    if (se.getDateStarted() != null) {
                        request.setAttribute("entityValue", dateFormatter.format(se.getDateStarted()));
                    }
                    request.setAttribute("entityName", resword.getString("start_date"));
                } else if ("end_date".equalsIgnoreCase(column)) {
                    if (se.getDateEnded() != null) {
                        request.setAttribute("entityValue", dateFormatter.format(se.getDateEnded()));
                    }
                    request.setAttribute("entityName", resword.getString("end_date"));
                }
            }
            preUserId = se.getOwnerId() > 0 ? se.getOwnerId() : 0;
            request.setAttribute("entityCreatedDate", sdf.format(se.getCreatedDate()));
        } else if ("eventCrf".equalsIgnoreCase(name)) {
            EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());
            EventCRFBean ec = (EventCRFBean) ecdao.findByPK(entityId);
            if (!StringUtil.isBlank(column)) {
                if ("date_interviewed".equals(column)) {
                    if (ec.getDateInterviewed() != null) {
                        request.setAttribute("entityValue", dateFormatter.format(ec.getDateInterviewed()));
                    }
                    request.setAttribute("entityName", resword.getString("date_interviewed"));
                } else if ("interviewer_name".equals(column)) {
                    request.setAttribute("entityValue", ec.getInterviewerName());
                    request.setAttribute("entityName", resword.getString("interviewer_name"));
                }
            }
            setupStudyEventCRFAttributes(ec);
            preUserId = ec.getOwnerId() > 0 ? ec.getOwnerId() : 0;
            request.setAttribute("entityCreatedDate", sdf.format(ec.getCreatedDate()));
        }
    }
    boolean writeToDB = fp.getBoolean(CreateDiscrepancyNoteServlet.WRITE_TO_DB, true);
    HashMap<Integer, Integer> autoviews = (HashMap<Integer, Integer>) session.getAttribute(AUTOVIEWS);
    autoviews = autoviews == null ? new HashMap<Integer, Integer>() : autoviews;
    HashMap<Integer, DiscrepancyNoteBean> boxDNMap = (HashMap<Integer, DiscrepancyNoteBean>) session.getAttribute(BOX_DN_MAP);
    if (boxDNMap == null || !boxDNMap.containsKey(0)) {
        boxDNMap = new HashMap<Integer, DiscrepancyNoteBean>();
        // initialize dn for a new thread
        DiscrepancyNoteBean dnb = new DiscrepancyNoteBean();
        if (currentRole.getRole().equals(Role.RESEARCHASSISTANT) || currentRole.getRole().equals(Role.RESEARCHASSISTANT2) || currentRole.getRole().equals(Role.INVESTIGATOR)) {
            dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.ANNOTATION.getId());
            dnb.setResolutionStatusId(ResolutionStatus.NOT_APPLICABLE.getId());
            autoviews.put(0, 0);
        // request.setAttribute("autoView", "0");
        } else {
            dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.QUERY.getId());
            dnb.setAssignedUserId(preUserId);
            autoviews.put(0, 1);
        // request.setAttribute("autoView", "1");
        }
        boxDNMap.put(0, dnb);
    } else if (boxDNMap.containsKey(0)) {
        int dnTypeId = boxDNMap.get(0).getDiscrepancyNoteTypeId();
        autoviews.put(0, dnTypeId == 3 ? 1 : 0);
    }
    if (boxDNMap.containsKey(0)) {
        int dnTypeId0 = boxDNMap.get(0).getDiscrepancyNoteTypeId();
        if (dnTypeId0 == 2 || dnTypeId0 == 4) {
            request.setAttribute("typeID0", dnTypeId0 + "");
        }
    }
    // request.setAttribute("enterData", enterData);
    request.setAttribute("monitor", monitor);
    request.setAttribute(ENTITY_ID, entityId + "");
    request.setAttribute(ENTITY_TYPE, name);
    request.setAttribute(ENTITY_FIELD, field);
    request.setAttribute(ENTITY_COLUMN, column);
    request.setAttribute(CreateDiscrepancyNoteServlet.WRITE_TO_DB, writeToDB ? "1" : "0");
    ArrayList notes = (ArrayList) dndao.findAllByEntityAndColumn(name, entityId, column);
    if (notes.size() > 0) {
        notes.get(0);
        // @pgawade 21-May-2011 Corrected the condition to throw no access
        // error
        StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
        int parentStudyForNoteSub = 0;
        // @pgawade #9801: 07-June-2011 corrected the way to get study
        // subject id associated with discrepancy note
        // int noteSubId = note.getOwnerId();
        StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
        // StudySubjectBean notessub = (StudySubjectBean)
        // ssdao.findByPK(noteSubId);
        StudySubjectBean notessub = (StudySubjectBean) ssdao.findByPK(subjectId);
        StudyBean studyBeanSub = (StudyBean) studyDAO.findByPK(notessub.getStudyId());
        if (null != studyBeanSub) {
            parentStudyForNoteSub = studyBeanSub.getParentStudyId();
        }
        if (notessub.getStudyId() != currentStudy.getId() && currentStudy.getId() != parentStudyForNoteSub) {
            addPageMessage(noAccessMessage);
            throw new InsufficientPermissionException(Page.MENU_SERVLET, exceptionName, "1");
        }
    }
    FormDiscrepancyNotes newNotes = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
    Map<Integer, DiscrepancyNoteBean> noteTree = new LinkedHashMap<Integer, DiscrepancyNoteBean>();
    String session_key = eventCRFId + "_" + field;
    ArrayList newFieldNotes = null;
    if (newNotes != null && (!newNotes.getNotes(field).isEmpty() || !newNotes.getNotes(session_key).isEmpty())) {
        newFieldNotes = newNotes.getNotes(field);
        if (newFieldNotes == null || newFieldNotes.size() == 0) {
            newFieldNotes = newNotes.getNotes(session_key);
        }
        // System.out.println("how many notes:" + newFieldNotes.size());
        for (int i = 0; i < newFieldNotes.size(); i++) {
            DiscrepancyNoteBean note = (DiscrepancyNoteBean) newFieldNotes.get(i);
            note.setLastUpdator(ub);
            note.setLastDateUpdated(new Date());
            note.setDisType(DiscrepancyNoteType.get(note.getDiscrepancyNoteTypeId()));
            note.setResStatus(ResolutionStatus.get(note.getResolutionStatusId()));
            note.setSaved(false);
            if (itemId > 0) {
                note.setEntityName(item.getName());
                note.setEntityValue(itemData.getValue());
            }
            note.setSubjectName(ssub.getName());
            note.setEntityType(name);
            int pId = note.getParentDnId();
            if (pId == 0) {
                // we can only keep one unsaved note because
                // note.id == 0
                noteTree.put(note.getId(), note);
            }
        }
        for (int i = 0; i < newFieldNotes.size(); i++) {
            DiscrepancyNoteBean note = (DiscrepancyNoteBean) newFieldNotes.get(i);
            int pId = note.getParentDnId();
            if (pId > 0) {
                note.setSaved(false);
                note.setLastUpdator(ub);
                note.setLastDateUpdated(new Date());
                note.setEntityName(item.getName());
                note.setSubjectName(ssub.getName());
                note.setEntityType(name);
                note.setDisType(DiscrepancyNoteType.get(note.getDiscrepancyNoteTypeId()));
                note.setResStatus(ResolutionStatus.get(note.getResolutionStatusId()));
                DiscrepancyNoteBean parent = noteTree.get(new Integer(pId));
                if (parent != null) {
                    parent.getChildren().add(note);
                }
            }
        }
    }
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    HashMap<Integer, String> fvcInitAssigns = new HashMap<Integer, String>();
    for (int i = 0; i < notes.size(); i++) {
        DiscrepancyNoteBean note = (DiscrepancyNoteBean) notes.get(i);
        note.setColumn(column);
        note.setEntityId(entityId);
        note.setEntityType(name);
        note.setField(field);
        Date lastUpdatedDate = note.getCreatedDate();
        UserAccountBean lastUpdator = (UserAccountBean) udao.findByPK(note.getOwnerId());
        note.setLastUpdator(lastUpdator);
        note.setLastDateUpdated(lastUpdatedDate);
        int pId = note.getParentDnId();
        note.setDisType(DiscrepancyNoteType.get(note.getDiscrepancyNoteTypeId()));
        note.setResStatus(ResolutionStatus.get(note.getResolutionStatusId()));
        if (pId == 0) {
            noteTree.put(new Integer(note.getId()), note);
        }
    }
    for (int i = 0; i < notes.size(); i++) {
        DiscrepancyNoteBean note = (DiscrepancyNoteBean) notes.get(i);
        int pId = note.getParentDnId();
        if (itemId > 0) {
            note.setEntityName(item.getName());
            note.setEntityValue(itemData.getValue());
        }
        note.setSubjectName(ssub.getName());
        note.setEntityType(name);
        Date lastUpdatedDate = note.getCreatedDate();
        UserAccountBean lastUpdator = (UserAccountBean) udao.findByPK(note.getOwnerId());
        note.setLastUpdator(lastUpdator);
        note.setLastDateUpdated(lastUpdatedDate);
        note.setDisType(DiscrepancyNoteType.get(note.getDiscrepancyNoteTypeId()));
        note.setResStatus(ResolutionStatus.get(note.getResolutionStatusId()));
        if (pId > 0) {
            DiscrepancyNoteBean parent = noteTree.get(new Integer(pId));
            if (parent != null) {
                parent.getChildren().add(note);
                if (!note.getCreatedDate().before(parent.getLastDateUpdated())) {
                    parent.setLastDateUpdated(note.getCreatedDate());
                }
                if (note.getDiscrepancyNoteTypeId() == 1 && note.getAssignedUserId() > 0) {
                    int ownerId = note.getOwnerId();
                    if (fvcInitAssigns.containsKey(pId)) {
                        String f = fvcInitAssigns.get(pId);
                        String fn = note.getId() + "." + ownerId;
                        if (fn.compareTo(f) < 0) {
                            fvcInitAssigns.put(pId, fn);
                        }
                    } else {
                        fvcInitAssigns.put(pId, note.getId() + "." + ownerId);
                    }
                }
            }
        }
    }
    Set parents = noteTree.keySet();
    Iterator it = parents.iterator();
    while (it.hasNext()) {
        Integer key = (Integer) it.next();
        DiscrepancyNoteBean note = noteTree.get(key);
        note.setNumChildren(note.getChildren().size());
        note.setEntityType(name);
        if (!boxDNMap.containsKey(key)) {
            DiscrepancyNoteBean dn = new DiscrepancyNoteBean();
            dn.setId(key);
            int dnTypeId = note.getDiscrepancyNoteTypeId();
            dn.setDiscrepancyNoteTypeId(dnTypeId);
            if (dnTypeId == 3) {
                // JsonQuery
                dn.setAssignedUserId(note.getOwnerId());
            } else if (dnTypeId == 1) {
                // FVC
                if (fvcInitAssigns.containsKey(key)) {
                    String[] s = fvcInitAssigns.get(key).split("\\.");
                    int i = Integer.parseInt(s.length == 2 ? s[1].trim() : "0");
                    dn.setAssignedUserId(i);
                }
            }
            Role r = currentRole.getRole();
            // currentStudy.getId() != currentStudy.getParentStudyId()) {
            if (r.equals(Role.RESEARCHASSISTANT) || r.equals(Role.RESEARCHASSISTANT2) || r.equals(Role.INVESTIGATOR)) {
                if (dn.getDiscrepancyNoteTypeId() == DiscrepancyNoteType.QUERY.getId() && note.getResStatus().getId() == ResolutionStatus.UPDATED.getId()) {
                    dn.setResolutionStatusId(ResolutionStatus.UPDATED.getId());
                } else {
                    dn.setResolutionStatusId(ResolutionStatus.RESOLVED.getId());
                }
                if (dn.getAssignedUserId() > 0) {
                    autoviews.put(key, 1);
                } else {
                    autoviews.put(key, 0);
                }
            // copied from CreateDiscrepancyNoteServlet
            // request.setAttribute("autoView", "0");
            // hide the panel, tbh
            } else {
                if (note.getResStatus().getId() == ResolutionStatus.RESOLVED.getId()) {
                    dn.setResolutionStatusId(ResolutionStatus.CLOSED.getId());
                } else if (note.getResStatus().getId() == ResolutionStatus.CLOSED.getId()) {
                    dn.setResolutionStatusId(ResolutionStatus.UPDATED.getId());
                } else if (r.equals(Role.MONITOR)) {
                    dn.setResolutionStatusId(ResolutionStatus.UPDATED.getId());
                } else if (dn.getDiscrepancyNoteTypeId() == 1) {
                    dn.setResolutionStatusId(ResolutionStatus.RESOLVED.getId());
                } else {
                    dn.setResolutionStatusId(ResolutionStatus.UPDATED.getId());
                }
                autoviews.put(key, 1);
                if (dn.getAssignedUserId() > 0) {
                } else {
                    dn.setAssignedUserId(preUserId);
                }
            }
            boxDNMap.put(key, dn);
        }
    }
    session.setAttribute(BOX_DN_MAP, boxDNMap);
    session.setAttribute(AUTOVIEWS, autoviews);
    // noteTree is a Hashmap mapping note id to a parent note, with all the
    // child notes
    // stored in the children List.
    // BWP 3029>>make sure the parent note has an updated resolution status
    // and
    // updated date
    fixStatusUpdatedDate(noteTree);
    request.setAttribute(DIS_NOTES, noteTree);
    // copied from CreatediscrepancyNoteServlet generateUserAccounts
    StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
    StudyBean subjectStudy = studyDAO.findByStudySubjectId(subjectId);
    int studyId = currentStudy.getId();
    ArrayList<UserAccountBean> userAccounts = new ArrayList();
    if (currentStudy.getParentStudyId() > 0) {
        userAccounts = udao.findAllUsersByStudyOrSite(studyId, currentStudy.getParentStudyId(), subjectId);
    } else if (subjectStudy.getParentStudyId() > 0) {
        userAccounts = udao.findAllUsersByStudyOrSite(subjectStudy.getId(), subjectStudy.getParentStudyId(), subjectId);
    } else {
        userAccounts = udao.findAllUsersByStudyOrSite(studyId, 0, subjectId);
    }
    request.setAttribute(USER_ACCOUNTS, userAccounts);
    request.setAttribute(VIEW_DN_LINK, this.getPageServletFileName());
    // audit log items (from ViewItemAuditLogServlet.java)
    AuditDAO adao = new AuditDAO(sm.getDataSource());
    if (name.equalsIgnoreCase("studysub")) {
        name = "study_subject";
    } else if (name.equalsIgnoreCase("eventcrf")) {
        name = "event_crf";
    } else if (name.equalsIgnoreCase("studyevent")) {
        name = "study_event";
    } else if (name.equalsIgnoreCase("itemdata")) {
        name = "item_data";
    }
    ArrayList itemAuditEvents = adao.findItemAuditEvents(entityId, name);
    request.setAttribute("itemAudits", itemAuditEvents);
    forwardPage(Page.VIEW_DISCREPANCY_NOTE);
}
Also used : ItemBean(org.akaza.openclinica.bean.submit.ItemBean) ItemDAO(org.akaza.openclinica.dao.submit.ItemDAO) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) LinkedHashMap(java.util.LinkedHashMap) ResolutionStatus(org.akaza.openclinica.bean.core.ResolutionStatus) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) ItemDataBean(org.akaza.openclinica.bean.submit.ItemDataBean) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) ArrayList(java.util.ArrayList) List(java.util.List) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) DiscrepancyNoteDAO(org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) CRFDAO(org.akaza.openclinica.dao.admin.CRFDAO) CRFVersionDAO(org.akaza.openclinica.dao.submit.CRFVersionDAO) FormDiscrepancyNotes(org.akaza.openclinica.control.form.FormDiscrepancyNotes) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) CRFBean(org.akaza.openclinica.bean.admin.CRFBean) Role(org.akaza.openclinica.bean.core.Role) SubjectBean(org.akaza.openclinica.bean.submit.SubjectBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudyEventDefinitionDAO(org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO) DiscrepancyNoteBean(org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean) Set(java.util.Set) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) SubjectDAO(org.akaza.openclinica.dao.submit.SubjectDAO) InsufficientPermissionException(org.akaza.openclinica.web.InsufficientPermissionException) ItemDataDAO(org.akaza.openclinica.dao.submit.ItemDataDAO) AuditDAO(org.akaza.openclinica.dao.admin.AuditDAO) DiscrepancyNoteType(org.akaza.openclinica.bean.core.DiscrepancyNoteType) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) Iterator(java.util.Iterator) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) Date(java.util.Date) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) CRFVersionBean(org.akaza.openclinica.bean.submit.CRFVersionBean) SimpleDateFormat(java.text.SimpleDateFormat)

Example 8 with FormDiscrepancyNotes

use of org.akaza.openclinica.control.form.FormDiscrepancyNotes in project OpenClinica by OpenClinica.

the class UpdateSubjectServlet method confirm.

/**
     * Processes 'confirm' request, validate the subject object
     *
     * @throws Exception
     */
private void confirm(SubjectBean subject, int subjectId) throws Exception {
    FormDiscrepancyNotes discNotes = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
    if (discNotes == null) {
        discNotes = new FormDiscrepancyNotes();
    }
    DiscrepancyValidator v = new DiscrepancyValidator(request, discNotes);
    FormProcessor fp = new FormProcessor(request);
    if (currentStudy.getStudyParameterConfig().getPersonIdShownOnCRF().equals("true")) {
        v.addValidation("uniqueIdentifier", Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 255);
        v.alwaysExecuteLastValidation("uniqueIdentifier");
    }
    String personId = fp.getString(INPUT_UNIQUE_IDENTIFIER);
    if (personId.contains("<") || personId.contains(">")) {
        v.addValidation("uniqueIdentifier", Validator.DOES_NOT_CONTAIN_HTML_LESSTHAN_GREATERTHAN_ELEMENTS);
    }
    if (currentStudy.getStudyParameterConfig().getCollectDob().equals("1")) {
        if (!StringUtil.isBlank(fp.getString(DATE_DOB))) {
            v.addValidation(DATE_DOB, Validator.IS_A_DATE);
            v.alwaysExecuteLastValidation(DATE_DOB);
        } else if (StringUtil.isBlank(fp.getString(DATE_DOB)) && subject.getDateOfBirth() != null) {
            Validator.addError(errors, DATE_DOB, resexception.getString("field_not_blank"));
        }
        if (fp.getDate(DATE_DOB) != null) {
            subject.setDateOfBirth(fp.getDate(DATE_DOB));
            String converted_date = local_df.format(subject.getDateOfBirth());
            request.setAttribute(DATE_DOB_TO_SAVE, converted_date);
        }
    } else if (currentStudy.getStudyParameterConfig().getCollectDob().equals("2")) {
        if (!StringUtils.isBlank(fp.getString(DATE_DOB))) {
            // if DOB was not updated (and originally entered as a full day, post it as is
            String submitted_date = fp.getString(DATE_DOB);
            boolean isTheSameDate = false;
            try {
                Date fakeDOB = yformat.parse(submitted_date);
                if (subject.getDateOfBirth() != null) {
                    if (subject.getDateOfBirth().getYear() == (fakeDOB.getYear())) {
                        isTheSameDate = true;
                        String converted_date = yformat.format(subject.getDateOfBirth());
                        request.setAttribute(DATE_DOB_TO_SAVE, converted_date);
                    }
                }
            } catch (ParseException pe) {
                logger.debug("update subject: cannot convert date " + submitted_date);
            //I am putting on Pradnya's request the link to code review with a long discussion
            //about what type of logging should be here: enjoy
            //https://dev.openclinica.com/crucible/cru/OC-117
            }
            if (!isTheSameDate) {
                v.addValidation(DATE_DOB, Validator.IS_AN_INTEGER);
                v.alwaysExecuteLastValidation(DATE_DOB);
                v.addValidation(DATE_DOB, Validator.COMPARES_TO_STATIC_VALUE, NumericComparisonOperator.GREATER_THAN_OR_EQUAL_TO, 1000);
                // get today's year
                Date today = new Date();
                Calendar c = Calendar.getInstance();
                c.setTime(today);
                int currentYear = c.get(Calendar.YEAR);
                v.addValidation(DATE_DOB, Validator.COMPARES_TO_STATIC_VALUE, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, currentYear);
                int yob = fp.getInt(DATE_DOB);
                Date fakeDate = new Date(yob);
                String dobString = yformat.format(fakeDate);
                try {
                    Date fakeDOB = yformat.parse(dobString);
                    if (yob != 0) {
                        subject.setDateOfBirth(fakeDOB);
                    }
                    request.setAttribute(DATE_DOB_TO_SAVE, yob);
                } catch (ParseException pe) {
                    logger.debug("Parse exception happened.");
                    //I am putting on Pradnya's request the link to code review with a long discussion
                    //about what type of logging should be here: enjoy
                    //https://dev.openclinica.com/crucible/cru/OC-117
                    Validator.addError(errors, DATE_DOB, resexception.getString("please_enter_a_valid_year_birth"));
                }
            }
            request.setAttribute(DATE_DOB, fp.getString(DATE_DOB));
        } else {
            Validator.addError(errors, DATE_DOB, resexception.getString("field_not_blank"));
        }
    }
    errors = v.validate();
    // uniqueIdentifier must be unique in the system
    if (currentStudy.getStudyParameterConfig().getSubjectPersonIdRequired().equals("required") || currentStudy.getStudyParameterConfig().getSubjectPersonIdRequired().equals("optional")) {
        String uniqueIdentifier = fp.getString("uniqueIdentifier");
        if (currentStudy.getStudyParameterConfig().getSubjectPersonIdRequired().equals("required") && !(subject.getUniqueIdentifier() == null || subject.getUniqueIdentifier().isEmpty()) && (uniqueIdentifier == null || uniqueIdentifier.isEmpty())) {
            Validator.addError(errors, "uniqueIdentifier", resexception.getString("field_not_blank"));
        }
        if (uniqueIdentifier != null && !uniqueIdentifier.isEmpty()) {
            if (uniqueIdentifier.length() > 255) {
                String descr = resexception.getString("input_provided_is_not") + NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO.getDescription() + " 255 " + resword.getString("characters_long") + ".";
                Validator.addError(errors, "uniqueIdentifier", descr);
            }
            SubjectDAO sdao = new SubjectDAO(sm.getDataSource());
            SubjectBean sub1 = (SubjectBean) sdao.findAnotherByIdentifier(uniqueIdentifier, subject.getId());
            if (sub1.getId() > 0) {
                Validator.addError(errors, "uniqueIdentifier", resexception.getString("person_ID_used_by_another_choose_unique"));
            }
            SubjectBean subjectWithSameId = sdao.findByUniqueIdentifier(uniqueIdentifier);
            if (subjectWithSameId.isActive() && subjectWithSameId.getId() != subject.getId()) {
                Validator.addError(errors, "uniqueIdentifier", resexception.getString("another_assigned_this_ID_choose_unique"));
            }
        }
        subject.setUniqueIdentifier(uniqueIdentifier);
    }
    if (!StringUtil.isBlank(fp.getString("gender"))) {
        subject.setGender(fp.getString("gender").charAt(0));
    } else {
        if (currentStudy.getStudyParameterConfig().getGenderRequired().equals("true") && subject.getGender() != ' ') {
            Validator.addError(errors, "gender", resexception.getString("field_not_blank"));
        }
        subject.setGender(' ');
    }
    request.setAttribute("subjectToUpdate", subject);
    if (errors.isEmpty()) {
        forwardPage(Page.UPDATE_SUBJECT_CONFIRM);
    } else {
        //I am putting on Pradnya's request the link to code review with a long discussion
        //about what type of logging should be here: enjoy
        //https://dev.openclinica.com/crucible/cru/OC-117
        logger.error("update subject validation errors");
        setInputMessages(errors);
        setDNFlag(subjectId);
        setLocalDOB(subject);
        if (currentStudy.getStudyParameterConfig().getCollectDob().equals("2"))
            request.setAttribute("localBirthDate", "");
        forwardPage(Page.UPDATE_SUBJECT);
    }
}
Also used : SubjectBean(org.akaza.openclinica.bean.submit.SubjectBean) DiscrepancyValidator(org.akaza.openclinica.control.form.DiscrepancyValidator) FormDiscrepancyNotes(org.akaza.openclinica.control.form.FormDiscrepancyNotes) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) SubjectDAO(org.akaza.openclinica.dao.submit.SubjectDAO) Calendar(java.util.Calendar) ParseException(java.text.ParseException) Date(java.util.Date)

Example 9 with FormDiscrepancyNotes

use of org.akaza.openclinica.control.form.FormDiscrepancyNotes in project OpenClinica by OpenClinica.

the class ViewSectionDataEntryServlet method processRequest.

// BWP 01/08>>
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    FormProcessor fp = new FormProcessor(request);
    StudyBean currentStudy = (StudyBean) request.getSession().getAttribute("study");
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);
    SectionBean sb = (SectionBean) request.getAttribute(SECTION_BEAN);
    boolean isSubmitted = false;
    EventDefinitionCRFBean edcb = (EventDefinitionCRFBean) request.getAttribute(EVENT_DEF_CRF_BEAN);
    if (!fp.getString("exitTo").equals("")) {
        request.setAttribute("exitTo", fp.getString("exitTo"));
    }
    int crfVersionId = fp.getInt("crfVersionId", true);
    int sectionId = fp.getInt("sectionId");
    int eventCRFId = fp.getInt(EVENT_CRF_ID, true);
    int studySubjectId = fp.getInt("studySubjectId", true);
    String action = fp.getString("action");
    HttpSession session = request.getSession();
    String fromResolvingNotes = fp.getString("fromResolvingNotes", true);
    if (StringUtil.isBlank(fromResolvingNotes)) {
        session.removeAttribute(ViewNotesServlet.WIN_LOCATION);
        session.removeAttribute(ViewNotesServlet.NOTES_TABLE);
    }
    // Added for
    request.setAttribute("studySubjectId", studySubjectId + "");
    // Mantis
    // Issue
    // 2268
    // Added
    request.setAttribute("crfListPage", fp.getString("crfListPage"));
    // for
    // Mantis
    // Issue
    // 2268
    // Added for
    request.setAttribute("eventId", fp.getString("eventId"));
    // Mantis
    // Issue
    // 2268
    // YW <<
    int sedId = fp.getInt("sedId");
    request.setAttribute("sedId", sedId + "");
    int crfId = fp.getInt("crfId");
    // BWP>> ... try to get crfId from crfVersionId
    if (crfId == 0 && crfVersionId > 0) {
        CRFVersionDAO crfVDao = new CRFVersionDAO(getDataSource());
        CRFVersionBean crvVBean = (CRFVersionBean) crfVDao.findByPK(crfVersionId);
        if (crvVBean != null) {
            crfId = crvVBean.getCrfId();
        }
    }
    // YW >>
    int eventDefinitionCRFId = fp.getInt("eventDefinitionCRFId");
    EventDefinitionCRFDAO eventCrfDao = new EventDefinitionCRFDAO(getDataSource());
    edcb = (EventDefinitionCRFBean) eventCrfDao.findByPK(eventDefinitionCRFId);
    if (eventCRFId == 0 && edcb.getStudyId() != currentStudy.getParentStudyId() && edcb.getStudyId() != currentStudy.getId()) {
        addPageMessage(respage.getString("no_have_correct_privilege_current_study") + " " + respage.getString("change_study_contact_sysadmin"), request);
        throw new InsufficientPermissionException(Page.MENU_SERVLET, resexception.getString("not_director"), "1");
    }
    if (crfId == 0 && eventDefinitionCRFId > 0) {
        // eventCrfDao.findByPK(eventDefinitionCRFId);
        if (edcb != null) {
            crfId = edcb.getCrfId();
        }
    }
    request.setAttribute("crfId", crfId + "");
    request.setAttribute("eventDefinitionCRFId", eventDefinitionCRFId + "");
    String printVersion = fp.getString("print");
    // BWP>> this has to be removed for CRFs that do not display an
    // interviewdate
    // for a particular event
    session.removeAttribute("presetValues");
    EventCRFDAO ecdao = new EventCRFDAO(getDataSource());
    SectionDAO sdao = new SectionDAO(getDataSource());
    String age = "";
    if (sectionId == 0 && crfVersionId == 0 && eventCRFId == 0) {
        addPageMessage(respage.getString("please_choose_a_CRF_to_view"), request);
        // forwardPage(Page.SUBMIT_DATA_SERVLET);
        forwardPage(Page.LIST_STUDY_SUBJECTS_SERVLET, request, response);
        // >> changed tbh, 06/2009
        return;
    }
    if (studySubjectId > 0) {
        StudySubjectDAO ssdao = new StudySubjectDAO(getDataSource());
        StudySubjectBean sub = (StudySubjectBean) ssdao.findByPK(studySubjectId);
        request.setAttribute("studySubject", sub);
    }
    if (eventCRFId > 0) {
        // for event crf, the input crfVersionId from url =0
        ecb = (EventCRFBean) ecdao.findByPK(eventCRFId);
        StudyEventDAO sedao = new StudyEventDAO(getDataSource());
        StudyEventBean event = (StudyEventBean) sedao.findByPK(ecb.getStudyEventId());
        // event.getSubjectEventStatus().getName());
        if (event.getSubjectEventStatus().equals(SubjectEventStatus.LOCKED)) {
            request.setAttribute("isLocked", "yes");
        // System.out.println("this event crf is locked");
        } else {
            request.setAttribute("isLocked", "no");
        }
        if (studySubjectId <= 0) {
            studySubjectId = event.getStudySubjectId();
            request.setAttribute("studySubjectId", studySubjectId + "");
        }
        // Get the status/number of item discrepancy notes
        DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(getDataSource());
        ArrayList<DiscrepancyNoteBean> allNotes = new ArrayList<DiscrepancyNoteBean>();
        List<DiscrepancyNoteBean> eventCrfNotes = new ArrayList<DiscrepancyNoteBean>();
        List<DiscrepancyNoteThread> noteThreads = new ArrayList<DiscrepancyNoteThread>();
        // if (eventCRFId > 0) {
        // this method finds only parent notes
        allNotes = dndao.findAllTopNotesByEventCRF(eventCRFId);
        // add interviewer.jsp related notes to this Collection
        eventCrfNotes = dndao.findOnlyParentEventCRFDNotesFromEventCRF(ecb);
        if (!eventCrfNotes.isEmpty()) {
            allNotes.addAll(eventCrfNotes);
            // make sure a necessary request attribute "hasNameNote" is set
            // properly
            this.setAttributeForInterviewerDNotes(eventCrfNotes, request);
        }
        // }
        // Create disc note threads out of the various notes
        DiscrepancyNoteUtil dNoteUtil = new DiscrepancyNoteUtil();
        noteThreads = dNoteUtil.createThreadsOfParents(allNotes, getDataSource(), currentStudy, null, -1, true);
        // variables that provide values for the CRF discrepancy note header
        int updatedNum = 0;
        int openNum = 0;
        int closedNum = 0;
        int resolvedNum = 0;
        int notAppNum = 0;
        DiscrepancyNoteBean tempBean;
        for (DiscrepancyNoteThread dnThread : noteThreads) {
            /*
                 * 3014: do not count parent beans, only the last child disc
                 * note of the thread.
                 */
            tempBean = dnThread.getLinkedNoteList().getLast();
            if (tempBean != null) {
                if (ResolutionStatus.UPDATED.equals(tempBean.getResStatus())) {
                    updatedNum++;
                } else if (ResolutionStatus.OPEN.equals(tempBean.getResStatus())) {
                    openNum++;
                } else if (ResolutionStatus.CLOSED.equals(tempBean.getResStatus())) {
                    // if (dn.getParentDnId() > 0){
                    closedNum++;
                // }
                } else if (ResolutionStatus.RESOLVED.equals(tempBean.getResStatus())) {
                    // if (dn.getParentDnId() > 0){
                    resolvedNum++;
                // }
                } else if (ResolutionStatus.NOT_APPLICABLE.equals(tempBean.getResStatus())) {
                    notAppNum++;
                }
            }
        }
        request.setAttribute("updatedNum", updatedNum + "");
        request.setAttribute("openNum", openNum + "");
        request.setAttribute("closedNum", closedNum + "");
        request.setAttribute("resolvedNum", resolvedNum + "");
        request.setAttribute("notAppNum", notAppNum + "");
        DisplayTableOfContentsBean displayBean = TableOfContentsServlet.getDisplayBean(ecb, getDataSource(), currentStudy);
        // Make sure that the interviewDate in the eventCRF is properly
        // formatted
        // for viewSectionDataEntry.jsp --> interviewer.jsp
        // int studyEventId = (Integer)request.getAttribute("studyEvent");
        // SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        //
        Date tmpDate = displayBean.getEventCRF().getDateInterviewed();
        String formattedInterviewerDate;
        try {
            DateFormat local_df = new SimpleDateFormat(resformat.getString("date_format_string"), ResourceBundleProvider.getLocale());
            formattedInterviewerDate = local_df.format(tmpDate);
        } catch (Exception e) {
            formattedInterviewerDate = "";
        }
        HashMap presetVals = (HashMap) session.getAttribute("presetValues");
        if (presetVals == null) {
            presetVals = new HashMap();
            session.setAttribute("presetValues", presetVals);
        }
        presetVals.put("interviewDate", formattedInterviewerDate);
        request.setAttribute("toc", displayBean);
        ArrayList sections = displayBean.getSections();
        request.setAttribute("sectionNum", sections.size() + "");
        if (!sections.isEmpty()) {
            if (sectionId == 0) {
                SectionBean firstSec = (SectionBean) sections.get(0);
                sectionId = firstSec.getId();
            }
        } else {
            addPageMessage(respage.getString("there_are_no_sections_ins_this_CRF"), request);
            // forwardPage(Page.SUBMIT_DATA_SERVLET);
            forwardPage(Page.LIST_STUDY_SUBJECTS_SERVLET, request, response);
            // >> changed tbh, 06/2009
            return;
        }
    } else if (crfVersionId > 0) {
        // for viewing blank CRF
        DisplayTableOfContentsBean displayBean = ViewTableOfContentServlet.getDisplayBean(getDataSource(), crfVersionId);
        request.setAttribute("toc", displayBean);
        ArrayList sections = displayBean.getSections();
        request.setAttribute("sectionNum", sections.size() + "");
        if (!sections.isEmpty()) {
            if (sectionId == 0) {
                SectionBean firstSec = (SectionBean) sections.get(0);
                sectionId = firstSec.getId();
            }
        } else {
            addPageMessage(respage.getString("there_are_no_sections_ins_this_CRF_version"), request);
            if (eventCRFId == 0) {
                forwardPage(Page.CRF_LIST_SERVLET, request, response);
            } else {
                // forwardPage(Page.SUBMIT_DATA_SERVLET);
                forwardPage(Page.LIST_STUDY_SUBJECTS_SERVLET, request, response);
            // >> changed tbh, 06/2009
            }
            return;
        }
    }
    sb = (SectionBean) sdao.findByPK(sectionId);
    if (eventCRFId == 0) {
        ecb = new EventCRFBean();
        ecb.setCRFVersionId(sb.getCRFVersionId());
        if (currentStudy.getParentStudyId() > 0) {
            // this is a site,find parent
            StudyDAO studydao = new StudyDAO(getDataSource());
            StudyBean parentStudy = (StudyBean) studydao.findByPK(currentStudy.getParentStudyId());
            request.setAttribute("studyTitle", parentStudy.getName());
            request.setAttribute("siteTitle", currentStudy.getName());
        } else {
            request.setAttribute("studyTitle", currentStudy.getName());
        }
    } else {
        ecb = (EventCRFBean) ecdao.findByPK(eventCRFId);
        request.setAttribute(INPUT_EVENT_CRF, ecb);
        request.setAttribute(SECTION_BEAN, sb);
        // This is the StudySubjectBean
        StudySubjectDAO ssdao = new StudySubjectDAO(getDataSource());
        StudySubjectBean sub = (StudySubjectBean) ssdao.findByPK(ecb.getStudySubjectId());
        // This is the SubjectBean
        SubjectDAO subjectDao = new SubjectDAO(getDataSource());
        int subjectId = sub.getSubjectId();
        int studyId = sub.getStudyId();
        SubjectBean subject = (SubjectBean) subjectDao.findByPK(subjectId);
        // Let us process the age
        if (currentStudy.getStudyParameterConfig().getCollectDob().equals("1")) {
            StudyEventDAO sedao = new StudyEventDAO(getDataSource());
            StudyEventBean se = (StudyEventBean) sedao.findByPK(ecb.getStudyEventId());
            StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(getDataSource());
            StudyEventDefinitionBean sed = (StudyEventDefinitionBean) seddao.findByPK(se.getStudyEventDefinitionId());
            se.setStudyEventDefinition(sed);
            request.setAttribute("studyEvent", se);
            // YW 11-16-2007 enrollment-date is used for computing age
            age = Utils.getInstacne().processAge(sub.getEnrollmentDate(), subject.getDateOfBirth());
        }
        // Get the study then the parent study
        StudyDAO studydao = new StudyDAO(getDataSource());
        StudyBean study = (StudyBean) studydao.findByPK(studyId);
        if (study.getParentStudyId() > 0) {
            // this is a site,find parent
            StudyBean parentStudy = (StudyBean) studydao.findByPK(study.getParentStudyId());
            request.setAttribute("studyTitle", parentStudy.getName());
            request.setAttribute("siteTitle", study.getName());
        } else {
            request.setAttribute("studyTitle", study.getName());
        }
        request.setAttribute("studySubject", sub);
        request.setAttribute("subject", subject);
        request.setAttribute("age", age);
    }
    // FormBeanUtil formUtil = new FormBeanUtil();
    // DisplaySectionBean newDisplayBean = new DisplaySectionBean();
    boolean hasItemGroup = false;
    // we will look into db to see if any repeating items for this CRF
    // section
    ItemGroupDAO igdao = new ItemGroupDAO(getDataSource());
    List<ItemGroupBean> itemGroups = igdao.findLegitGroupBySectionId(sectionId);
    if (!itemGroups.isEmpty()) {
        hasItemGroup = true;
    }
    // if the List of DisplayFormGroups is empty, then the servlet defers to
    // the prior method
    // of generating a DisplaySectionBean for the application
    DisplaySectionBean dsb;
    // want to get displayBean with grouped and ungrouped items
    request.setAttribute(EVENT_DEF_CRF_BEAN, edcb);
    request.setAttribute(INPUT_EVENT_CRF, ecb);
    request.setAttribute(SECTION_BEAN, sb);
    dsb = super.getDisplayBean(hasItemGroup, false, request, isSubmitted);
    StudySubjectDAO studySubjectDAO = new StudySubjectDAO(getDataSource());
    StudyEventDefinitionDAO studyEventDefinitionDAO = new StudyEventDefinitionDAO(getDataSource());
    StudyEventDAO studyEventDAO = new StudyEventDAO(getDataSource());
    StudyEventDefinitionBean studyEventDefinition = (StudyEventDefinitionBean) studyEventDefinitionDAO.findByPK(edcb.getStudyEventDefinitionId());
    StudyEventBean studyEvent = (StudyEventBean) studyEventDAO.findByPK(ecb.getStudyEventId());
    VariableSubstitutionHelper.replaceVariables(dsb, currentStudy, (StudySubjectBean) studySubjectDAO.findByPK(studySubjectId), studyEventDefinition, studyEvent, getDataSource());
    FormDiscrepancyNotes discNotes = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
    if (discNotes == null) {
        discNotes = new FormDiscrepancyNotes();
        session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes);
    }
    /*
         * if (hasItemGroup) { //
         * dsb.setDisplayItemGroups(newDisplayBean.getDisplayItemGroups());
         * request.setAttribute("new_table", true); }
         */
    // If the Horizontal type table will be used, then set the
    // DisplaySectionBean's
    // DisplayFormGroups List to the ones we have just generated
    // @pgawade 30-May-2012 Fix for issue 13963 - added an extra parameter
    // 'isSubmitted' to method createItemWithGroups
    List<DisplayItemWithGroupBean> displayItemWithGroups = super.createItemWithGroups(dsb, hasItemGroup, eventDefinitionCRFId, request, isSubmitted);
    dsb.setDisplayItemGroups(displayItemWithGroups);
    super.populateNotesWithDBNoteCounts(discNotes, dsb, request);
    if (fp.getString("fromViewNotes") != null && "1".equals(fp.getString("fromViewNotes"))) {
        request.setAttribute("fromViewNotes", fp.getString("fromViewNotes"));
    } else {
        session.removeAttribute("viewNotesURL");
    }
    if ("saveNotes".equalsIgnoreCase(action)) {
        LOGGER.info("33333how many group rows:" + dsb.getDisplayItemGroups().size());
        // let's save notes for the blank items
        DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(getDataSource());
        discNotes = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
        for (int i = 0; i < dsb.getDisplayItemGroups().size(); i++) {
            DisplayItemWithGroupBean diwb = dsb.getDisplayItemGroups().get(i);
            if (diwb.isInGroup()) {
                List<DisplayItemGroupBean> dgbs = diwb.getItemGroups();
                LOGGER.info("dgbs size: " + dgbs.size());
                for (int j = 0; j < dgbs.size(); j++) {
                    DisplayItemGroupBean displayGroup = dgbs.get(j);
                    List<DisplayItemBean> items = displayGroup.getItems();
                    LOGGER.info("item size: " + items.size());
                    for (DisplayItemBean displayItem : items) {
                        String inputName = getGroupItemInputName(displayGroup, j, displayItem);
                        LOGGER.info("inputName:" + inputName);
                        LOGGER.info("item data id:" + displayItem.getData().getId());
                        AddNewSubjectServlet.saveFieldNotes(inputName, discNotes, dndao, displayItem.getData().getId(), "itemData", currentStudy);
                    }
                }
            } else {
                DisplayItemBean dib = diwb.getSingleItem();
                // TODO work on this line
                String inputName = getInputName(dib);
                AddNewSubjectServlet.saveFieldNotes(inputName, discNotes, dndao, dib.getData().getId(), DiscrepancyNoteBean.ITEM_DATA, currentStudy);
                ArrayList childItems = dib.getChildren();
                for (int j = 0; j < childItems.size(); j++) {
                    DisplayItemBean child = (DisplayItemBean) childItems.get(j);
                    inputName = getInputName(child);
                    AddNewSubjectServlet.saveFieldNotes(inputName, discNotes, dndao, dib.getData().getId(), DiscrepancyNoteBean.ITEM_DATA, currentStudy);
                }
            }
        }
        addPageMessage("Discrepancy notes are saved successfully.", request);
        request.setAttribute("id", studySubjectId + "");
        forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET, request, response);
        // "ViewStudySubject?id=" + studySubjectId));
        return;
    } else {
        request.setAttribute(BEAN_DISPLAY, dsb);
        request.setAttribute(BEAN_ANNOTATIONS, ecb.getAnnotations());
        request.setAttribute("sec", sb);
        request.setAttribute("EventCRFBean", ecb);
        int tabNum = 1;
        if ("".equalsIgnoreCase(fp.getString("tabId"))) {
            tabNum = 1;
        } else {
            tabNum = fp.getInt("tabId");
        }
        request.setAttribute("tabId", new Integer(tabNum).toString());
        // 2808: Signal interviewer.jsp that the containing page is
        // viewSectionData,
        // for the purpose of suppressing discrepancy note icons for the
        // interview date and name fields
        request.setAttribute(ENCLOSING_PAGE, "viewSectionData");
        if ("yes".equalsIgnoreCase(printVersion)) {
            forwardPage(Page.VIEW_SECTION_DATA_ENTRY_PRINT, request, response);
        } else {
            forwardPage(Page.VIEW_SECTION_DATA_ENTRY, request, response);
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) DiscrepancyNoteUtil(org.akaza.openclinica.service.DiscrepancyNoteUtil) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) DiscrepancyNoteDAO(org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO) FormDiscrepancyNotes(org.akaza.openclinica.control.form.FormDiscrepancyNotes) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) DisplayItemWithGroupBean(org.akaza.openclinica.bean.submit.DisplayItemWithGroupBean) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) EventDefinitionCRFDAO(org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO) SectionBean(org.akaza.openclinica.bean.submit.SectionBean) DisplaySectionBean(org.akaza.openclinica.bean.submit.DisplaySectionBean) SubjectBean(org.akaza.openclinica.bean.submit.SubjectBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudyEventDefinitionDAO(org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO) DiscrepancyNoteBean(org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean) EventDefinitionCRFBean(org.akaza.openclinica.bean.managestudy.EventDefinitionCRFBean) ItemGroupBean(org.akaza.openclinica.bean.submit.ItemGroupBean) DisplayItemGroupBean(org.akaza.openclinica.bean.submit.DisplayItemGroupBean) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) InsufficientPermissionException(org.akaza.openclinica.web.InsufficientPermissionException) DisplayItemBean(org.akaza.openclinica.bean.submit.DisplayItemBean) DiscrepancyNoteThread(org.akaza.openclinica.service.DiscrepancyNoteThread) DisplayItemGroupBean(org.akaza.openclinica.bean.submit.DisplayItemGroupBean) HttpSession(javax.servlet.http.HttpSession) DisplayTableOfContentsBean(org.akaza.openclinica.bean.submit.DisplayTableOfContentsBean) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) Date(java.util.Date) InsufficientPermissionException(org.akaza.openclinica.web.InsufficientPermissionException) DisplaySectionBean(org.akaza.openclinica.bean.submit.DisplaySectionBean) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) CRFVersionBean(org.akaza.openclinica.bean.submit.CRFVersionBean) SimpleDateFormat(java.text.SimpleDateFormat)

Example 10 with FormDiscrepancyNotes

use of org.akaza.openclinica.control.form.FormDiscrepancyNotes in project OpenClinica by OpenClinica.

the class CreateNewStudyEventServlet method processRequest.

@Override
protected void processRequest() throws Exception {
    checkStudyLocked(Page.LIST_STUDY_SUBJECTS, respage.getString("current_study_locked"));
    panel.setStudyInfoShown(false);
    fp = new FormProcessor(request);
    FormDiscrepancyNotes discNotes = null;
    int studySubjectId = fp.getInt(INPUT_STUDY_SUBJECT_ID_FROM_VIEWSUBJECT);
    // input from manage subject matrix, user has specified definition id
    int studyEventDefinitionId = fp.getInt(INPUT_STUDY_EVENT_DEFINITION);
    // TODO: make this sensitive to permissions
    StudySubjectDAO sdao = new StudySubjectDAO(sm.getDataSource());
    StudySubjectBean ssb;
    if (studySubjectId <= 0) {
        ssb = (StudySubjectBean) request.getAttribute(INPUT_STUDY_SUBJECT);
    } else {
        // YW 11-08-2007, << a new study event could not be added if its
        // study subject has been removed
        ssb = (StudySubjectBean) sdao.findByPK(studySubjectId);
        Status s = ssb.getStatus();
        if ("removed".equalsIgnoreCase(s.getName()) || "auto-removed".equalsIgnoreCase(s.getName())) {
            addPageMessage(resword.getString("study_event") + resterm.getString("could_not_be") + resterm.getString("added") + "." + respage.getString("study_subject_has_been_deleted"));
            request.setAttribute("id", new Integer(studySubjectId).toString());
            forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
        }
        // YW >>
        request.setAttribute(INPUT_REQUEST_STUDY_SUBJECT, "no");
    }
    // running this crashes the server, or so we think...instead, let's grab a count
    // or remove it altogether tbh 10/2009
    // ArrayList subjects = sdao.findAllActiveByStudyOrderByLabel(currentStudy);
    // TODO: make this sensitive to permissions
    StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource());
    StudyBean studyWithEventDefinitions = currentStudy;
    if (currentStudy.getParentStudyId() > 0) {
        studyWithEventDefinitions = new StudyBean();
        studyWithEventDefinitions.setId(currentStudy.getParentStudyId());
    }
    // find all active definitions with CRFs
    ArrayList eventDefinitions = seddao.findAllActiveByStudy(studyWithEventDefinitions);
    // EventDefinitionCRFDAO edcdao = new
    // EventDefinitionCRFDAO(sm.getDataSource());
    // ArrayList definitionsWithCRF = new ArrayList();
    // for (int i=0; i<eventDefinitions.size(); i++) {
    // StudyEventDefinitionBean sed =
    // (StudyEventDefinitionBean)eventDefinitions.get(i);
    // logger.info("StudyEventDefinition name[" + sed.getName() + "]");
    // ArrayList edcs = edcdao.findAllByEventDefinitionId(sed.getId());
    // if (!edcs.isEmpty()) {
    // definitionsWithCRF.add(sed);
    // }
    // }
    // Collections.sort(definitionsWithCRF);
    Collections.sort(eventDefinitions);
    /*
         * ArrayList eventDefinitionsScheduled = new ArrayList(); for (int i =
         * 0; i < eventDefinitions.size(); i++) { StudyEventDefinitionBean sed =
         * (StudyEventDefinitionBean) eventDefinitions.get(i); if
         * (sed.getType().equalsIgnoreCase("scheduled")) {
         * eventDefinitionsScheduled.add(sed); } }
         */
    // all definitions will appear in scheduled event creation box-11/26/05
    ArrayList eventDefinitionsScheduled = eventDefinitions;
    if (!fp.isSubmitted()) {
        // StudyEventDAO sed = new StudyEventDAO(sm.getDataSource());
        // sed.updateSampleOrdinals_v092();
        HashMap presetValues = new HashMap();
        // YW 08-16-2007 << set default as blank for time
        presetValues.put(INPUT_STARTDATE_PREFIX + "Hour", new Integer(-1));
        presetValues.put(INPUT_STARTDATE_PREFIX + "Minute", new Integer(-1));
        presetValues.put(INPUT_STARTDATE_PREFIX + "Half", new String(""));
        presetValues.put(INPUT_ENDDATE_PREFIX + "Hour", new Integer(-1));
        presetValues.put(INPUT_ENDDATE_PREFIX + "Minute", new Integer(-1));
        presetValues.put(INPUT_ENDDATE_PREFIX + "Half", new String(""));
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Hour", new Integer(-1));
            presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Minute", new Integer(-1));
            presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Half", new String(""));
            presetValues.put(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Hour", new Integer(-1));
            presetValues.put(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Minute", new Integer(-1));
            presetValues.put(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Half", new String(""));
        }
        // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        // example of taking the above line and transferring to i18n on the
        // below line, tbh
        String dateValue = local_df.format(new Date(System.currentTimeMillis()));
        presetValues.put(INPUT_STARTDATE_PREFIX + "Date", dateValue);
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Date", dateValue);
            // location
            presetValues.put(INPUT_SCHEDULED_LOCATION[i], currentStudy.getFacilityCity());
            presetValues.put(this.DISPLAY_SCHEDULED[i], "none");
        }
        // defualt
        presetValues.put(INPUT_LOCATION, currentStudy.getFacilityCity());
        if (ssb != null && ssb.isActive()) {
            presetValues.put(INPUT_STUDY_SUBJECT, ssb);
            String requestStudySubject = (String) request.getAttribute(INPUT_REQUEST_STUDY_SUBJECT);
            if (requestStudySubject != null) {
                presetValues.put(INPUT_REQUEST_STUDY_SUBJECT, requestStudySubject);
                dateValue = local_df.format(new Date());
                presetValues.put(INPUT_STARTDATE_PREFIX + "Date", dateValue);
            }
        }
        if (studyEventDefinitionId > 0) {
            StudyEventDefinitionBean sed = (StudyEventDefinitionBean) seddao.findByPK(studyEventDefinitionId);
            presetValues.put(INPUT_STUDY_EVENT_DEFINITION, sed);
        }
        // tbh
        logger.debug("set preset values: " + presetValues.toString());
        logger.debug("found def.w.CRF list, size " + eventDefinitions.size());
        // tbh
        setPresetValues(presetValues);
        ArrayList subjects = new ArrayList();
        setupBeans(subjects, eventDefinitions);
        discNotes = new FormDiscrepancyNotes();
        session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes);
        request.setAttribute("eventDefinitionsScheduled", eventDefinitionsScheduled);
        setInputMessages(new HashMap());
        forwardPage(Page.CREATE_NEW_STUDY_EVENT);
    } else {
        // tbh
        // String dateCheck = (String)request.getAttribute("startDate");
        // String endCheck = (String)request.getAttribute("endDate");
        // logger.debug(dateCheck+"; "+endCheck);
        String dateCheck2 = request.getParameter("startDate");
        String endCheck2 = request.getParameter("endDate");
        logger.debug(dateCheck2 + "; " + endCheck2);
        // YW, 3-12-2008, 2220 fix <<
        String strEnd = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX);
        String[] strEndScheduled = new String[ADDITIONAL_SCHEDULED_NUM];
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            strEndScheduled[i] = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
        }
        Date start = getInputStartDate();
        Date end = null;
        Date[] startScheduled = new Date[ADDITIONAL_SCHEDULED_NUM];
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            startScheduled[i] = getInputStartDateScheduled(i);
        }
        Date[] endScheduled = new Date[ADDITIONAL_SCHEDULED_NUM];
        // YW >>
        // for (java.util.Enumeration enu = request.getAttributeNames();
        // enu.hasMoreElements() ;) {
        // logger.debug(">>> found "+enu.nextElement().toString());
        // }
        // tbh
        discNotes = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
        if (discNotes == null) {
            discNotes = new FormDiscrepancyNotes();
            session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes);
        }
        DiscrepancyValidator v = new DiscrepancyValidator(request, discNotes);
        v.addValidation(INPUT_STARTDATE_PREFIX, Validator.IS_DATE_TIME);
        v.alwaysExecuteLastValidation(INPUT_STARTDATE_PREFIX);
        if (!strEnd.equals("")) {
            v.addValidation(INPUT_ENDDATE_PREFIX, Validator.IS_DATE_TIME);
            v.alwaysExecuteLastValidation(INPUT_ENDDATE_PREFIX);
        }
        v.addValidation(INPUT_STUDY_EVENT_DEFINITION, Validator.ENTITY_EXISTS_IN_STUDY, seddao, studyWithEventDefinitions);
        // v.addValidation(INPUT_STUDY_SUBJECT, Validator.ENTITY_EXISTS_IN_STUDY, sdao, currentStudy);
        // removed tbh 11/2009
        //Made optional field-issue-4904.
        //v.addValidation(INPUT_LOCATION, Validator.NO_BLANKS);
        v.addValidation(INPUT_STUDY_SUBJECT_LABEL, Validator.NO_BLANKS);
        v.addValidation(INPUT_LOCATION, Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 2000);
        if (currentStudy.getStudyParameterConfig().getEventLocationRequired().equalsIgnoreCase("required")) {
            v.addValidation(INPUT_LOCATION, Validator.NO_BLANKS);
        }
        v.alwaysExecuteLastValidation(INPUT_LOCATION);
        boolean hasScheduledEvent = false;
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            if (!StringUtil.isBlank(fp.getString(this.INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i]))) {
                // logger.debug("has scheduled definition******");
                v.addValidation(this.INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i], Validator.ENTITY_EXISTS_IN_STUDY, seddao, studyWithEventDefinitions);
                if (currentStudy.getStudyParameterConfig().getEventLocationRequired().equalsIgnoreCase("required")) {
                    v.addValidation(INPUT_SCHEDULED_LOCATION[i], Validator.NO_BLANKS);
                    v.addValidation(INPUT_SCHEDULED_LOCATION[i], Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 2000);
                    v.alwaysExecuteLastValidation(INPUT_SCHEDULED_LOCATION[i]);
                }
                v.addValidation(INPUT_STARTDATE_PREFIX_SCHEDULED[i], Validator.IS_DATE_TIME);
                v.alwaysExecuteLastValidation(INPUT_STARTDATE_PREFIX_SCHEDULED[i]);
                if (!strEndScheduled[i].equals("")) {
                    v.addValidation(INPUT_ENDDATE_PREFIX_SCHEDULED[i], Validator.IS_DATE_TIME);
                    v.alwaysExecuteLastValidation(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
                }
                hasScheduledEvent = true;
                fp.addPresetValue(DISPLAY_SCHEDULED[i], "all");
            } else {
                fp.addPresetValue(DISPLAY_SCHEDULED[i], "none");
            }
        }
        HashMap errors = v.validate();
        // logger.debug("v is not null *****");
        String location = resword.getString("location");
        // is a required field
        if (!StringUtil.isBlank(fp.getString(INPUT_LOCATION)) && fp.getString(INPUT_LOCATION).equalsIgnoreCase(location)) {
            Validator.addError(errors, INPUT_LOCATION, restext.getString("not_a_valid_location"));
        }
        StudyEventDefinitionBean definition = (StudyEventDefinitionBean) seddao.findByPK(fp.getInt(INPUT_STUDY_EVENT_DEFINITION));
        // StudySubjectBean studySubject = (StudySubjectBean) sdao.findByPK(fp.getInt(INPUT_STUDY_SUBJECT));
        // sdao.findByLabelAndStudy(label, study)
        StudySubjectBean studySubject = sdao.findByLabelAndStudy(fp.getString(INPUT_STUDY_SUBJECT_LABEL), currentStudy);
        // what if we are sent here from AddNewSubjectServlet.java??? we need to get that study subject bean
        if (request.getAttribute(INPUT_STUDY_SUBJECT) != null) {
            studySubject = (StudySubjectBean) request.getAttribute(INPUT_STUDY_SUBJECT);
        }
        // << tbh
        if (studySubject.getLabel() == "") {
            // add an error here, tbh
            Validator.addError(errors, INPUT_STUDY_SUBJECT, respage.getString("must_enter_subject_ID_for_identifying"));
        }
        if (!subjectMayReceiveStudyEvent(sm.getDataSource(), definition, studySubject)) {
            Validator.addError(errors, INPUT_STUDY_EVENT_DEFINITION, restext.getString("not_added_since_event_not_repeating"));
        }
        ArrayList<StudyEventDefinitionBean> definitionScheduleds = new ArrayList<StudyEventDefinitionBean>();
        int[] scheduledDefinitionIds = new int[ADDITIONAL_SCHEDULED_NUM];
        if (hasScheduledEvent) {
            for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
                int pk = fp.getInt(INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i]);
                if (pk > 0) {
                    StudyEventDefinitionBean sedb = (StudyEventDefinitionBean) seddao.findByPK(pk);
                    logger.debug("scheduled def:" + pk + " " + INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i] + " " + sedb.getName());
                    definitionScheduleds.add(sedb);
                    scheduledDefinitionIds[i] = pk;
                    if (!subjectMayReceiveStudyEvent(sm.getDataSource(), sedb, studySubject)) {
                        Validator.addError(errors, INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i], restext.getString("not_added_since_event_not_repeating"));
                    }
                } else {
                    definitionScheduleds.add(new StudyEventDefinitionBean());
                }
            }
        }
        // YW, 3-12-2008, 2220 fix >>
        if (!"".equals(strEnd) && !errors.containsKey(INPUT_STARTDATE_PREFIX) && !errors.containsKey(INPUT_ENDDATE_PREFIX)) {
            end = getInputEndDate();
            if (!fp.getString(INPUT_STARTDATE_PREFIX + "Date").equals(fp.getString(INPUT_ENDDATE_PREFIX + "Date"))) {
                if (end.before(start)) {
                    Validator.addError(errors, INPUT_ENDDATE_PREFIX, resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                }
            } else {
                // if in same date, only check when both had time entered
                if (fp.timeEntered(INPUT_STARTDATE_PREFIX) && fp.timeEntered(INPUT_ENDDATE_PREFIX)) {
                    if (end.before(start) || end.equals(start)) {
                        Validator.addError(errors, INPUT_ENDDATE_PREFIX, resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                    }
                }
            }
        }
        String prevStartPrefix = INPUT_STARTDATE_PREFIX;
        Set<Integer> pickedSeds = new TreeSet<Integer>();
        pickedSeds.add(studyEventDefinitionId);
        HashMap<Integer, Integer> scheduledSeds = new HashMap<Integer, Integer>();
        scheduledSeds.put(studyEventDefinitionId, -1);
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            if (scheduledDefinitionIds[i] > 0 && !errors.containsKey(INPUT_STARTDATE_PREFIX_SCHEDULED[i]) && !errors.containsKey(INPUT_ENDDATE_PREFIX_SCHEDULED[i])) {
                if (scheduledSeds.containsKey(scheduledDefinitionIds[i])) {
                    int prevStart = scheduledSeds.get(scheduledDefinitionIds[i]);
                    prevStartPrefix = prevStart == -1 ? INPUT_STARTDATE_PREFIX : INPUT_STARTDATE_PREFIX_SCHEDULED[prevStart];
                    Date prevStartDate = prevStart == -1 ? this.getInputStartDate() : this.getInputStartDateScheduled(Integer.parseInt(prevStartPrefix.charAt(prevStartPrefix.length() - 1) + ""));
                    if (fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Date").equals(fp.getString(prevStartPrefix + "Date"))) {
                        // if in same day, only check when both have time
                        // inputs.
                        boolean schStartTime = fp.timeEntered(INPUT_STARTDATE_PREFIX_SCHEDULED[i]);
                        boolean startTime = fp.timeEntered(prevStartPrefix);
                        if (schStartTime && startTime) {
                            if (startScheduled[i].before(prevStartDate)) {
                                Validator.addError(errors, INPUT_STARTDATE_PREFIX_SCHEDULED[i], resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                            }
                        }
                    } else {
                        if (startScheduled[i].before(prevStartDate)) {
                            Validator.addError(errors, INPUT_STARTDATE_PREFIX_SCHEDULED[i], resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                        }
                    }
                }
                scheduledSeds.put(scheduledDefinitionIds[i], i);
                if (!strEndScheduled[i].equals("")) {
                    endScheduled[i] = fp.getDateTime(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
                    String prevEndPrefix = i > 0 ? INPUT_ENDDATE_PREFIX_SCHEDULED[i - 1] : INPUT_ENDDATE_PREFIX;
                    if (!fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Date").equals(fp.getString(prevEndPrefix + "Date"))) {
                        if (endScheduled[i].before(startScheduled[i])) {
                            Validator.addError(errors, INPUT_ENDDATE_PREFIX_SCHEDULED[i], resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                        }
                    } else {
                        // entered
                        if (fp.timeEntered(INPUT_STARTDATE_PREFIX_SCHEDULED[i]) && fp.timeEntered(INPUT_ENDDATE_PREFIX_SCHEDULED[i])) {
                            if (endScheduled[i].before(startScheduled[i]) || endScheduled[i].equals(startScheduled[i])) {
                                Validator.addError(errors, INPUT_ENDDATE_PREFIX_SCHEDULED[i], resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                            }
                        }
                    }
                }
            }
        }
        // YW >>
        logger.error("we have errors; number of this; " + errors.size());
        if (!errors.isEmpty()) {
            logger.debug("we have errors; number of this; " + errors.size());
            logger.error("found request study subject: " + fp.getString(INPUT_REQUEST_STUDY_SUBJECT));
            addPageMessage(respage.getString("errors_in_submission_see_below"));
            setInputMessages(errors);
            fp.addPresetValue(INPUT_STUDY_EVENT_DEFINITION, definition);
            fp.addPresetValue(INPUT_STUDY_SUBJECT, studySubject);
            fp.addPresetValue(INPUT_STUDY_SUBJECT_LABEL, fp.getString(INPUT_STUDY_SUBJECT_LABEL));
            fp.addPresetValue(INPUT_REQUEST_STUDY_SUBJECT, fp.getString(INPUT_REQUEST_STUDY_SUBJECT));
            fp.addPresetValue(INPUT_LOCATION, fp.getString(INPUT_LOCATION));
            for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
                fp.addPresetValue(INPUT_SCHEDULED_LOCATION[i], fp.getString(INPUT_SCHEDULED_LOCATION[i]));
            }
            String[] prefixes = new String[2 + 2 * ADDITIONAL_SCHEDULED_NUM];
            prefixes[0] = INPUT_STARTDATE_PREFIX;
            prefixes[1] = INPUT_ENDDATE_PREFIX;
            int b = ADDITIONAL_SCHEDULED_NUM + 2;
            for (int i = 2; i < b; ++i) {
                prefixes[i] = INPUT_STARTDATE_PREFIX_SCHEDULED[i - 2];
            }
            for (int i = b; i < ADDITIONAL_SCHEDULED_NUM + b; ++i) {
                prefixes[i] = INPUT_ENDDATE_PREFIX_SCHEDULED[i - b];
            }
            fp.setCurrentDateTimeValuesAsPreset(prefixes);
            if (hasScheduledEvent) {
                for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
                    fp.addPresetValue(INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i], definitionScheduleds.get(i));
                }
            }
            setPresetValues(fp.getPresetValues());
            ArrayList subjects = new ArrayList();
            setupBeans(subjects, eventDefinitions);
            request.setAttribute("eventDefinitionsScheduled", eventDefinitionsScheduled);
            forwardPage(Page.CREATE_NEW_STUDY_EVENT);
        } else {
            logger.debug("error is empty");
            StudyEventDAO sed = new StudyEventDAO(sm.getDataSource());
            StudyEventBean studyEvent = new StudyEventBean();
            studyEvent.setStudyEventDefinitionId(definition.getId());
            studyEvent.setStudySubjectId(studySubject.getId());
            // YW 08-17-2007 <<
            if ("-1".equals(getInputStartHour()) && "-1".equals(getInputStartMinute()) && "".equals(getInputStartHalf())) {
                studyEvent.setStartTimeFlag(false);
            } else {
                studyEvent.setStartTimeFlag(true);
            }
            // YW >>
            studyEvent.setDateStarted(start);
            // comment to find bug 1389, tbh
            logger.debug("found start date: " + local_df.format(start));
            Date[] startScheduled2 = new Date[ADDITIONAL_SCHEDULED_NUM];
            for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
                startScheduled2[i] = getInputStartDateScheduled(i);
            }
            // YW, 3-12-2008, 2220 fix <<
            if (!"".equals(strEnd)) {
                // YW >>
                if ("-1".equals(getInputEndHour()) && "-1".equals(getInputEndMinute()) && "".equals(getInputEndHalf())) {
                    studyEvent.setEndTimeFlag(false);
                } else {
                    studyEvent.setEndTimeFlag(true);
                }
                studyEvent.setDateEnded(end);
            }
            studyEvent.setOwner(ub);
            studyEvent.setStatus(Status.AVAILABLE);
            studyEvent.setLocation(fp.getString(INPUT_LOCATION));
            studyEvent.setSubjectEventStatus(SubjectEventStatus.SCHEDULED);
            // ArrayList subjectsExistingEvents =
            // sed.findAllByStudyAndStudySubjectId(currentStudy,
            // studySubject.getId());
            studyEvent.setSampleOrdinal(sed.getMaxSampleOrdinal(definition, studySubject) + 1);
            studyEvent = (StudyEventBean) sed.create(studyEvent);
            if (!studyEvent.isActive()) {
                throw new OpenClinicaException(restext.getString("event_not_created_in_database"), "2");
            }
            addPageMessage(restext.getString("X_event_wiht_definition") + definition.getName() + restext.getString("X_and_subject") + studySubject.getName() + respage.getString("X_was_created_succesfully"));
            // save discrepancy notes into DB
            FormDiscrepancyNotes fdn = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
            DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
            String[] eventFields = { INPUT_LOCATION, INPUT_STARTDATE_PREFIX, INPUT_ENDDATE_PREFIX };
            for (String element : eventFields) {
                AddNewSubjectServlet.saveFieldNotes(element, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy);
            }
            // logger.debug("here ok 3333333333333333");
            if (hasScheduledEvent) {
                for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
                    // which is scheduledDefinitionIds[i] > 0
                    if (scheduledDefinitionIds[i] > 0) {
                        if (subjectMayReceiveStudyEvent(sm.getDataSource(), definitionScheduleds.get(i), studySubject)) {
                            StudyEventBean studyEventScheduled = new StudyEventBean();
                            studyEventScheduled.setStudyEventDefinitionId(scheduledDefinitionIds[i]);
                            studyEventScheduled.setStudySubjectId(studySubject.getId());
                            // YW 11-14-2007
                            if ("-1".equals(fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Hour")) && "-1".equals(fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Minute")) && "".equals(fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Half"))) {
                                studyEventScheduled.setStartTimeFlag(false);
                            } else {
                                studyEventScheduled.setStartTimeFlag(true);
                            }
                            // YW >>
                            studyEventScheduled.setDateStarted(startScheduled[i]);
                            // YW, 3-12-2008, 2220 fix<<
                            if (!"".equals(strEndScheduled[i])) {
                                endScheduled[i] = fp.getDateTime(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
                                if ("-1".equals(fp.getString(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Hour")) && "-1".equals(fp.getString(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Minute")) && "".equals(fp.getString(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Half"))) {
                                    studyEventScheduled.setEndTimeFlag(false);
                                } else {
                                    studyEventScheduled.setEndTimeFlag(true);
                                }
                            }
                            studyEventScheduled.setDateEnded(endScheduled[i]);
                            // YW >>
                            studyEventScheduled.setOwner(ub);
                            studyEventScheduled.setStatus(Status.AVAILABLE);
                            studyEventScheduled.setLocation(fp.getString(INPUT_SCHEDULED_LOCATION[i]));
                            studyEvent.setSubjectEventStatus(SubjectEventStatus.SCHEDULED);
                            // subjectsExistingEvents =
                            // sed.findAllByStudyAndStudySubjectId(
                            // currentStudy,
                            // studySubject.getId());
                            studyEventScheduled.setSampleOrdinal(sed.getMaxSampleOrdinal(definitionScheduleds.get(i), studySubject) + 1);
                            //System.out.println("create scheduled events");
                            studyEventScheduled = (StudyEventBean) sed.create(studyEventScheduled);
                            if (!studyEventScheduled.isActive()) {
                                throw new OpenClinicaException(restext.getString("scheduled_event_not_created_in_database"), "2");
                            }
                            AddNewSubjectServlet.saveFieldNotes(INPUT_SCHEDULED_LOCATION[i], fdn, dndao, studyEventScheduled.getId(), "studyEvent", currentStudy);
                            // YW 3-12-2008, 2220 fix <<
                            AddNewSubjectServlet.saveFieldNotes(INPUT_STARTDATE_PREFIX_SCHEDULED[i], fdn, dndao, studyEventScheduled.getId(), "studyEvent", currentStudy);
                            AddNewSubjectServlet.saveFieldNotes(INPUT_ENDDATE_PREFIX_SCHEDULED[i], fdn, dndao, studyEventScheduled.getId(), "studyEvent", currentStudy);
                        // YW >>
                        } else {
                            addPageMessage(restext.getString("scheduled_event_definition") + definitionScheduleds.get(i).getName() + restext.getString("X_and_subject") + studySubject.getName() + restext.getString("not_created_since_event_not_repeating") + restext.getString("event_type_already_exists"));
                        }
                    }
                }
            }
            // if
            session.removeAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
            request.setAttribute(EnterDataForStudyEventServlet.INPUT_EVENT_ID, String.valueOf(studyEvent.getId()));
            ArrayList<String> pMessage = (ArrayList<String>) request.getAttribute(SecureController.PAGE_MESSAGE);
            String url = response.encodeRedirectURL("EnterDataForStudyEvent?eventId=" + studyEvent.getId() + "&alertmessage=" + URLEncoder.encode(pMessage.get(0), "UTF-8"));
            response.sendRedirect(url);
            // + studyEvent.getId()));
            return;
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) TreeSet(java.util.TreeSet) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) Status(org.akaza.openclinica.bean.core.Status) SubjectEventStatus(org.akaza.openclinica.bean.core.SubjectEventStatus) DiscrepancyNoteDAO(org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO) FormDiscrepancyNotes(org.akaza.openclinica.control.form.FormDiscrepancyNotes) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) Date(java.util.Date) DiscrepancyValidator(org.akaza.openclinica.control.form.DiscrepancyValidator) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudyEventDefinitionDAO(org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO)

Aggregations

FormDiscrepancyNotes (org.akaza.openclinica.control.form.FormDiscrepancyNotes)20 ArrayList (java.util.ArrayList)15 FormProcessor (org.akaza.openclinica.control.form.FormProcessor)15 HashMap (java.util.HashMap)14 StudySubjectBean (org.akaza.openclinica.bean.managestudy.StudySubjectBean)13 DiscrepancyNoteDAO (org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO)13 StudySubjectDAO (org.akaza.openclinica.dao.managestudy.StudySubjectDAO)13 StudyBean (org.akaza.openclinica.bean.managestudy.StudyBean)12 StudyDAO (org.akaza.openclinica.dao.managestudy.StudyDAO)11 Date (java.util.Date)10 StudyEventBean (org.akaza.openclinica.bean.managestudy.StudyEventBean)9 StudyEventDAO (org.akaza.openclinica.dao.managestudy.StudyEventDAO)9 DiscrepancyNoteBean (org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean)8 StudyEventDefinitionBean (org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean)8 EventCRFBean (org.akaza.openclinica.bean.submit.EventCRFBean)8 SubjectBean (org.akaza.openclinica.bean.submit.SubjectBean)8 StudyEventDefinitionDAO (org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO)8 SubjectDAO (org.akaza.openclinica.dao.submit.SubjectDAO)8 EventCRFDAO (org.akaza.openclinica.dao.submit.EventCRFDAO)7 ItemDataBean (org.akaza.openclinica.bean.submit.ItemDataBean)6