public ActionForward execute(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response)
      throws javax.servlet.ServletException, java.io.IOException {

    formErrors = new ArrayList();
    MiscCashReceiptsForm form = (MiscCashReceiptsForm) actionForm;
    ActionErrors errors = new ActionErrors();
    HttpSession session = request.getSession();
    DbUserSession sessionUser = SessionHelpers.getUserSession(request);
    DatabaseTransaction t = null;
    DbHistory dbHistory = null;

    if (form.getSubmitButton() != null && form.getSubmitButton().equals("exit")) {
      ActionForward actionForward = mapping.findForward("financial");
      return actionForward;
    }

    try {
      t = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser);
      // AppLog.trace("ProcessMiscCashReceipts submit ="+form.getSubmitButton());

      // --- HANDLE PRINTING A RECEIPT ---
      if (form.getFormId() != null
          && form.getFormId().trim().length() > 0
          && (!form.getFormId().equals("None"))) {
        // AppLog.trace("ProcessMiscCashReceipts printing receipt form: "+form.getFormId());
        if (FormatNumber.parseInteger(form.getFormId()) < 1) {
          // AppLog.error("ProcessMiscCashReceipts - No receipt type selected.");
          errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.tables.noselect"));
          formErrors.add("formId");
          t.closeConnection();
          return (new ActionForward(mapping.getInput()));
        }
      }

      if (form.getSubmitButton().equals("save")) {
        dbHistory = new DbHistory();
        dbHistory.setNew();
        validateData(form, errors);
        if (errors.isEmpty()) {
          setHistory(t, sessionUser, dbHistory, form, errors);
          if (errors.isEmpty()) {
            t.save();
          } else {
            // AppLog.criticalError("Exception in ProcessMiscCashReceipts.setHistory.");
          }
        } else {
          // AppLog.trace("Validation Errors in ProcessMiscCashReceipts; returning to
          // MiscCashReceipts form.");
        }
      }

      // --- HANDLE PRINTING A RECEIPT ---
      if (errors.isEmpty() && FormatNumber.parseInteger(form.getFormId()) > 0) {

        String crystalFlag =
            UtilSingleton.getInstance()
                .getProperty(sessionUser.getConfigID(), "CrystalServer.useReportingService");
        String pageName = null;

        if (crystalFlag != null && "true".equals(crystalFlag)) {
          CrystalReportManagerBean crystalServerReport =
              new CrystalReportManagerBean(sessionUser.getConfigID());
          pageName =
              crystalServerReport.printReport(
                  sessionUser,
                  FormatNumber.parseInteger(form.getFormId()),
                  "",
                  "",
                  null,
                  "",
                  Integer.toString(dbHistory.getId()),
                  true);
        } else {
          ExportReport crystal = new ExportReport();
          crystal.setRecordIdSelParam(dbHistory.getId()); // selection parameter
          pageName =
              crystal.printForm(
                  sessionUser,
                  FormatNumber.parseInteger(form.getFormId()),
                  "",
                  "",
                  null,
                  "",
                  request,
                  response,
                  servlet.getServletContext());
        }

        form = new MiscCashReceiptsForm();
        setNewForm(request, sessionUser, session, form, errors);
        form.setPreviewFile(pageName);
        // AppLog.trace("Setting miscCashReceipts collection arrays into session scope.");
        session.setAttribute("miscCashReceipts", form);
        ActionForward actionForward = mapping.findForward("showMiscCashReceipts");
        return actionForward;
      }

    } catch (PersistenceException pe) {
      logger.error("Persistence Exception in ProcessMiscCashReceipts.doPerform. " + pe);
      errors.add(
          ActionErrors.GLOBAL_ERROR, new ActionError("error.PersistenceException", pe.getCause()));
    } catch (Exception pe) {
      logger.error("Exception in ProcessMiscCashReceipts.doPerform. ", pe);
      errors.add(
          ActionErrors.GLOBAL_ERROR, new ActionError("error.GeneralException", pe.getMessage()));
    } finally {
      if (t != null) {
        t.closeConnection();
      }
    }

    // Action Forward Logic

    ActionForward actionForward = mapping.findForward("showMiscCashReceiptsGlobal");

    if (!errors.isEmpty()) {
      // AppLog.info("ProcessMiscCashReceipts Invoking forward mapping getInput() ");
      saveErrors(request, errors);
      request.setAttribute("formErrors", formErrors);
      actionForward = new ActionForward(mapping.getInput());
    }

    logger.debug("Leaving ProcessMiscCashReceipts.");
    return actionForward;
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response)
      throws javax.servlet.ServletException, java.io.IOException {

    logger.debug("********************************************");
    logger.debug("*** Entering ProcessFirstCallInformation ***");

    CemAnStatus form = (CemAnStatus) actionForm;
    ActionErrors errors = new ActionErrors();
    formErrors = new ArrayList();
    HttpSession session = request.getSession();
    DbUserSession sessionUser = (DbUserSession) session.getAttribute(SessionValueKeys.DB_USER);

    logger.debug("ExecutorSame request value : " + request.getParameter("executorSame"));

    DatabaseTransaction t = null;
    FdmsDb fdmsdb = null;
    DbVitalsDeceased deceased = null;
    DbVitalsInformant informant = null;
    DbVitalsFirstCall firstCall = null;
    DbCase caseinfo = null;
    DbVitalsNextKin nextkin = null;
    DbPreneed preneed = null;
    DbVitalsSchedule sched = null;
    DbVitalsExecutor executor = null;
    DbCemAtneed cematneed = null;
    boolean addmode = false;
    int vitalsid = 0;
    String directive = form.getDirective();

    // Try to set the vitalsid from the form.
    try {
      vitalsid = FormatNumber.parseInteger(form.getVitalsId());
    } catch (Exception e) {
      vitalsid = 0;
    }

    cematneed = new DbCemAtneed();
    cematneed.setNew();

    if (directive.equals("cancel")) {
      // go back to case status unless no vitalsid then, show introduction.
      vitalsid = SessionHelpers.getVitalsIdFromSession(request, sessionUser);
      if (vitalsid > 0) {
        return mapping.findForward("showCaseStatusGlobal");
      } else {
        return mapping.findForward("ShowIntroductionGlobal");
      }
    }

    if (directive.equals("help")) {
      return mapping.findForward("usingHelp");
    }

    // From this point, we need to access the database
    try {
      t = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser);
      fdmsdb = FdmsDb.getInstance();

      if (directive.equals("redisplay")) {
        redisplayForm(t, sessionUser, form, errors);
        form.setDirective(" ");
        session.setAttribute("cemAnStatus", form);
        return new ActionForward(mapping.getInput());
      }

      validateForm(t, sessionUser, form, errors);
      // if errors found, return to input screen without saving anything
      if (!errors.isEmpty()) {
        // AppLog.info("ProcessFirstCall Invoking forward mapping getInput() after validation.");
        saveErrors(request, errors);
        request.setAttribute("formErrors", formErrors);

        form.setDirective(" ");
        session.setAttribute("cemAnStatus", form);
        return new ActionForward(mapping.getInput());
      } else {
        // AppLog.trace("ProcessFirstCall past validation.");
      }

      // Get the DbVitalDeceased and DbVitalsFirstCall objects
      if (vitalsid == 0) {
        deceased = new DbVitalsDeceased();
        deceased.setNew();
        addmode = true;
      } else {
        deceased = fdmsdb.getVitalsDeceased(t, vitalsid);
      }

      // Set the data in the DbVitalsDeceased and DbVitalsFirstCall records
      setVitalsDeceased(deceased, informant, form, errors);
      // if errors found, return to input screen without saving anything
      if (!errors.isEmpty()) {
        // AppLog.info("ProcessFirstCall Invoking forward mapping getInput() after
        // setVitalsDeceased.");
        saveErrors(request, errors);
        request.setAttribute("formErrors", formErrors);
        session.setAttribute("cemAnStatus", form);
        form.setDirective(" ");
        return new ActionForward(mapping.getInput());
      } else {
        // AppLog.trace("ProcessFirstCall past setVitalsDeceased.");
      }

      if (vitalsid == 0) {
        t.addPersistent(deceased);
        t.save();
        t.closeConnection();
        t = null;

        vitalsid = deceased.getId();
        form.setVitalsId(String.valueOf(vitalsid));
        sessionUser.setCurrentCaseID(vitalsid);
        // Need another transaction to continue with add
        t = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser);
        // increment next contract number if user did not change it
        // and assign to this case
        // if user changed contract# then use the one they entered.
        if (form.getContractNumber().equals(form.getNextContractNumber())) {
          int newnextno =
              SessionHelpers.nextContractNumber(sessionUser.getDbLookup(), sessionUser.getRegion());
          form.setContractNumber(String.valueOf(newnextno));
          form.setNextContractNumber(form.getContractNumber());
          // need new transaction since save in above method ends that transaction
        }
        sched = fdmsdb.getVitalsSchedule(t, vitalsid);
        sched.setDefaultAtNeedCheckList(sessionUser.getRegion(), sessionUser.getDbLookup());
      } else {
        sched = fdmsdb.getVitalsSchedule(t, vitalsid);
      }

      // Now, lets update the other Vitals information
      SessionHelpers.setVitalsIdInRequest(request, vitalsid);
      firstCall = fdmsdb.getVitalsFirstCall(t, vitalsid);
      informant = fdmsdb.getVitalsInformant(t, vitalsid);
      caseinfo = fdmsdb.getCase(t, vitalsid);
      nextkin = fdmsdb.getVitalsNextKin(t, vitalsid);
      executor = fdmsdb.getVitalsExecutor(t, vitalsid);
      // cematneed = fdmsdb.getCemAtneed(t, vitalsid);
      if (executor == null) {
        executor = new DbVitalsExecutor();
        executor.setNew();
      }
      setVitalsRest(
          t,
          sessionUser,
          deceased,
          firstCall,
          informant,
          caseinfo,
          nextkin,
          executor,
          cematneed,
          form,
          errors);
      // if errors found, return to input screen without saving anything
      if (!errors.isEmpty()) {
        // AppLog.info("ProcessFirstCall Invoking forward mapping getInput() after setVitalsRest.");
        saveErrors(request, errors);
        request.setAttribute("formErrors", formErrors);
        session.setAttribute("cemAnStatus", form);
        form.setDirective(" ");
        return new ActionForward(mapping.getInput());
      } else {
        logger.debug("no errors exist in processfirstcall information");
        // AppLog.trace("ProcessFirstCall past setVitalsRest.");
      }

      // determine whether active preneed or deceased
      preneed = fdmsdb.getPreneed(t, vitalsid);
      String relation = "Deceased";
      if (preneed.getStatus().equals(DbPreneed.ACTIVE)) {
        relation = "Preneed";
      }
      t.removePersistent(preneed);

      // update special survivor information for searching deceased, informant, case#, contract#
      DbSurvivor.addUpdateSurvivor(
          t,
          vitalsid,
          DbSurvivor.DECEASED,
          deceased.getSalutation(),
          deceased.getDecFName(),
          deceased.getDecMName(),
          deceased.getDecLName(),
          deceased.getSuffix(),
          deceased.getMaidenName(),
          deceased.getFullName(),
          deceased.getDecResStreet() + " " + deceased.getDecAptNo(),
          "",
          deceased.getDecResMailCity(),
          deceased.getDecResState(),
          deceased.getDecResZip(),
          "",
          "",
          "",
          relation,
          "",
          "",
          "");
      DbSurvivor.addUpdateSurvivor(
          t,
          vitalsid,
          DbSurvivor.INFORMANT,
          informant.getSalutation(),
          informant.getFname(),
          informant.getMname(),
          informant.getLname(),
          "",
          "",
          "",
          informant.getStreet() + " " + informant.getRoad2() + " " + informant.getRoad3(),
          "",
          informant.getCity(),
          informant.getState(),
          informant.getZip(),
          informant.getPhone(),
          "",
          informant.getInformantEmail(),
          "Informant",
          "",
          "",
          "");
      DbSurvivor.addUpdateSurvivor(
          t,
          vitalsid,
          DbSurvivor.CONTRACT,
          "",
          deceased.getDecLName(),
          "",
          caseinfo.getContractCode(),
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          deceased.getDecFName(),
          "",
          "",
          "");
      DbSurvivor.addUpdateSurvivor(
          t,
          vitalsid,
          DbSurvivor.CASECODE,
          "",
          deceased.getDecLName(),
          "",
          caseinfo.getCaseCode(),
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          deceased.getDecFName(),
          "",
          "",
          "");

      // add informant and next-of-kin as normal survivors but only during add cycle
      if (addmode) {
        // AppLog.trace("Adding informant and NOK as survivors.");
        DbSurvivor infsurv =
            new DbSurvivor(
                vitalsid,
                informant.getSalutation(),
                informant.getFname(),
                informant.getMname(),
                informant.getLname(),
                "",
                "",
                "",
                informant.getStreet() + " " + informant.getRoad2() + " " + informant.getRoad3(),
                "",
                informant.getCity(),
                informant.getState(),
                informant.getZip(),
                informant.getPhone(),
                "",
                informant.getInformantEmail(),
                informant.getRelated(),
                "",
                "",
                "",
                "");
        t.addPersistent(infsurv);
        if (!form.getNextKinSame()) {
          DbSurvivor noksurv =
              new DbSurvivor(
                  vitalsid,
                  nextkin.getSalutation(),
                  nextkin.getFirstname(),
                  "",
                  nextkin.getLastname(),
                  "",
                  "",
                  "",
                  nextkin.getStreet() + nextkin.getRoad2() + " " + nextkin.getRoad3(),
                  "",
                  nextkin.getCity(),
                  nextkin.getState(),
                  nextkin.getZip(),
                  nextkin.getPhone(),
                  "",
                  "",
                  nextkin.getRelation(),
                  "",
                  "",
                  "",
                  "");
          t.addPersistent(noksurv);
        }
      }
      t.addPersistent(cematneed);

      if (executor != null) t.addPersistent(executor);

      // Final commit and cleanup
      t.save();

    } catch (PersistenceException pe) {
      logger.error("PersistenceException in doPerform() : ", pe);
      errors.add(
          ActionErrors.GLOBAL_ERROR, new ActionError("error.PersistenceException", pe.getCause()));
    } catch (Exception pe) {
      logger.error("Error in doPerform() : ", pe);
      errors.add(
          ActionErrors.GLOBAL_ERROR, new ActionError("error.GeneralException", pe.getMessage()));
    } finally {
      if (t != null) {
        try {
          t.closeConnection();
          t = null;
        } catch (Exception e) {
          logger.error("Error in closeConnection() : ", e);
        }
      }
    }

    if (!errors.isEmpty()) {
      // AppLog.info("ProcessFirstCallInformation Invoking forward mapping getInput().");
      saveErrors(request, errors);
      request.setAttribute("formErrors", formErrors);
      form.setDirective(" ");
      session.setAttribute("cemAnStatus", form);
      return (new ActionForward(mapping.getInput()));
    }

    // remove session variables used in FirstCall page
    SessionHelpers.removeArrangerListFromSession(request);
    SessionHelpers.removeChapelListInSession(request);
    session.removeAttribute("cemAnStatus");
    SessionHelpers.setVitalsIdInRequest(request, vitalsid);

    // Since we are forwarding to another ACTION, need to go through this exercise
    /*	ActionMappings mappings = mapping.getMappings();
           String returnPath = actionForward.getPath();
           int periodpos = returnPath.indexOf(".do");
           returnPath = returnPath.substring(0,periodpos);
           ActionMapping finalMapping = mappings.findMapping(returnPath);
           Action finalAction = null;

           try {
               Class clazz = Class.forName(finalMapping.getType());
               finalAction = (Action) clazz.newInstance();
               AppLog.trace("chaining to:"+finalAction.toString());
           } catch (Exception e) {
               AppLog.warning("Could not find chained action: " + e.getMessage());
               return forwardGlobalCancel(mapping) ;
           }

           return finalAction.perform(finalMapping,form,request,response);
    */
    // return forwardShowCaseStatusGlobal(mapping);

    if (errors.isEmpty()) {
      request.setAttribute("redirect", Boolean.TRUE);
      request.setAttribute("vitalsId", new Integer(vitalsid));
    }
    return new ActionForward(mapping.getInput());
  }
  /**
   * Called from ProcessMiscCashReceipts, this Method sets the History record from the
   * MiscCashReceipts form values. If am error occurs, the error is stored in the errors collection.
   * Creation date: (8/13/2002 3:41:43 PM)
   */
  public void setHistory(
      DatabaseTransaction t,
      DbUserSession sessionUser,
      DbHistory dbHistory,
      fdms.ui.struts.form.MiscCashReceiptsForm form,
      ActionErrors errors) {

    String errorField = new String();
    String formField = null;
    DbLocale userlocale = null;
    DatabaseTransaction tlocale = null;
    int receiptNumber = 0;

    try {

      errorField = "VitalsMasterKey";
      dbHistory.setLMainKey(0);

      errorField = "ARAcct";
      formField = "arAcct";
      dbHistory.setCHistARacct(form.getArAcct());

      errorField = "Date";
      formField = "dateOfTran";
      dbHistory.setCHistDate(
          new java.sql.Date(FormatDate.convertToDate(form.getDateOfTran()).getTime()));

      errorField = "Description";
      formField = "description";
      dbHistory.setCHistDesc(form.getDescription());

      errorField = "GLAcct";
      formField = "glAcct";
      dbHistory.setCHistGLAcct(form.getGlAcct());

      errorField = "ManualReceipt";
      formField = "manualReceiptNo";
      dbHistory.setCHistManualReceipt(form.getManualReceiptNo());

      errorField = "OriginalPosting";
      formField = "";
      dbHistory.setCHistOriginalPosting('N');

      errorField = "PayMethod";
      formField = "getPayMethod";
      dbHistory.setCHistPayMethod(form.getPayMethod());

      errorField = "Posted";
      formField = "";
      dbHistory.setCHistPosted('N');

      errorField = "SPF";
      formField = "";
      dbHistory.setCHistSPF('R');

      // Set Receipt Number from locale
      try {
        tlocale = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser);
        userlocale = FdmsDb.getInstance().getLocaleWithLock(tlocale, sessionUser.getRegion());
        if (userlocale == null) {
          throw new java.sql.SQLException("No locale for user region.");
        }
        receiptNumber = userlocale.getNextReceiptNo();
        userlocale.setNextReceiptNo(receiptNumber + 1);
        tlocale.addPersistent(userlocale);
        tlocale.save();
        // AppLog.trace("ProcessMiscCashReceipts: next receipt number = " +receiptNumber);

      } catch (java.sql.SQLException e) {
        if (e.getErrorCode() == 1205) {
          // AppLog.warning("ProcessMiscCashReceipts - DbLocale locked from updating."
          // +sessionUser.getRegion());
          throw new PersistenceException("User locale temporarily locked. Try again.");
        }
        // AppLog.warning("ProcessMiscCashReceipts - invalid region for user "
        // +sessionUser.getUserName());
        throw new PersistenceException("Invalid region for user", e);
      } finally {
        if (t != null) {
          t.closeConnection();
        }
      }

      errorField = "ReceiptNo";
      dbHistory.setLHistReceiptNo(receiptNumber);

      errorField = "Amount";
      dbHistory.setLHistAmount(
          FormatNumber.parseInteger(
              String.valueOf(FormatCurrency.convertToCurrency(form.getAmountOfTran()))));

      errorField = "LocationId";
      dbHistory.setLocationId(Integer.parseInt(form.getLocationId()));

      t.addPersistent(dbHistory);

    } catch (Exception e) {
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.set" + errorField));
      formErrors.add(formField);
    }

    return;
  }