Search in sources :

Example 26 with DiscrepancyNoteDAO

use of org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO 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)

Example 27 with DiscrepancyNoteDAO

use of org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO in project OpenClinica by OpenClinica.

the class CreateOneDiscrepancyNoteServlet method processRequest.

@Override
protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
    int eventCRFId = fp.getInt(CreateDiscrepancyNoteServlet.EVENT_CRF_ID);
    request.setAttribute(CreateDiscrepancyNoteServlet.EVENT_CRF_ID, new Integer(eventCRFId));
    int parentId = fp.getInt(PARENT_ID);
    DiscrepancyNoteBean parent = parentId > 0 ? (DiscrepancyNoteBean) dndao.findByPK(parentId) : new DiscrepancyNoteBean();
    HashMap<Integer, DiscrepancyNoteBean> boxDNMap = (HashMap<Integer, DiscrepancyNoteBean>) session.getAttribute(BOX_DN_MAP);
    boxDNMap = boxDNMap == null ? new HashMap<Integer, DiscrepancyNoteBean>() : boxDNMap;
    DiscrepancyNoteBean dn = boxDNMap.size() > 0 && boxDNMap.containsKey(Integer.valueOf(parentId)) ? boxDNMap.get(Integer.valueOf(parentId)) : new DiscrepancyNoteBean();
    int entityId = fp.getInt(ENTITY_ID, true);
    entityId = entityId > 0 ? entityId : parent.getEntityId();
    if (entityId == 0) {
        Validator.addError(errors, "newChildAdded" + parentId, respage.getString("note_cannot_be_saved"));
        logger.info("entityId is 0. Note saving can not be started.");
    }
    String entityType = fp.getString(ENTITY_TYPE, true);
    FormDiscrepancyNotes noteTree = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
    if (noteTree == null) {
        noteTree = new FormDiscrepancyNotes();
    }
    String ypos = fp.getString("ypos" + parentId);
    int refresh = 0;
    String field = fp.getString(ENTITY_FIELD, true);
    String description = fp.getString("description" + parentId);
    int typeId = fp.getInt("typeId" + parentId);
    String detailedDes = fp.getString("detailedDes" + parentId);
    int resStatusId = fp.getInt(RES_STATUS_ID + parentId);
    int assignedUserAccountId = fp.getInt(SUBMITTED_USER_ACCOUNT_ID + parentId);
    String viewNoteLink = fp.getString("viewDNLink" + parentId);
    viewNoteLink = this.appendPageFileName(viewNoteLink, "fromBox", "1");
    Validator v = new Validator(request);
    v.addValidation("description" + parentId, Validator.NO_BLANKS);
    v.addValidation("description" + parentId, Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 255);
    v.addValidation("detailedDes" + parentId, Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 1000);
    v.addValidation("typeId" + parentId, Validator.NO_BLANKS);
    HashMap errors = v.validate();
    dn.setParentDnId(parentId);
    dn.setDescription(description);
    dn.setDiscrepancyNoteTypeId(typeId);
    dn.setDetailedNotes(detailedDes);
    dn.setResolutionStatusId(resStatusId);
    if (typeId != DiscrepancyNoteType.ANNOTATION.getId() && typeId != DiscrepancyNoteType.REASON_FOR_CHANGE.getId()) {
        dn.setAssignedUserId(assignedUserAccountId);
    }
    if (DiscrepancyNoteType.ANNOTATION.getId() == dn.getDiscrepancyNoteTypeId()) {
        updateStudyEvent(entityType, entityId);
        updateStudySubjectStatus(entityType, entityId);
    }
    if (DiscrepancyNoteType.ANNOTATION.getId() == dn.getDiscrepancyNoteTypeId() || DiscrepancyNoteType.REASON_FOR_CHANGE.getId() == dn.getDiscrepancyNoteTypeId()) {
        dn.setResStatus(ResolutionStatus.NOT_APPLICABLE);
        dn.setResolutionStatusId(ResolutionStatus.NOT_APPLICABLE.getId());
    }
    if (DiscrepancyNoteType.FAILEDVAL.getId() == dn.getDiscrepancyNoteTypeId() || DiscrepancyNoteType.QUERY.getId() == dn.getDiscrepancyNoteTypeId()) {
        if (ResolutionStatus.NOT_APPLICABLE.getId() == dn.getResolutionStatusId()) {
            Validator.addError(errors, RES_STATUS_ID + parentId, restext.getString("not_valid_res_status"));
        }
    }
    if (errors.isEmpty()) {
        HashMap<String, ArrayList<String>> results = new HashMap<String, ArrayList<String>>();
        ArrayList<String> mess = new ArrayList<String>();
        String column = fp.getString(ENTITY_COLUMN, true);
        dn.setOwner(ub);
        dn.setStudyId(currentStudy.getId());
        dn.setEntityId(entityId);
        dn.setEntityType(entityType);
        dn.setColumn(column);
        dn.setField(field);
        if (parentId > 0) {
            if (dn.getResolutionStatusId() != parent.getResolutionStatusId()) {
                parent.setResolutionStatusId(dn.getResolutionStatusId());
                dndao.update(parent);
                if (!parent.isActive()) {
                    logger.info("Failed to update resolution status ID for the parent dn ID = " + parentId + ". ");
                }
            }
            if (dn.getAssignedUserId() != parent.getAssignedUserId()) {
                parent.setAssignedUserId(dn.getAssignedUserId());
                if (parent.getAssignedUserId() > 0) {
                    dndao.updateAssignedUser(parent);
                } else {
                    dndao.updateAssignedUserToNull(parent);
                }
                if (!parent.isActive()) {
                    logger.info("Failed to update assigned user ID for the parent dn ID= " + parentId + ". ");
                }
            }
        } else {
            ypos = "0";
        }
        dn = (DiscrepancyNoteBean) dndao.create(dn);
        boolean success = dn.getId() > 0 ? true : false;
        if (success) {
            refresh = 1;
            dndao.createMapping(dn);
            success = dndao.isQuerySuccessful();
            if (success == false) {
                mess.add(restext.getString("failed_create_dn_mapping_for_dnId") + dn.getId() + ". ");
            }
            noteTree.addNote(eventCRFId + "_" + field, dn);
            noteTree.addIdNote(dn.getEntityId(), field);
            session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, noteTree);
            if (dn.getParentDnId() == 0) {
                // see issue 2659 this is a new thread, we will create
                // two notes in this case,
                // This way one can be the parent that updates as the
                // status changes, but one also stays as New.
                dn.setParentDnId(dn.getId());
                dn = (DiscrepancyNoteBean) dndao.create(dn);
                if (dn.getId() > 0) {
                    dndao.createMapping(dn);
                    if (!dndao.isQuerySuccessful()) {
                        mess.add(restext.getString("failed_create_dn_mapping_for_dnId") + dn.getId() + ". ");
                    }
                    noteTree.addNote(eventCRFId + "_" + field, dn);
                    noteTree.addIdNote(dn.getEntityId(), field);
                    session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, noteTree);
                } else {
                    mess.add(restext.getString("failed_create_child_dn_for_new_parent_dnId") + dn.getId() + ". ");
                }
            }
        } else {
            mess.add(restext.getString("failed_create_new_dn") + ". ");
        }
        if (success) {
            if (boxDNMap.size() > 0 && boxDNMap.containsKey(parentId)) {
                boxDNMap.remove(parentId);
            }
            session.removeAttribute(BOX_TO_SHOW);
            /*
                 * Copied from CreateDiscrepancyNoteServlet
                 * Setting a marker to check
                 * later while saving administrative edited data. This is needed to
                 * make sure the system flags error while changing data for items
                 * which already has a DiscrepanyNote
                 */
            manageReasonForChangeState(session, eventCRFId + "_" + field);
            String email = fp.getString(EMAIL_USER_ACCOUNT + parentId);
            if (dn.getAssignedUserId() > 0 && "1".equals(email.trim())) {
                logger.info("++++++ found our way here");
                // generate email for user here
                StringBuffer message = new StringBuffer();
                dn = getNoteInfo(dn);
                // generate message here
                EmailEngine em = new EmailEngine(EmailEngine.getSMTPHost());
                UserAccountDAO userAccountDAO = new UserAccountDAO(sm.getDataSource());
                ItemDAO itemDAO = new ItemDAO(sm.getDataSource());
                ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
                ItemBean item = new ItemBean();
                ItemDataBean itemData = new ItemDataBean();
                StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
                UserAccountBean assignedUser = (UserAccountBean) userAccountDAO.findByPK(dn.getAssignedUserId());
                String alertEmail = assignedUser.getEmail();
                message.append(MessageFormat.format(respage.getString("mailDNHeader"), assignedUser.getFirstName(), assignedUser.getLastName()));
                message.append("<A HREF='" + SQLInitServlet.getField("sysURL.base") + "ViewNotes?module=submit&listNotes_f_discrepancyNoteBean.user=" + assignedUser.getName() + "&listNotes_f_entityName=" + dn.getEntityName() + "'>" + SQLInitServlet.getField("sysURL.base") + "</A><BR/>");
                message.append(respage.getString("you_received_this_from"));
                StudyBean study = (StudyBean) studyDAO.findByPK(dn.getStudyId());
                if ("itemData".equalsIgnoreCase(entityType)) {
                    itemData = (ItemDataBean) iddao.findByPK(dn.getEntityId());
                    item = (ItemBean) itemDAO.findByPK(itemData.getItemId());
                }
                message.append(respage.getString("email_body_separator"));
                message.append(respage.getString("disc_note_info"));
                message.append(respage.getString("email_body_separator"));
                message.append(MessageFormat.format(respage.getString("mailDNParameters1"), dn.getDescription(), dn.getDetailedNotes(), ub.getName()));
                message.append(respage.getString("email_body_separator"));
                message.append(respage.getString("entity_information"));
                message.append(respage.getString("email_body_separator"));
                message.append(MessageFormat.format(respage.getString("mailDNParameters2"), study.getName(), dn.getSubjectName()));
                if (!("studySub".equalsIgnoreCase(entityType) || "subject".equalsIgnoreCase(entityType))) {
                    message.append(MessageFormat.format(respage.getString("mailDNParameters3"), dn.getEventName()));
                    if (!"studyEvent".equalsIgnoreCase(dn.getEntityType())) {
                        message.append(MessageFormat.format(respage.getString("mailDNParameters4"), dn.getCrfName()));
                        if (!"eventCrf".equalsIgnoreCase(dn.getEntityType())) {
                            message.append(MessageFormat.format(respage.getString("mailDNParameters6"), item.getName()));
                        }
                    }
                }
                message.append(respage.getString("email_body_separator"));
                message.append(MessageFormat.format(respage.getString("mailDNThanks"), study.getName()));
                message.append(respage.getString("email_body_separator"));
                message.append(respage.getString("disclaimer"));
                message.append(respage.getString("email_body_separator"));
                message.append(respage.getString("email_footer"));
                /*
                     *
                     *
                     *
                     * Please select the link below to view the information
                     * provided. You may need to login to
                     * OpenClinica_testbed with your user name and password
                     * after selecting the link. If you receive a page
                     * cannot be displayed message, please make sure to
                     * select the Change Study/Site link in the upper right
                     * table of the page, select the study referenced above,
                     * and select the link again.
                     *
                     * https://openclinica.s-3.com/OpenClinica_testbed/
                     * ViewSectionDataEntry ?ecId=117&sectionId=142&tabId=2
                     */
                String emailBodyString = message.toString();
                sendEmail(alertEmail.trim(), EmailEngine.getAdminEmail(), MessageFormat.format(respage.getString("mailDNSubject"), study.getName(), dn.getEntityName()), emailBodyString, true, null, null, true);
            }
            String close = fp.getString("close" + parentId);
            //session.setAttribute(CLOSE_WINDOW, "true".equals(close)?"true":"");
            if ("true".equals(close)) {
                addPageMessage(respage.getString("note_saved_into_db"));
                addPageMessage(respage.getString("page_close_automatically"));
                forwardPage(Page.ADD_DISCREPANCY_NOTE_SAVE_DONE);
                logger.info("Should forwardPage to ADD_DISCREPANCY_NOTE_SAVE_DONE.");
            } else {
                if (parentId == dn.getParentDnId()) {
                    mess.add(restext.getString("a_new_child_dn_added"));
                    results.put("newChildAdded" + parentId, mess);
                    setInputMessages(results);
                } else {
                    addPageMessage(restext.getString("a_new_dn_thread_added"));
                }
            }
        } else {
            session.setAttribute(BOX_TO_SHOW, parentId + "");
        }
    } else {
        setInputMessages(errors);
        boxDNMap.put(Integer.valueOf(parentId), dn);
        session.setAttribute(BOX_TO_SHOW, parentId + "");
    }
    session.setAttribute(BOX_DN_MAP, boxDNMap);
    viewNoteLink = this.appendPageFileName(viewNoteLink, "refresh", refresh + "");
    viewNoteLink = this.appendPageFileName(viewNoteLink, "y", ypos != null && ypos.length() > 0 ? ypos : "0");
    getServletContext().getRequestDispatcher(viewNoteLink).forward(request, response);
