private DiscrepancyNote createQuery(QueryServiceHelperBean helperBean, QueryBean queryBean)
      throws Exception {
    DiscrepancyNote dn = new DiscrepancyNote();
    dn.setStudy(helperBean.getContainer().getStudy());
    dn.setEntityType("itemData");
    dn.setDescription("description");

    dn.setDetailedNotes(queryBean.getComment());
    dn.setDiscrepancyNoteType(new DiscrepancyNoteType(3));

    if (queryBean.getStatus().equals("new")) {
      dn.setResolutionStatus(resolutionStatusDao.findById(1));
    } else if (queryBean.getStatus().equals("updated")) {
      dn.setResolutionStatus(resolutionStatusDao.findById(2));
    } else if (queryBean.getStatus().equals("closed")) {
      dn.setResolutionStatus(resolutionStatusDao.findById(4));
    }

    String assignedTo = queryBean.getAssigned_to();
    if (!StringUtils.isEmpty(assignedTo)) {
      int endIndex = assignedTo.indexOf(")");
      int begIndex = assignedTo.indexOf("(");
      String userName = assignedTo.substring(begIndex + 1, endIndex);
      UserAccount userAccount = userAccountDao.findByUserName(userName);
      helperBean.setUserAccount(userAccount);
      dn.setUserAccount(userAccount);
    }
    dn.setUserAccountByOwnerId(helperBean.getContainer().getUser());
    // create itemData when a query is created without an autosaved itemdata
    if (helperBean.getItemData() == null) {
      helperBean.setItemData(createBlankItemData(helperBean));
    }
    dn.setDateCreated(new Date());
    return dn;
  }
 private ItemData getItemData(QueryServiceHelperBean helperBean) {
   ItemData id =
       itemDataDao.findByEventCrfItemName(
           helperBean.getContainer().getEventCrf().getEventCrfId(),
           helperBean.getParentElementName(),
           helperBean.getItemOrdinal());
   return id;
 }
  private void updateParentQuery(QueryServiceHelperBean helperBean) {
    if (helperBean.getDn().getParentDiscrepancyNote() == null) return;

    DiscrepancyNote itemParentNote =
        discrepancyNoteDao.findByDiscrepancyNoteId(
            helperBean.getDn().getParentDiscrepancyNote().getDiscrepancyNoteId());
    itemParentNote.setResolutionStatus(helperBean.getResStatus());
    discrepancyNoteDao.saveOrUpdate(itemParentNote);
  }
 private ItemData createBlankItemData(QueryServiceHelperBean helperBean) {
   Item item =
       itemDao.findByNameCrfId(
           helperBean.getParentElementName(),
           helperBean.getContainer().getCrfVersion().getCrf().getCrfId());
   ItemData itemData = new ItemData();
   itemData.setItem(item);
   itemData.setEventCrf(helperBean.getContainer().getEventCrf());
   itemData.setValue("");
   itemData.setDateCreated(new Date());
   itemData.setStatus(Status.AVAILABLE);
   // TODO this value should change once you have an ordinal attribute specified in the query
   itemData.setOrdinal(helperBean.getItemOrdinal());
   itemData.setUserAccount(helperBean.getUserAccount());
   itemData.setDeleted(false);
   itemDataDao.saveOrUpdate(itemData);
   return itemData;
 }
  private void saveQueryItemDatamap(QueryServiceHelperBean helperBean) {
    // Create Mapping for new Discrepancy Note
    DnItemDataMapId dnItemDataMapId = new DnItemDataMapId();
    dnItemDataMapId.setDiscrepancyNoteId(helperBean.getDn().getDiscrepancyNoteId());
    dnItemDataMapId.setItemDataId(helperBean.getItemData().getItemDataId());
    dnItemDataMapId.setStudySubjectId(helperBean.getContainer().getSubject().getStudySubjectId());
    dnItemDataMapId.setColumnName("value");

    DnItemDataMap mapping = new DnItemDataMap();
    mapping.setDnItemDataMapId(dnItemDataMapId);
    mapping.setItemData(helperBean.getItemData());
    mapping.setStudySubject(helperBean.getContainer().getSubject());
    mapping.setActivated(false);
    mapping.setDiscrepancyNote(helperBean.getDn());
    dnItemDataMapDao.saveOrUpdate(mapping);
    // updateParentQuery(helperBean);
  }
  @Override
  public void process(
      QueryServiceHelperBean helperBean,
      SubmissionContainer container,
      Node itemNode,
      int itemOrdinal)
      throws Exception {
    helperBean.setContainer(container);
    helperBean.setItemOrdinal(itemOrdinal);
    helperBean.setItemNode(itemNode);
    helperBean.setItemData(getItemData(helperBean));
    // helperBean.setResStatus(resolutionStatusDao.findByResolutionStatusId(1));
    QueriesBean queries = null;
    try {
      ObjectMapper objectMapper = new ObjectMapper();
      queries = objectMapper.readValue(itemNode.getTextContent(), QueriesBean.class);
    } catch (IOException e) {
      logger.error(e.getMessage());
      throw e;
    }

    List<Integer> idList = new ArrayList();
    List<QueryBean> qBeans = queries.getQueries();
    QueryBean queryBean = null;
    DiscrepancyNote childDN = null;
    DiscrepancyNote parentDN = null;

    if (qBeans.size() == 1) {
      queryBean = qBeans.get(0);
      // this is the first entry , expected to build 2 records in DN table, one parent, the other
      // child
      parentDN = createQuery(helperBean, queryBean);
      parentDN = discrepancyNoteDao.saveOrUpdate(parentDN);

      childDN = createQuery(helperBean, queryBean);
      childDN.setParentDiscrepancyNote(parentDN);
      childDN = discrepancyNoteDao.saveOrUpdate(childDN);

      parentDN.setUserAccount(childDN.getUserAccount());
      parentDN = discrepancyNoteDao.saveOrUpdate(parentDN);
      helperBean.setDn(parentDN);
      saveQueryItemDatamap(helperBean);

    } else if (qBeans.size() > 1) {
      for (QueryBean qBean : qBeans) {
        idList.add(Integer.valueOf(qBean.getId()));
      }
      Collections.reverse(idList);
      queryBean = qBeans.get(0);

      // Enketo passes JSON "id" attribute for unsubmitted queries only
      // if (StringUtils.isEmpty(queryBean.getId())){

      childDN = createQuery(helperBean, queryBean);
      childDN.setParentDiscrepancyNote(findQueryParent(helperBean));
      childDN = discrepancyNoteDao.saveOrUpdate(childDN);

      parentDN = findQueryParent(helperBean);
      parentDN.setUserAccount(childDN.getUserAccount());
      parentDN = discrepancyNoteDao.saveOrUpdate(parentDN);
    }
    helperBean.setDn(childDN);
    saveQueryItemDatamap(helperBean);
    handleEmailNotification(helperBean, queryBean);
  }
  private void prepareEmail(QueryServiceHelperBean helperBean) throws Exception {
    StringBuffer message = new StringBuffer();

    message.append(
        MessageFormat.format(
            respage.getString("mailDNHeader"),
            helperBean.getUserAccount().getFirstName(),
            helperBean.getUserAccount().getLastName()));
    message.append(
        "<A HREF='"
            + SQLInitServlet.getField("sysURL.base")
            + "ViewNotes?module=submit&listNotes_f_discrepancyNoteBean.user="******"&listNotes_f_entityName="
            + helperBean.getParentElementName()
            + "'>"
            + SQLInitServlet.getField("sysURL.base")
            + "</A><BR/>");
    message.append(respage.getString("you_received_this_from"));
    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"),
            helperBean.getDn().getDescription(),
            helperBean.getDn().getDetailedNotes(),
            helperBean.getUserAccount().getUserName()));
    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"),
            helperBean.getDn().getStudy().getName(),
            helperBean.getDn().getDescription()));

    if (!("studySub".equalsIgnoreCase(helperBean.getDn().getEntityType())
        || "subject".equalsIgnoreCase(helperBean.getDn().getEntityType()))) {
      message.append(
          MessageFormat.format(
              respage.getString("mailDNParameters3"),
              helperBean.getContainer().getStudyEvent().getStudyEventDefinition().getName()));
      if (!"studyEvent".equalsIgnoreCase(helperBean.getDn().getEntityType())) {
        message.append(
            MessageFormat.format(
                respage.getString("mailDNParameters4"),
                helperBean.getContainer().getCrfVersion().getCrf().getName()));
        if (!"eventCrf".equalsIgnoreCase(helperBean.getDn().getEntityType())) {
          message.append(
              MessageFormat.format(
                  respage.getString("mailDNParameters6"), helperBean.getParentElementName()));
        }
      }
    }

    message.append(respage.getString("email_body_separator"));
    message.append(
        MessageFormat.format(
            respage.getString("mailDNThanks"), helperBean.getDn().getStudy().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 subject =
        MessageFormat.format(
            respage.getString("mailDNSubject"),
            helperBean.getDn().getStudy().getName(),
            helperBean.getParentElementName());

    String emailBodyString = message.toString();
    try {
      sendEmail(helperBean.getUserAccount().getEmail().trim(), subject, emailBodyString, true);
    } catch (Exception e) {
      logger.error(e.getMessage());
      throw e;
    }
  }
 public String getQueryAttribute(QueryServiceHelperBean helperBean, Node itemNode) {
   helperBean.setItemNode(itemNode);
   helperBean.setParentElementName(QueryService.super.getQueryAttribute(helperBean, itemNode));
   return helperBean.getParentElementName();
 }
 private DiscrepancyNote findQueryParent(QueryServiceHelperBean helperBean) {
   DiscrepancyNote parentDiscrepancyNote =
       discrepancyNoteDao.findParentQueryByItemData(helperBean.getItemData().getItemDataId());
   return parentDiscrepancyNote;
 }