// forwardPage(Page.setNewPage(viewNoteLink, Page.VIEW_DISCREPANCY_NOTE.getTitle()));
}
Also used : DiscrepancyNoteDAO(org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO) ItemBean(org.akaza.openclinica.bean.submit.ItemBean) HashMap(java.util.HashMap) FormDiscrepancyNotes(org.akaza.openclinica.control.form.FormDiscrepancyNotes) ItemDAO(org.akaza.openclinica.dao.submit.ItemDAO) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) ArrayList(java.util.ArrayList) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) EmailEngine(org.akaza.openclinica.core.EmailEngine) ItemDataDAO(org.akaza.openclinica.dao.submit.ItemDataDAO) DiscrepancyNoteBean(org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean) ItemDataBean(org.akaza.openclinica.bean.submit.ItemDataBean) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) Validator(org.akaza.openclinica.control.form.Validator)

Example 28 with DiscrepancyNoteDAO

use of org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO in project OpenClinica by OpenClinica.

the class CreateDiscrepancyNoteServlet method processRequest.

@Override
protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
    List<DiscrepancyNoteType> types = DiscrepancyNoteType.list;
    request.setAttribute(DIS_TYPES, types);
    request.setAttribute(RES_STATUSES, ResolutionStatus.list);
    //this should be set based on a new property of DisplayItemBean
    boolean writeToDB = fp.getBoolean(WRITE_TO_DB, true);
    boolean isReasonForChange = fp.getBoolean(IS_REASON_FOR_CHANGE);
    int entityId = fp.getInt(ENTITY_ID);
    // subjectId has to be added to the database when disc notes area saved
    // as entity_type 'subject'
    int subjectId = fp.getInt(SUBJECT_ID);
    int itemId = fp.getInt(ITEM_ID);
    String entityType = fp.getString(ENTITY_TYPE);
    String field = fp.getString(ENTITY_FIELD);
    String column = fp.getString(ENTITY_COLUMN);
    int parentId = fp.getInt(PARENT_ID);
    //patch for repeating groups and RFC on empty fields
    int isGroup = fp.getInt(IS_GROUP_ITEM);
    //  request.setAttribute(IS_GROUP_ITEM, new Integer(isGroup));
    int eventCRFId = fp.getInt(EVENT_CRF_ID);
    request.setAttribute(EVENT_CRF_ID, new Integer(eventCRFId));
    int rowCount = fp.getInt(PARENT_ROW_COUNT);
    // run only once: try to recalculate writeToDB
    if (!StringUtils.isBlank(entityType) && "itemData".equalsIgnoreCase(entityType) && isGroup != 0 && eventCRFId != 0) {
        //  request.setAttribute(PARENT_ROW_COUNT, new Integer(eventCRFId));
        int ordinal_for_repeating_group_field = calculateOrdinal(isGroup, field, eventCRFId, rowCount);
        int writeToDBStatus = isWriteToDB(isGroup, field, entityId, itemId, ordinal_for_repeating_group_field, eventCRFId);
        writeToDB = (writeToDBStatus == -1) ? false : ((writeToDBStatus == 1) ? true : writeToDB);
    }
    boolean isInError = fp.getBoolean(ERROR_FLAG);
    boolean isNew = fp.getBoolean(NEW_NOTE);
    request.setAttribute(NEW_NOTE, isNew ? "1" : "0");
    String strResStatus = fp.getString(PRESET_RES_STATUS);
    if (!strResStatus.equals("")) {
        request.setAttribute(PRESET_RES_STATUS, strResStatus);
    }
    String monitor = fp.getString("monitor");
    String enterData = fp.getString("enterData");
    request.setAttribute("enterData", enterData);
    boolean enteringData = false;
    if (enterData != null && "1".equalsIgnoreCase(enterData)) {
        // variables are not set in JSP, so not from viewing data and from
        // entering data
        request.setAttribute(CAN_MONITOR, "1");
        request.setAttribute("monitor", monitor);
        enteringData = true;
    } else 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");
    }
    if ("itemData".equalsIgnoreCase(entityType) && enteringData) {
        request.setAttribute("enterItemData", "yes");
    }
    DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
    int preUserId = 0;
    if (!StringUtils.isBlank(entityType)) {
        if ("itemData".equalsIgnoreCase(entityType) || "itemdata".equalsIgnoreCase(entityType)) {
            ItemBean item = (ItemBean) new ItemDAO(sm.getDataSource()).findByPK(itemId);
            ItemDataBean itemData = (ItemDataBean) new ItemDataDAO(sm.getDataSource()).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();
        } else if ("studySub".equalsIgnoreCase(entityType)) {
            StudySubjectBean ssub = (StudySubjectBean) new StudySubjectDAO(sm.getDataSource()).findByPK(entityId);
            SubjectBean sub = (SubjectBean) new SubjectDAO(sm.getDataSource()).findByPK(ssub.getSubjectId());
            preUserId = ssub.getOwnerId();
            if (!StringUtils.isBlank(column)) {
                if ("enrollment_date".equalsIgnoreCase(column)) {
                    if (ssub.getEnrollmentDate() != null) {
                        request.setAttribute("entityValue", dateFormatter.format(ssub.getEnrollmentDate()));
                    } else {
                        request.setAttribute("entityValue", resword.getString("N/A"));
                    }
                    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()));
                    } else {
                        request.setAttribute("entityValue", resword.getString("N/A"));
                    }
                    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"));
                }
            }
        } else if ("subject".equalsIgnoreCase(entityType)) {
            SubjectBean sub = (SubjectBean) new SubjectDAO(sm.getDataSource()).findByPK(entityId);
            preUserId = sub.getOwnerId();
            if (!StringUtils.isBlank(column)) {
                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)) {
                    request.setAttribute("entityValue", sub.getUniqueIdentifier());
                    request.setAttribute("entityName", resword.getString("unique_identifier"));
                }
            }
        } else if ("studyEvent".equalsIgnoreCase(entityType)) {
            StudyEventBean se = (StudyEventBean) new StudyEventDAO(sm.getDataSource()).findByPK(entityId);
            preUserId = se.getOwnerId();
            if (!StringUtils.isBlank(column)) {
                if ("location".equalsIgnoreCase(column)) {
                    request.setAttribute("entityValue", se.getLocation().equals("") || se.getLocation() == null ? resword.getString("N/A") : 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()));
                    } else {
                        request.setAttribute("entityValue", resword.getString("N/A"));
                    }
                    request.setAttribute("entityName", resword.getString("start_date"));
                } else if ("end_date".equalsIgnoreCase(column)) {
                    if (se.getDateEnded() != null) {
                        request.setAttribute("entityValue", dateFormatter.format(se.getDateEnded()));
                    } else {
                        request.setAttribute("entityValue", resword.getString("N/A"));
                    }
                    request.setAttribute("entityName", resword.getString("end_date"));
                }
            }
        } else if ("eventCrf".equalsIgnoreCase(entityType)) {
            EventCRFBean ec = (EventCRFBean) new EventCRFDAO(sm.getDataSource()).findByPK(entityId);
            preUserId = ec.getOwnerId();
            if (!StringUtils.isBlank(column)) {
                if ("date_interviewed".equals(column)) {
                    if (ec.getDateInterviewed() != null) {
                        request.setAttribute("entityValue", dateFormatter.format(ec.getDateInterviewed()));
                    } else {
                        request.setAttribute("entityValue", resword.getString("N/A"));
                    }
                    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"));
                }
            }
        }
    }
    // finds all the related notes
    ArrayList notes = (ArrayList) dndao.findAllByEntityAndColumn(entityType, entityId, column);
    DiscrepancyNoteBean parent = new DiscrepancyNoteBean();
    if (parentId > 0) {
        dndao.setFetchMapping(true);
        parent = (DiscrepancyNoteBean) dndao.findByPK(parentId);
        if (parent.isActive()) {
            request.setAttribute("parent", parent);
        }
        dndao.setFetchMapping(false);
    }
    FormDiscrepancyNotes newNotes = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
    if (newNotes == null) {
        newNotes = new FormDiscrepancyNotes();
    }
    boolean isNotesExistInSession = (!newNotes.getNotes(field).isEmpty()) ? true : (!newNotes.getNotes(eventCRFId + "_" + field).isEmpty()) ? true : false;
    if (!notes.isEmpty() || isNotesExistInSession) {
        request.setAttribute("hasNotes", "yes");
    } else {
        request.setAttribute("hasNotes", "no");
        logger.debug("has notes:" + "no");
    }
    //only for adding a new thread
    if (currentRole.getRole().equals(Role.RESEARCHASSISTANT) || currentRole.getRole().equals(Role.RESEARCHASSISTANT2) || currentRole.getRole().equals(Role.INVESTIGATOR)) {
        ArrayList<ResolutionStatus> resStatuses = new ArrayList<ResolutionStatus>();
        resStatuses.add(ResolutionStatus.OPEN);
        resStatuses.add(ResolutionStatus.RESOLVED);
        request.setAttribute(RES_STATUSES, resStatuses);
        List<DiscrepancyNoteType> types2 = new ArrayList<DiscrepancyNoteType>(DiscrepancyNoteType.list);
        types2.remove(DiscrepancyNoteType.QUERY);
        request.setAttribute(DIS_TYPES, types2);
        request.setAttribute(WHICH_RES_STATUSES, "22");
    } 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_TYPES, types2);
    } else {
        //Role.STUDYDIRECTOR Role.COORDINATOR
        List<ResolutionStatus> resStatuses = new ArrayList<ResolutionStatus>(ResolutionStatus.list);
        resStatuses.remove(ResolutionStatus.NOT_APPLICABLE);
        request.setAttribute(RES_STATUSES, resStatuses);
        ;
        request.setAttribute(WHICH_RES_STATUSES, "2");
    }
    if (!fp.isSubmitted()) {
        DiscrepancyNoteBean dnb = new DiscrepancyNoteBean();
        if (subjectId > 0) {
            // BWP: this doesn't seem correct, because the SubjectId should
            // be the id for
            // the SubjectBean, different from StudySubjectBean
            StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
            StudySubjectBean ssub = (StudySubjectBean) ssdao.findByPK(subjectId);
            dnb.setSubjectName(ssub.getName());
            dnb.setSubjectId(ssub.getId());
            dnb.setStudySub(ssub);
            StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
            int parentStudyForSubject = 0;
            StudyBean studyBeanSub = (StudyBean) studyDAO.findByPK(ssub.getStudyId());
            if (null != studyBeanSub) {
                parentStudyForSubject = studyBeanSub.getParentStudyId();
            }
            if (ssub.getStudyId() != currentStudy.getId() && currentStudy.getId() != parentStudyForSubject) {
                addPageMessage(noAccessMessage);
                throw new InsufficientPermissionException(Page.MENU_SERVLET, exceptionName, "1");
            }
        }
        if (itemId > 0) {
            ItemBean item = (ItemBean) new ItemDAO(sm.getDataSource()).findByPK(itemId);
            dnb.setEntityName(item.getName());
            request.setAttribute("item", item);
        }
        dnb.setEntityType(entityType);
        dnb.setColumn(column);
        dnb.setEntityId(entityId);
        dnb.setField(field);
        dnb.setParentDnId(parent.getId());
        dnb.setCreatedDate(new Date());
        if (parent.getId() == 0 || isNew) {
            // no parent, new note thread
            if (enteringData) {
                if (isInError) {
                    dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.FAILEDVAL.getId());
                } else {
                    dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.ANNOTATION.getId());
                    dnb.setResolutionStatusId(ResolutionStatus.NOT_APPLICABLE.getId());
                // >> tbh WHO bug: set an assigned user for the parent
                // note
                // dnb.setAssignedUser(ub);
                // dnb.setAssignedUserId(ub.getId());
                // << tbh 08/2009
                }
                if (isReasonForChange) {
                    dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.REASON_FOR_CHANGE.getId());
                    dnb.setResolutionStatusId(ResolutionStatus.NOT_APPLICABLE.getId());
                }
                // << tbh 02/2010, trumps failed evaluation error checks
                // can we put this in admin editing
                request.setAttribute("autoView", "0");
            // above set to automatically open up the user panel
            } else {
                // when the user is a CRC and is adding a note to the thread
                // it should default to Resolution Proposed,
                // and the assigned should be the user who logged the query,
                // NOT the one who is proposing the solution, tbh 02/2009
                // if (currentRole.getRole().equals(Role.COORDINATOR)) {
                // dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.
                // REASON_FOR_CHANGE.getId());
                // request.setAttribute("autoView", "1");
                // // above set to automatically open up the user panel
                // } else {
                dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.QUERY.getId());
                //if (currentRole.getRole().equals(Role.RESEARCHASSISTANT) && currentStudy.getId() != currentStudy.getParentStudyId()
                if (currentRole.getRole().equals(Role.RESEARCHASSISTANT) || currentRole.getRole().equals(Role.RESEARCHASSISTANT2) || currentRole.getRole().equals(Role.INVESTIGATOR)) {
                    request.setAttribute("autoView", "0");
                } else {
                    request.setAttribute("autoView", "1");
                    dnb.setAssignedUserId(preUserId);
                }
            // above set to automatically open up the user panel
            // }
            }
        } else if (parent.getDiscrepancyNoteTypeId() > 0) {
            dnb.setDiscrepancyNoteTypeId(parent.getDiscrepancyNoteTypeId());
            // adding second rule here, tbh 08/2009
            if ((currentRole.getRole().equals(Role.RESEARCHASSISTANT) || currentRole.getRole().equals(Role.RESEARCHASSISTANT2)) && currentStudy.getId() != currentStudy.getParentStudyId()) {
                dnb.setResolutionStatusId(ResolutionStatus.RESOLVED.getId());
                request.setAttribute("autoView", "0");
            // hide the panel, tbh
            } else {
                dnb.setResolutionStatusId(ResolutionStatus.UPDATED.getId());
            }
        }
        dnb.setOwnerId(parent.getOwnerId());
        String detailedDes = fp.getString("strErrMsg");
        if (detailedDes != null) {
            dnb.setDetailedNotes(detailedDes);
            logger.debug("found strErrMsg: " + fp.getString("strErrMsg"));
        }
        // #4346 TBH 10/2009
        //If the data entry form has not been saved yet, collecting info from parent page.
        // populate note infos
        dnb = getNoteInfo(dnb);
        if (dnb.getEventName() == null || dnb.getEventName().equals("")) {
            if (!fp.getString("eventName").equals("")) {
                dnb.setEventName(fp.getString("eventName"));
            } else {
                dnb.setEventName(getStudyEventDefinition(eventCRFId).getName());
            }
        }
        if (dnb.getEventStart() == null) {
            if (fp.getDate("eventDate") != null) {
                dnb.setEventStart(fp.getDate("eventDate"));
            } else {
                dnb.setEventStart(getStudyEvent(eventCRFId).getDateStarted());
            }
        }
        if (dnb.getCrfName() == null || dnb.getCrfName().equals("")) {
            if (!fp.getString("crfName").equals("")) {
                dnb.setCrfName(fp.getString("crfName"));
            } else {
                dnb.setCrfName(getCrf(eventCRFId).getName());
            }
        }
        //            // #4346 TBH 10/2009
        request.setAttribute(DIS_NOTE, dnb);
        request.setAttribute("unlock", "0");
        //this should go from UI & here
        request.setAttribute(WRITE_TO_DB, writeToDB ? "1" : "0");
        ArrayList userAccounts = this.generateUserAccounts(ub.getActiveStudyId(), subjectId);
        request.setAttribute(USER_ACCOUNTS, userAccounts);
        // ideally should be only two cases
        if ((currentRole.getRole().equals(Role.RESEARCHASSISTANT) || currentRole.getRole().equals(Role.RESEARCHASSISTANT2)) && currentStudy.getId() != currentStudy.getParentStudyId()) {
            // assigning back to OP, tbh
            request.setAttribute(USER_ACCOUNT_ID, Integer.valueOf(parent.getOwnerId()).toString());
            logger.debug("assigned owner id: " + parent.getOwnerId());
        } else if (dnb.getEventCRFId() > 0) {
            logger.debug("found a event crf id: " + dnb.getEventCRFId());
            EventCRFDAO eventCrfDAO = new EventCRFDAO(sm.getDataSource());
            EventCRFBean eventCrfBean = new EventCRFBean();
            eventCrfBean = (EventCRFBean) eventCrfDAO.findByPK(dnb.getEventCRFId());
            request.setAttribute(USER_ACCOUNT_ID, Integer.valueOf(eventCrfBean.getOwnerId()).toString());
            logger.debug("assigned owner id: " + eventCrfBean.getOwnerId());
        } else {
        // the end case
        }
        // set the user account id for the user who completed data entry
        forwardPage(Page.ADD_DISCREPANCY_NOTE);
    } else {
        FormDiscrepancyNotes noteTree = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
        FormDiscrepancyNotes noteTree_RFC_REPEAT = (FormDiscrepancyNotes) session.getAttribute(FLAG_DISCREPANCY_RFC);
        ;
        if (noteTree_RFC_REPEAT == null)
            noteTree_RFC_REPEAT = new FormDiscrepancyNotes();
        if (noteTree == null) {
            noteTree = new FormDiscrepancyNotes();
            logger.debug("No note tree initailized in session");
        }
        Validator v = new Validator(request);
        String description = fp.getString("description");
        int typeId = fp.getInt("typeId");
        int assignedUserAccountId = fp.getInt(SUBMITTED_USER_ACCOUNT_ID);
        int resStatusId = fp.getInt(RES_STATUS_ID);
        String detailedDes = fp.getString("detailedDes");
        int sectionId = fp.getInt("sectionId");
        DiscrepancyNoteBean note = new DiscrepancyNoteBean();
        v.addValidation("description", Validator.NO_BLANKS);
        v.addValidation("description", Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 255);
        v.addValidation("detailedDes", Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 1000);
        v.addValidation("typeId", Validator.NO_BLANKS);
        HashMap errors = v.validate();
        note.setDescription(description);
        note.setDetailedNotes(detailedDes);
        note.setOwner(ub);
        note.setOwnerId(ub.getId());
        note.setCreatedDate(new Date());
        note.setResolutionStatusId(resStatusId);
        note.setDiscrepancyNoteTypeId(typeId);
        note.setParentDnId(parent.getId());
        if (typeId != DiscrepancyNoteType.ANNOTATION.getId() && typeId != DiscrepancyNoteType.FAILEDVAL.getId() && typeId != DiscrepancyNoteType.REASON_FOR_CHANGE.getId()) {
            if (assignedUserAccountId > 0) {
                note.setAssignedUserId(assignedUserAccountId);
                logger.debug("^^^ found assigned user id: " + assignedUserAccountId);
            } else {
                // a little bit of a workaround, should ideally be always from
                // the form
                note.setAssignedUserId(parent.getOwnerId());
                logger.debug("found user assigned id, in the PARENT OWNER ID: " + parent.getOwnerId() + " note that user assgined id did not work: " + assignedUserAccountId);
            }
        }
        note.setField(field);
        if (DiscrepancyNoteType.ANNOTATION.getId() == note.getDiscrepancyNoteTypeId()) {
            updateStudyEvent(entityType, entityId);
            updateStudySubjectStatus(entityType, entityId);
        }
        if (DiscrepancyNoteType.ANNOTATION.getId() == note.getDiscrepancyNoteTypeId() || DiscrepancyNoteType.REASON_FOR_CHANGE.getId() == note.getDiscrepancyNoteTypeId()) {
            note.setResStatus(ResolutionStatus.NOT_APPLICABLE);
            note.setResolutionStatusId(ResolutionStatus.NOT_APPLICABLE.getId());
        }
        if (DiscrepancyNoteType.FAILEDVAL.getId() == note.getDiscrepancyNoteTypeId() || DiscrepancyNoteType.QUERY.getId() == note.getDiscrepancyNoteTypeId()) {
            if (ResolutionStatus.NOT_APPLICABLE.getId() == note.getResolutionStatusId()) {
                Validator.addError(errors, RES_STATUS_ID, restext.getString("not_valid_res_status"));
            }
        }
        if (!parent.isActive()) {
            note.setEntityId(entityId);
            note.setEntityType(entityType);
            note.setColumn(column);
        } else {
            note.setEntityId(parent.getEntityId());
            note.setEntityType(parent.getEntityType());
            if (!StringUtils.isBlank(parent.getColumn())) {
                note.setColumn(parent.getColumn());
            } else {
                note.setColumn(column);
            }
            note.setParentDnId(parent.getId());
        }
        note.setStudyId(currentStudy.getId());
        // populate note infos
        note = getNoteInfo(note);
        request.setAttribute(DIS_NOTE, note);
        //this should go from UI & here
        request.setAttribute(WRITE_TO_DB, writeToDB ? "1" : "0");
        ArrayList userAccounts = this.generateUserAccounts(ub.getActiveStudyId(), subjectId);
        request.setAttribute(USER_ACCOUNT_ID, Integer.valueOf(note.getAssignedUserId()).toString());
        // formality more than anything else, we should go to say the note
        // is done
        Role r = currentRole.getRole();
        if (r.equals(Role.MONITOR) || r.equals(Role.INVESTIGATOR) || r.equals(Role.RESEARCHASSISTANT) || r.equals(Role.RESEARCHASSISTANT2) || r.equals(Role.COORDINATOR)) {
            // investigator
            request.setAttribute("unlock", "1");
            logger.debug("set UNLOCK to ONE");
        } else {
            request.setAttribute("unlock", "0");
            logger.debug("set UNLOCK to ZERO");
        }
        request.setAttribute(USER_ACCOUNTS, userAccounts);
        if (errors.isEmpty()) {
            if (!writeToDB) {
                noteTree.addNote(field, note);
                noteTree.addIdNote(note.getEntityId(), field);
                noteTree_RFC_REPEAT.addNote(EVENT_CRF_ID + "_" + field, note);
                noteTree_RFC_REPEAT.addIdNote(note.getEntityId(), field);
                //-> catcher                //   FORM_DISCREPANCY_NOTES_NAME
                session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, noteTree);
                session.setAttribute(FLAG_DISCREPANCY_RFC, noteTree_RFC_REPEAT);
                //
                /*Setting a marker to check later while saving administrative edited data. This is needed to make
                    * sure the system flags error while changing data for items which already has a DiscrepanyNote*/
                manageReasonForChangeState(session, eventCRFId + "_" + field);
                forwardPage(Page.ADD_DISCREPANCY_NOTE_DONE);
            } else {
                // if not creating a new thread(note), update exsiting notes
                // if necessary
                //if ("itemData".equalsIgnoreCase(entityType) && !isNew) {
                int pdnId = note != null ? note.getParentDnId() : 0;
                if (pdnId > 0) {
                    logger.debug("Create:find parent note for item data:" + note.getEntityId());
                    DiscrepancyNoteBean pNote = (DiscrepancyNoteBean) dndao.findByPK(pdnId);
                    logger.debug("setting DN owner id: " + pNote.getOwnerId());
                    note.setOwnerId(pNote.getOwnerId());
                    if (note.getDiscrepancyNoteTypeId() == pNote.getDiscrepancyNoteTypeId()) {
                        if (note.getResolutionStatusId() != pNote.getResolutionStatusId()) {
                            pNote.setResolutionStatusId(note.getResolutionStatusId());
                            dndao.update(pNote);
                        }
                        if (note.getAssignedUserId() != pNote.getAssignedUserId()) {
                            pNote.setAssignedUserId(note.getAssignedUserId());
                            if (pNote.getAssignedUserId() > 0) {
                                dndao.updateAssignedUser(pNote);
                            } else {
                                dndao.updateAssignedUserToNull(pNote);
                            }
                        }
                    }
                }
                note = (DiscrepancyNoteBean) dndao.create(note);
                dndao.createMapping(note);
                request.setAttribute(DIS_NOTE, note);
                if (note.getParentDnId() == 0) {
                    // see issue 2659 this is a new thread, we will create
                    // two notes in this case,
                    // This way one can be the parent that updates as the
                    // status changes, but one also stays as New.
                    note.setParentDnId(note.getId());
                    note = (DiscrepancyNoteBean) dndao.create(note);
                    dndao.createMapping(note);
                }
                /*Setting a marker to check later while saving administrative edited data. This is needed to make
                    * sure the system flags error while changing data for items which already has a DiscrepanyNote*/
                //session.setAttribute(DataEntryServlet.NOTE_SUBMITTED, true);
                //session.setAttribute(DataEntryServlet.NOTE_SUBMITTED, true);
                // String field_id_for_RFC_hash = buildDiscrepancyNoteIdForRFCHash(eventCRFId,entityId, isGroup, field, ordinal_for_repeating_group_field);
                String field_id_for_RFC_hash = eventCRFId + "_" + field;
                manageReasonForChangeState(session, field_id_for_RFC_hash);
                logger.debug("found resolution status: " + note.getResolutionStatusId());
                String email = fp.getString(EMAIL_USER_ACCOUNT);
                logger.debug("found email: " + email);
                if (note.getAssignedUserId() > 0 && "1".equals(email.trim()) && DiscrepancyNoteType.QUERY.getId() == note.getDiscrepancyNoteTypeId()) {
                    logger.debug("++++++ found our way here: " + note.getDiscrepancyNoteTypeId() + " id number and " + note.getDisType().getName());
                    // generate email for user here
                    StringBuffer message = new StringBuffer();
                    // generate message here
                    UserAccountDAO userAccountDAO = new UserAccountDAO(sm.getDataSource());
                    ItemDAO itemDAO = new ItemDAO(sm.getDataSource());
                    ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
                    ItemBean item = new ItemBean();
                    ItemDataBean itemData = new ItemDataBean();
                    SectionBean section = new SectionBean();
                    StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
                    UserAccountBean assignedUser = (UserAccountBean) userAccountDAO.findByPK(note.getAssignedUserId());
                    String alertEmail = assignedUser.getEmail();
                    message.append(MessageFormat.format(respage.getString("mailDNHeader"), assignedUser.getFirstName(), assignedUser.getLastName()));
                    message.append("<A HREF='" + SQLInitServlet.getField("sysURL.base") + "ViewNotes?module=submit&listNotes_f_discrepancyNoteBean.user=" + assignedUser.getName() + "&listNotes_f_entityName=" + note.getEntityName() + "'>" + SQLInitServlet.getField("sysURL.base") + "</A><BR/>");
                    message.append(respage.getString("you_received_this_from"));
                    StudyBean study = (StudyBean) studyDAO.findByPK(note.getStudyId());
                    SectionDAO sectionDAO = new SectionDAO(sm.getDataSource());
                    if ("itemData".equalsIgnoreCase(entityType)) {
                        itemData = (ItemDataBean) iddao.findByPK(note.getEntityId());
                        item = (ItemBean) itemDAO.findByPK(itemData.getItemId());
                        if (sectionId > 0) {
                            section = (SectionBean) sectionDAO.findByPK(sectionId);
                        } else {
                        //Todo section should be initialized when sectionId = 0
                        }
                    }
                    message.append(respage.getString("email_body_separator"));
                    message.append(respage.getString("disc_note_info"));
                    message.append(respage.getString("email_body_separator"));
                    message.append(MessageFormat.format(respage.getString("mailDNParameters1"), note.getDescription(), note.getDetailedNotes(), ub.getName()));
                    message.append(respage.getString("email_body_separator"));
                    message.append(respage.getString("entity_information"));
                    message.append(respage.getString("email_body_separator"));
                    message.append(MessageFormat.format(respage.getString("mailDNParameters2"), study.getName(), note.getSubjectName()));
                    if (!("studySub".equalsIgnoreCase(entityType) || "subject".equalsIgnoreCase(entityType))) {
                        message.append(MessageFormat.format(respage.getString("mailDNParameters3"), note.getEventName()));
                        if (!"studyEvent".equalsIgnoreCase(note.getEntityType())) {
                            message.append(MessageFormat.format(respage.getString("mailDNParameters4"), note.getCrfName()));
                            if (!"eventCrf".equalsIgnoreCase(note.getEntityType())) {
                                if (sectionId > 0) {
                                    message.append(MessageFormat.format(respage.getString("mailDNParameters5"), section.getName()));
                                }
                                message.append(MessageFormat.format(respage.getString("mailDNParameters6"), item.getName()));
                            }
                        }
                    }
                    message.append(respage.getString("email_body_separator"));
                    message.append(MessageFormat.format(respage.getString("mailDNThanks"), study.getName()));
                    message.append(respage.getString("email_body_separator"));
                    message.append(respage.getString("disclaimer"));
                    message.append(respage.getString("email_body_separator"));
                    message.append(respage.getString("email_footer"));
                    String emailBodyString = message.toString();
                    sendEmail(alertEmail.trim(), EmailEngine.getAdminEmail(), MessageFormat.format(respage.getString("mailDNSubject"), study.getName(), note.getEntityName()), emailBodyString, true, null, null, true);
                } else {
                    logger.debug("did not send email, but did save DN");
                }
                // addPageMessage(
                // "Your discrepancy note has been saved into database.");
                addPageMessage(respage.getString("note_saved_into_db"));
                addPageMessage(respage.getString("page_close_automatically"));
                forwardPage(Page.ADD_DISCREPANCY_NOTE_SAVE_DONE);
            }
        } else {
            if (parentId > 0) {
                if (note.getResolutionStatusId() == ResolutionStatus.NOT_APPLICABLE.getId()) {
                    request.setAttribute("autoView", "0");
                }
            } else {
                if (note.getDiscrepancyNoteTypeId() == DiscrepancyNoteType.QUERY.getId()) {
                    request.setAttribute("autoView", "1");
                } else {
                    request.setAttribute("autoView", "0");
                }
            }
            setInputMessages(errors);
            forwardPage(Page.ADD_DISCREPANCY_NOTE);
        }
    }
}
Also used : ItemBean(org.akaza.openclinica.bean.submit.ItemBean) ItemDAO(org.akaza.openclinica.dao.submit.ItemDAO) HashMap(java.util.HashMap) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) SubjectDAO(org.akaza.openclinica.dao.submit.SubjectDAO) ArrayList(java.util.ArrayList) InsufficientPermissionException(org.akaza.openclinica.web.InsufficientPermissionException) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) ItemDataDAO(org.akaza.openclinica.dao.submit.ItemDataDAO) ResolutionStatus(org.akaza.openclinica.bean.core.ResolutionStatus) DiscrepancyNoteType(org.akaza.openclinica.bean.core.DiscrepancyNoteType) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) ItemDataBean(org.akaza.openclinica.bean.submit.ItemDataBean) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) List(java.util.List) ArrayList(java.util.ArrayList) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) 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) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) Date(java.util.Date) Role(org.akaza.openclinica.bean.core.Role) SubjectBean(org.akaza.openclinica.bean.submit.SubjectBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) SectionBean(org.akaza.openclinica.bean.submit.SectionBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) DiscrepancyNoteBean(org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean) DateFormat(java.text.DateFormat) Validator(org.akaza.openclinica.control.form.Validator) SectionDAO(org.akaza.openclinica.dao.submit.SectionDAO)

Example 29 with DiscrepancyNoteDAO

use of org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO in project OpenClinica by OpenClinica.

the class DataEntryServlet method setToolTipEventNotes.

private void setToolTipEventNotes(HttpServletRequest request) {
    long t = System.currentTimeMillis();
    logMe("Method:setToolTipEventNotes" + t);
    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(getDataSource());
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);
    ArrayList<DiscrepancyNoteBean> ecNotes = dndao.findEventCRFDNotesToolTips(ecb);
    ArrayList<DiscrepancyNoteBean> nameNotes = new ArrayList();
    ArrayList<DiscrepancyNoteBean> dateNotes = new ArrayList();
    for (int i = 0; i < ecNotes.size(); i++) {
        DiscrepancyNoteBean dn = ecNotes.get(i);
        if (INTERVIEWER_NAME.equalsIgnoreCase(dn.getColumn())) {
            nameNotes.add(dn);
        }
        if (DATE_INTERVIEWED.equalsIgnoreCase(dn.getColumn())) {
            dateNotes.add(dn);
        }
    }
    request.setAttribute("nameNotes", nameNotes);
    request.setAttribute("intrvDates", dateNotes);
    logMe("existing Method:setToolTipEventNotes, time took" + (System.currentTimeMillis() - t));
}
Also used : DiscrepancyNoteDAO(org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) DiscrepancyNoteBean(org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean) ArrayList(java.util.ArrayList)

Example 30 with DiscrepancyNoteDAO

use of org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO in project OpenClinica by OpenClinica.

the class DataEntryServlet method getDiscrepancyNoteResolutionStatus.

/*Determining the resolution status that will be shown in color flag for an item.*/
private int getDiscrepancyNoteResolutionStatus(int itemDataId, ArrayList formNotes) {
    int resolutionStatus = 0;
    boolean hasOtherThread = false;
    int parentNotesNum = 0;
    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(getDataSource());
    ArrayList existingNotes = dndao.findExistingNotesForItemData(itemDataId);
    for (Object obj : existingNotes) {
        DiscrepancyNoteBean note = (DiscrepancyNoteBean) obj;
        /*We would only take the resolution status of the parent note of any note thread. If there
            * are more than one note thread, the thread with the worst resolution status will be taken.*/
        if (note.getParentDnId() == 0) {
            if (hasOtherThread) {
                if (resolutionStatus > note.getResolutionStatusId()) {
                    resolutionStatus = note.getResolutionStatusId();
                }
            } else {
                resolutionStatus = note.getResolutionStatusId();
            }
            hasOtherThread = true;
        }
    }
    if (formNotes == null || formNotes.isEmpty()) {
        return resolutionStatus;
    }
    for (Object obj : formNotes) {
        DiscrepancyNoteBean note = (DiscrepancyNoteBean) obj;
        if (note.getParentDnId() == 0) {
            if (hasOtherThread) {
                if (resolutionStatus > note.getResolutionStatusId()) {
                    resolutionStatus = note.getResolutionStatusId();
                }
            } else {
                resolutionStatus = note.getResolutionStatusId();
            }
            hasOtherThread = true;
        }
    }
    return resolutionStatus;
}
Also used : DiscrepancyNoteDAO(org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO) DiscrepancyNoteBean(org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean) ArrayList(java.util.ArrayList)

Aggregations

DiscrepancyNoteDAO (org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO)44 DiscrepancyNoteBean (org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean)34 ArrayList (java.util.ArrayList)32 StudySubjectDAO (org.akaza.openclinica.dao.managestudy.StudySubjectDAO)22 StudySubjectBean (org.akaza.openclinica.bean.managestudy.StudySubjectBean)20 EventCRFDAO (org.akaza.openclinica.dao.submit.EventCRFDAO)19 StudyEventBean (org.akaza.openclinica.bean.managestudy.StudyEventBean)18 Date (java.util.Date)17 StudyBean (org.akaza.openclinica.bean.managestudy.StudyBean)17 EventCRFBean (org.akaza.openclinica.bean.submit.EventCRFBean)17 FormProcessor (org.akaza.openclinica.control.form.FormProcessor)17 StudyDAO (org.akaza.openclinica.dao.managestudy.StudyDAO)17 StudyEventDAO (org.akaza.openclinica.dao.managestudy.StudyEventDAO)16 HashMap (java.util.HashMap)14 FormDiscrepancyNotes (org.akaza.openclinica.control.form.FormDiscrepancyNotes)13 StudyEventDefinitionDAO (org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO)13 StudyEventDefinitionBean (org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean)11 SubjectDAO (org.akaza.openclinica.dao.submit.SubjectDAO)11 EventDefinitionCRFDAO (org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO)10 ItemDataDAO (org.akaza.openclinica.dao.submit.ItemDataDAO)10