private void generatePositionsFromExistingCustomerPositions(
      CustomerBO customer,
      List<PositionEntity> customerPositions,
      List<CustomerPositionDto> customerPositionDtos) {
    for (PositionEntity position : customerPositions) {
      for (CustomerPositionEntity entity : customer.getCustomerPositions()) {
        if (position.getId().equals(entity.getPosition().getId())) {

          CustomerPositionDto customerPosition;
          if (entity.getCustomer() != null) {
            customerPosition =
                new CustomerPositionDto(
                    entity.getCustomer().getCustomerId(),
                    entity.getPosition().getId(),
                    entity.getPosition().getName());
          } else {
            customerPosition =
                new CustomerPositionDto(
                    customer.getCustomerId(),
                    entity.getPosition().getId(),
                    entity.getPosition().getName());
          }

          customerPositionDtos.add(customerPosition);
        }
      }
    }
  }
  @Override
  public void createCustomerNote(CustomerNoteFormDto customerNoteForm) {

    MifosUser user =
        (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    CustomerBO customer = this.customerDao.findCustomerBySystemId(customerNoteForm.getGlobalNum());
    customer.updateDetails(userContext);

    PersonnelBO loggedInUser = this.personnelDao.findPersonnelById(userContext.getId());

    CustomerNoteEntity customerNote =
        new CustomerNoteEntity(
            customerNoteForm.getComment(),
            new DateTimeService().getCurrentJavaSqlDate(),
            loggedInUser,
            customer);
    customer.addCustomerNotes(customerNote);

    try {
      this.transactionHelper.startTransaction();
      this.customerDao.save(customer);
      this.transactionHelper.commitTransaction();
    } catch (Exception e) {
      this.transactionHelper.rollbackTransaction();
      throw new BusinessRuleException(customer.getCustomerAccount().getAccountId().toString(), e);
    } finally {
      this.transactionHelper.closeSession();
    }
  }
Example #3
0
  @CloseSession
  @TransactionDemarcate(validateAndResetToken = true)
  public ActionForward removeGroupMemberShip(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      @SuppressWarnings("unused") HttpServletResponse response)
      throws Exception {

    GroupTransferActionForm actionForm = (GroupTransferActionForm) form;
    CustomerBO customerBOInSession =
        (CustomerBO) SessionUtils.getAttribute(Constants.BUSINESS_KEY, request);
    ClientBO client = this.customerDao.findClientBySystemId(customerBOInSession.getGlobalCustNum());

    checkVersionMismatch(customerBOInSession.getVersionNo(), client.getVersionNo());

    Short loanOfficerId = null;
    if (StringUtils.isNotBlank(actionForm.getAssignedLoanOfficerId())) {
      loanOfficerId = Short.valueOf(actionForm.getAssignedLoanOfficerId());
    }

    this.clientServiceFacade.removeGroupMembership(
        customerBOInSession.getGlobalCustNum(), loanOfficerId, actionForm.getComment());

    return mapping.findForward(ActionForwards.view_client_details_page.toString());
  }
  @Override
  public CustomerChargesDetailsDto retrieveChargesDetails(Integer customerId) {

    MifosUser mifosUser =
        (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = new UserContextFactory().create(mifosUser);

    CustomerBO customerBO = this.customerDao.findCustomerById(customerId);
    CustomerAccountBO customerAccount = customerBO.getCustomerAccount();

    List<AccountFeesDto> accountFeesDtos = new ArrayList<AccountFeesDto>();
    if (!customerAccount.getAccountFees().isEmpty()) {
      for (AccountFeesEntity accountFeesEntity : customerAccount.getAccountFees()) {
        AccountFeesDto accountFeesDto =
            new AccountFeesDto(
                accountFeesEntity.getFees().getFeeFrequency().getFeeFrequencyType().getId(),
                (accountFeesEntity.getFees().getFeeFrequency().getFeePayment() != null
                    ? accountFeesEntity.getFees().getFeeFrequency().getFeePayment().getId()
                    : null),
                accountFeesEntity.getFeeStatus(),
                accountFeesEntity.getFees().getFeeName(),
                accountFeesEntity.getAccountFeeAmount().toString(),
                getMeetingRecurrence(
                    accountFeesEntity.getFees().getFeeFrequency().getFeeMeetingFrequency(),
                    userContext),
                accountFeesEntity.getFees().getFeeId());
        accountFeesDtos.add(accountFeesDto);
      }
    }

    CustomerScheduleDto customerSchedule = null;
    CustomerScheduleEntity scheduleEntity =
        (CustomerScheduleEntity) customerAccount.getUpcomingInstallment();
    if (scheduleEntity != null) {
      Set<AccountFeesActionDetailEntity> feeEntities = scheduleEntity.getAccountFeesActionDetails();

      List<AccountFeeScheduleDto> feeDtos = new ArrayList<AccountFeeScheduleDto>();
      for (AccountFeesActionDetailEntity feeEntity : feeEntities) {
        feeDtos.add(convertToDto(feeEntity));
      }

      customerSchedule =
          new CustomerScheduleDto(
              scheduleEntity.getMiscFee().toString(),
              scheduleEntity.getMiscFeePaid().toString(),
              scheduleEntity.getMiscPenalty().toString(),
              scheduleEntity.getMiscPenaltyPaid().toString(),
              feeDtos);
    }

    return new CustomerChargesDetailsDto(
        customerAccount.getNextDueAmount().toString(),
        customerAccount.getTotalAmountInArrears().toString(),
        customerAccount.getTotalAmountDue().toString(),
        customerAccount.getUpcomingChargesDate(),
        customerSchedule,
        accountFeesDtos);
  }
  @SuppressWarnings("deprecation")
  private CustomerAccountView getCustomerAccountView(final CustomerBO customer) {
    CustomerAccountView customerAccountView =
        new CustomerAccountView(customer.getCustomerAccount().getAccountId(), getCurrency());

    List<AccountActionDateEntity> accountAction = new ArrayList<AccountActionDateEntity>();
    accountAction.add(customer.getCustomerAccount().getAccountActionDate(Short.valueOf("1")));
    customerAccountView.setAccountActionDates(
        TestObjectFactory.getBulkEntryAccountActionViews(accountAction));
    customerAccountView.setCustomerAccountAmountEntered("100.0");
    customerAccountView.setValidCustomerAccountAmountEntered(true);
    return customerAccountView;
  }
  @Override
  public List<CustomerRecentActivityDto> retrieveAllAccountActivity(String globalCustNum) {
    List<CustomerRecentActivityDto> customerActivityViewList =
        new ArrayList<CustomerRecentActivityDto>();

    CustomerBO customerBO = this.customerDao.findCustomerBySystemId(globalCustNum);
    List<CustomerActivityEntity> customerActivityDetails =
        customerBO.getCustomerAccount().getCustomerActivitDetails();

    for (CustomerActivityEntity customerActivityEntity : customerActivityDetails) {
      customerActivityViewList.add(
          assembleCustomerActivityDto(customerActivityEntity, Locale.getDefault()));
    }
    return customerActivityViewList;
  }
Example #7
0
 private void setFormAttributes(UserContext userContext, ActionForm form, CustomerBO customerBO)
     throws ApplicationException, InvalidDateException {
   CustomerNotesActionForm notesActionForm = (CustomerNotesActionForm) form;
   notesActionForm.setLevelId(customerBO.getCustomerLevel().getId().toString());
   notesActionForm.setGlobalCustNum(customerBO.getGlobalCustNum());
   notesActionForm.setCustomerName(customerBO.getDisplayName());
   notesActionForm.setCommentDate(DateUtils.getCurrentDate(userContext.getPreferredLocale()));
   if (customerBO instanceof CenterBO) {
     notesActionForm.setInput("center");
   } else if (customerBO instanceof GroupBO) {
     notesActionForm.setInput("group");
   } else if (customerBO instanceof ClientBO) {
     notesActionForm.setInput("client");
   }
 }
 private CustomerView getCusomerView(final CustomerBO customer) {
   CustomerView customerView = new CustomerView();
   customerView.setCustomerId(customer.getCustomerId());
   customerView.setCustomerLevelId(customer.getCustomerLevel().getId());
   customerView.setCustomerSearchId(customer.getSearchId());
   customerView.setDisplayName(customer.getDisplayName());
   customerView.setGlobalCustNum(customer.getGlobalCustNum());
   customerView.setOfficeId(customer.getOffice().getOfficeId());
   if (null != customer.getParentCustomer()) {
     customerView.setParentCustomerId(customer.getParentCustomer().getCustomerId());
   }
   customerView.setPersonnelId(customer.getPersonnel().getPersonnelId());
   customerView.setStatusId(customer.getCustomerStatus().getId());
   return customerView;
 }
  @Test
  public void testGetAllClosedAccounts() throws Exception {
    createInitialObjects();
    MeetingBO meetingIntCalc =
        TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
    MeetingBO meetingIntPost =
        TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());

    Date startDate = new Date(System.currentTimeMillis());
    savingsOffering =
        TestObjectFactory.createSavingsProduct(
            "SavingPrd1",
            ApplicableTo.GROUPS,
            new Date(System.currentTimeMillis()),
            PrdStatus.SAVINGS_ACTIVE,
            300.0,
            RecommendedAmountUnit.PER_INDIVIDUAL,
            1.2,
            200.0,
            200.0,
            SavingsType.VOLUNTARY,
            InterestCalcType.MINIMUM_BALANCE,
            meetingIntCalc,
            meetingIntPost);
    savings =
        TestObjectFactory.createSavingsAccount(
            "432434", center, AccountState.SAVINGS_CLOSED.getValue(), startDate, savingsOffering);
    List<SavingsBO> savingsAccounts = service.getAllClosedAccounts(center.getCustomerId());
    Assert.assertEquals(1, savingsAccounts.size());
  }
 private Short extractLoanOfficerId(CustomerBO customer) {
   Short loanOfficerId = null;
   PersonnelBO loanOfficer = customer.getPersonnel();
   if (loanOfficer != null) {
     loanOfficerId = loanOfficer.getPersonnelId();
   }
   return loanOfficerId;
 }
  @Override
  public List<CustomerRecentActivityDto> retrieveRecentActivities(
      Integer customerId, Integer countOfActivities) {
    CustomerBO customerBO = this.customerDao.findCustomerById(customerId);
    List<CustomerActivityEntity> customerActivityDetails =
        customerBO.getCustomerAccount().getCustomerActivitDetails();

    List<CustomerRecentActivityDto> customerActivityViewList =
        new ArrayList<CustomerRecentActivityDto>();
    int count = 0;
    for (CustomerActivityEntity customerActivityEntity : customerActivityDetails) {
      customerActivityViewList.add(getCustomerActivityView(customerActivityEntity));
      if (++count == countOfActivities) {
        break;
      }
    }
    return customerActivityViewList;
  }
Example #12
0
 @CloseSession
 @TransactionDemarcate(validateAndResetToken = true)
 public ActionForward create(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   logger.debug("In CustomerNotesAction::create()");
   ActionForward forward = null;
   CustomerNotesActionForm notesActionForm = (CustomerNotesActionForm) form;
   CustomerBO customerBO =
       getCustomerBusinessService()
           .getCustomer(Integer.valueOf(((CustomerNotesActionForm) form).getCustomerId()));
   UserContext uc = getUserContext(request);
   if (customerBO.getPersonnel() != null) {
     checkPermissionForAddingNotes(
         AccountTypes.CUSTOMER_ACCOUNT,
         customerBO.getLevel(),
         uc,
         customerBO.getOffice().getOfficeId(),
         customerBO.getPersonnel().getPersonnelId());
   } else {
     checkPermissionForAddingNotes(
         AccountTypes.CUSTOMER_ACCOUNT,
         customerBO.getLevel(),
         uc,
         customerBO.getOffice().getOfficeId(),
         uc.getId());
   }
   PersonnelBO personnelBO = new PersonnelPersistence().getPersonnel(uc.getId());
   CustomerNoteEntity customerNote =
       new CustomerNoteEntity(
           notesActionForm.getComment(),
           new DateTimeService().getCurrentJavaSqlDate(),
           personnelBO,
           customerBO);
   customerBO.addCustomerNotes(customerNote);
   customerBO.setUserContext(uc);
   customerBO.update();
   forward = mapping.findForward(getDetailCustomerPage(notesActionForm));
   customerBO = null;
   return forward;
 }
 private void generateNewListOfPositions(
     CustomerBO customer,
     List<PositionEntity> customerPositions,
     List<CustomerPositionDto> customerPositionDtos) {
   for (PositionEntity position : customerPositions) {
     CustomerPositionDto customerPosition =
         new CustomerPositionDto(customer.getCustomerId(), position.getId(), position.getName());
     customerPositionDtos.add(customerPosition);
   }
 }
  @Override
  public CustomerNoteFormDto retrieveCustomerNote(String globalCustNum) {

    MifosUser user =
        (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    CustomerBO customer = this.customerDao.findCustomerBySystemId(globalCustNum);
    PersonnelBO loggedInUser = this.personnelDao.findPersonnelById(userContext.getId());

    Integer customerLevel = customer.getCustomerLevel().getId().intValue();
    String globalNum = customer.getGlobalCustNum();
    String displayName = customer.getDisplayName();
    LocalDate commentDate = new LocalDate();
    String commentUser = loggedInUser.getDisplayName();

    return new CustomerNoteFormDto(
        globalNum, displayName, customerLevel, commentDate, commentUser, "");
  }
Example #15
0
 @TransactionDemarcate(joinToken = true)
 public ActionForward load(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   logger.debug("In CustomerNotesAction::load()");
   clearActionForm(form);
   UserContext userContext = getUserContext(request);
   CustomerBO customerBO =
       getCustomerBusinessService()
           .getCustomer(Integer.valueOf(((CustomerNotesActionForm) form).getCustomerId()));
   customerBO.setUserContext(userContext);
   setFormAttributes(userContext, form, customerBO);
   PersonnelBO personnelBO = new PersonnelPersistence().getPersonnel(userContext.getId());
   SessionUtils.removeAttribute(Constants.BUSINESS_KEY, request);
   SessionUtils.setAttribute(Constants.BUSINESS_KEY, customerBO, request);
   SessionUtils.setAttribute(
       CustomerConstants.PERSONNEL_NAME, personnelBO.getDisplayName(), request);
   return mapping.findForward(ActionForwards.load_success.toString());
 }
  public void testSuccessfulPreview() throws Exception {
    CollectionSheetEntryGridDto bulkEntry = getSuccessfulBulkEntry();
    Calendar meetinDateCalendar = new GregorianCalendar();
    int year = meetinDateCalendar.get(Calendar.YEAR);
    int month = meetinDateCalendar.get(Calendar.MONTH);
    int day = meetinDateCalendar.get(Calendar.DAY_OF_MONTH);
    meetinDateCalendar = new GregorianCalendar(year, month, day);

    request.setAttribute(Constants.CURRENTFLOWKEY, flowKey);
    SessionUtils.setAttribute(CollectionSheetEntryConstants.BULKENTRY, bulkEntry, request);
    setRequestPathInfo("/collectionsheetaction.do");
    addRequestParameter(Constants.CURRENTFLOWKEY, flowKey);
    addRequestParameter("method", "preview");
    addRequestParameter("attendanceSelected[0]", "1");
    addRequestParameter("enteredAmount[0][0]", "212.0");
    addRequestParameter("enteredAmount[1][1]", "212.0");
    addRequestParameter("enteredAmount[0][1]", "212.0");
    addRequestParameter("enteredAmount[1][0]", "212.0");
    addRequestParameter("withDrawalAmountEntered[2][2]", "100.0");
    addRequestParameter("depositAmountEntered[2][2]", "100.0");
    addRequestParameter("withDrawalAmountEntered[0][0]", "100.0");
    addRequestParameter("depositAmountEntered[0][0]", "100.0");
    addRequestDateParameter("transactionDate", day + "/" + (month + 1) + "/" + year);
    performNoErrors();
    verifyForward("preview_success");

    groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
    clientAccount = TestObjectFactory.getObject(LoanBO.class, clientAccount.getAccountId());
    centerSavingsAccount =
        TestObjectFactory.getObject(SavingsBO.class, centerSavingsAccount.getAccountId());
    clientSavingsAccount =
        TestObjectFactory.getObject(SavingsBO.class, clientSavingsAccount.getAccountId());
    groupSavingsAccount =
        TestObjectFactory.getObject(SavingsBO.class, groupSavingsAccount.getAccountId());
    center = TestObjectFactory.getCustomer(center.getCustomerId());
    group = TestObjectFactory.getCustomer(group.getCustomerId());
    client = TestObjectFactory.getClient(client.getCustomerId());
  }
  @Override
  public void revertLastChargesPayment(String globalCustNum, String adjustmentNote) {

    MifosUser user =
        (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    PersonnelBO loggedInUser = this.personnelDao.findPersonnelById(userContext.getId());
    CustomerBO customerBO = this.customerDao.findCustomerBySystemId(globalCustNum);
    customerBO.updateDetails(userContext);

    if (customerBO.getCustomerAccount().findMostRecentNonzeroPaymentByPaymentDate() != null) {
      customerBO.getCustomerAccount().updateDetails(userContext);

      try {
        if (customerBO.getPersonnel() != null) {
          new AccountBusinessService()
              .checkPermissionForAdjustment(
                  AccountTypes.CUSTOMER_ACCOUNT,
                  customerBO.getLevel(),
                  userContext,
                  customerBO.getOffice().getOfficeId(),
                  customerBO.getPersonnel().getPersonnelId());
        } else {
          new AccountBusinessService()
              .checkPermissionForAdjustment(
                  AccountTypes.CUSTOMER_ACCOUNT,
                  customerBO.getLevel(),
                  userContext,
                  customerBO.getOffice().getOfficeId(),
                  userContext.getId());
        }

        this.transactionHelper.startTransaction();
        customerBO.adjustPmnt(adjustmentNote, loggedInUser);
        this.customerDao.save(customerBO);
        this.transactionHelper.commitTransaction();
      } catch (SystemException e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
      } catch (ApplicationException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getKey(), e);
      }
    }
  }
  @Override
  public CenterDto retrieveCenterDetailsForUpdate(Integer centerId) {

    MifosUser user =
        (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    CustomerBO center = customerDao.findCustomerById(centerId);

    Short officeId = center.getOffice().getOfficeId();
    String searchId = center.getSearchId();
    Short loanOfficerId = extractLoanOfficerId(center);

    CenterCreation centerCreation =
        new CenterCreation(
            officeId,
            userContext.getId(),
            userContext.getLevelId(),
            userContext.getPreferredLocale());
    List<PersonnelDto> activeLoanOfficersForBranch =
        personnelDao.findActiveLoanOfficersForOffice(centerCreation);

    List<CustomerDto> customerList =
        customerDao.findClientsThatAreNotCancelledOrClosed(searchId, officeId);

    List<CustomerPositionDto> customerPositionDtos =
        generateCustomerPositionViews(center, userContext.getLocaleId());

    DateTime mfiJoiningDate = new DateTime();
    String mfiJoiningDateAsString = "";
    if (center.getMfiJoiningDate() != null) {
      mfiJoiningDate = new DateTime(center.getMfiJoiningDate());
      mfiJoiningDateAsString =
          DateUtils.getUserLocaleDate(
              userContext.getPreferredLocale(), center.getMfiJoiningDate().toString());
    }

    AddressDto address = null;
    if (center.getAddress() != null) {
      address = Address.toDto(center.getAddress());
    }
    return new CenterDto(
        loanOfficerId,
        center.getCustomerId(),
        center.getGlobalCustNum(),
        mfiJoiningDate,
        mfiJoiningDateAsString,
        center.getExternalId(),
        address,
        customerPositionDtos,
        customerList,
        activeLoanOfficersForBranch,
        true);
  }
  private CollectionSheetEntryGridDto getFailureBulkEntry() throws Exception {
    Date startDate = new Date(System.currentTimeMillis());

    MeetingBO meeting =
        TestObjectFactory.createMeeting(
            TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
    center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
    group =
        TestObjectFactory.createWeeklyFeeGroupUnderCenter(
            "Group", CustomerStatus.GROUP_ACTIVE, center);
    client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
    LoanOfferingBO loanOffering1 = TestObjectFactory.createLoanOffering(startDate, meeting);
    LoanOfferingBO loanOffering2 =
        TestObjectFactory.createLoanOffering("Loan2345", "313f", startDate, meeting);
    groupAccount =
        TestObjectFactory.createLoanAccount(
            "42423142341",
            group,
            AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
            startDate,
            loanOffering1);
    clientAccount =
        TestObjectFactory.createLoanAccount(
            "3243", client, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate, loanOffering2);
    MeetingBO meetingIntCalc =
        TestObjectFactory.createMeeting(
            TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
    MeetingBO meetingIntPost =
        TestObjectFactory.createMeeting(
            TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
    SavingsOfferingBO savingsOffering =
        TestObjectFactory.createSavingsProduct(
            "SavingPrd123c",
            "ased",
            ApplicableTo.GROUPS,
            startDate,
            PrdStatus.SAVINGS_ACTIVE,
            300.0,
            RecommendedAmountUnit.PER_INDIVIDUAL,
            1.2,
            200.0,
            200.0,
            SavingsType.VOLUNTARY,
            InterestCalcType.MINIMUM_BALANCE,
            meetingIntCalc,
            meetingIntPost);
    SavingsOfferingBO savingsOffering1 =
        TestObjectFactory.createSavingsProduct(
            "SavingPrd1we",
            "vbgr",
            ApplicableTo.GROUPS,
            startDate,
            PrdStatus.SAVINGS_ACTIVE,
            300.0,
            RecommendedAmountUnit.PER_INDIVIDUAL,
            1.2,
            200.0,
            200.0,
            SavingsType.VOLUNTARY,
            InterestCalcType.MINIMUM_BALANCE,
            meetingIntCalc,
            meetingIntPost);
    centerSavingsAccount =
        TestObjectFactory.createSavingsAccount(
            "432434", center, Short.valueOf("16"), startDate, savingsOffering);
    clientSavingsAccount =
        TestObjectFactory.createSavingsAccount(
            "432434", client, Short.valueOf("16"), startDate, savingsOffering1);

    CollectionSheetEntryView bulkEntryParent =
        new CollectionSheetEntryView(getCusomerView(center), null);
    bulkEntryParent.addSavingsAccountDetail(getSavingsAccountView(centerSavingsAccount));
    bulkEntryParent.setCustomerAccountDetails(getCustomerAccountView(center));

    CollectionSheetEntryView bulkEntryChild =
        new CollectionSheetEntryView(getCusomerView(group), null);
    LoanAccountView groupLoanAccountView = getLoanAccountView(groupAccount);
    bulkEntryChild.addLoanAccountDetails(groupLoanAccountView);
    bulkEntryChild.setCustomerAccountDetails(getCustomerAccountView(group));
    CollectionSheetEntryView bulkEntrySubChild =
        new CollectionSheetEntryView(getCusomerView(client), null);
    LoanAccountView clientLoanAccountView = getLoanAccountView(clientAccount);
    bulkEntrySubChild.addLoanAccountDetails(clientLoanAccountView);
    bulkEntrySubChild.addSavingsAccountDetail(getSavingsAccountView(clientSavingsAccount));
    bulkEntrySubChild.setCustomerAccountDetails(getCustomerAccountView(client));

    bulkEntryChild.addChildNode(bulkEntrySubChild);
    bulkEntryParent.addChildNode(bulkEntryChild);
    bulkEntryChild.getLoanAccountDetails().get(0).setEnteredAmount("100.0");
    bulkEntryChild
        .getLoanAccountDetails()
        .get(0)
        .setPrdOfferingId(groupLoanAccountView.getPrdOfferingId());
    bulkEntrySubChild.getLoanAccountDetails().get(0).setEnteredAmount("100.0");
    bulkEntrySubChild
        .getLoanAccountDetails()
        .get(0)
        .setPrdOfferingId(clientLoanAccountView.getPrdOfferingId());

    ProductDto loanOfferingDto =
        new ProductDto(loanOffering1.getPrdOfferingId(), loanOffering1.getPrdOfferingShortName());
    ProductDto loanOfferingDto2 =
        new ProductDto(loanOffering2.getPrdOfferingId(), loanOffering2.getPrdOfferingShortName());

    List<ProductDto> loanProducts = Arrays.asList(loanOfferingDto, loanOfferingDto2);

    ProductDto savingsOfferingDto =
        new ProductDto(
            savingsOffering.getPrdOfferingId(), savingsOffering.getPrdOfferingShortName());
    List<ProductDto> savingsProducts = Arrays.asList(savingsOfferingDto);

    final PersonnelView loanOfficer = getPersonnelView(center.getPersonnel());
    final OfficeView officeView = null;
    final List<CustomValueListElement> attendanceTypesList =
        new ArrayList<CustomValueListElement>();

    bulkEntryParent.setCountOfCustomers(3);
    final CollectionSheetEntryGridDto bulkEntry =
        new CollectionSheetEntryGridDto(
            bulkEntryParent,
            loanOfficer,
            officeView,
            getPaymentTypeView(),
            startDate,
            "324343242",
            startDate,
            loanProducts,
            savingsProducts,
            attendanceTypesList);

    return bulkEntry;
  }
  private CollectionSheetEntryGridDto getSuccessfulBulkEntry() throws Exception {

    MeetingBO meeting =
        TestObjectFactory.createMeeting(
            TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
    Date startDate = new Date(System.currentTimeMillis());
    center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
    group =
        TestObjectFactory.createWeeklyFeeGroupUnderCenter(
            "Group", CustomerStatus.GROUP_ACTIVE, center);
    client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
    LoanOfferingBO loanOffering1 = TestObjectFactory.createLoanOffering(startDate, meeting);
    LoanOfferingBO loanOffering2 =
        TestObjectFactory.createLoanOffering(
            "Loan2345",
            "313f",
            ApplicableTo.CLIENTS,
            startDate,
            PrdStatus.LOAN_ACTIVE,
            300.0,
            1.2,
            3,
            InterestType.FLAT,
            meeting);
    groupAccount =
        TestObjectFactory.createLoanAccount(
            "42423142341",
            group,
            AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
            startDate,
            loanOffering1);
    clientAccount = getLoanAccount(AccountState.LOAN_APPROVED, startDate, 1, loanOffering2);
    Date currentDate = new Date(System.currentTimeMillis());
    // 2010-01-18: JohnW - This use of TestObjectFactory.createSavingsProduct used to break a number
    // of
    // business rules.
    // E.g all the savings products were set up as applicable for Groups and "per individual" which
    // is wrong for
    // centers and clients. In the case of the client being wrongly set up as "Per Individual" it
    // now triggers save
    // collection sheet validation (which checks that the account associated with the client marked
    // "per individual"
    // matches its parent group or center)
    // Also, when creating the center savings accounts (which is effectively "per individual") and
    // the group savings
    // account which is "per individual" the saving_schedule entries for the client are not written
    // (they are in the
    // production code).
    //
    // Considered using/updating the savingsProductBuilder functionality but that doesn't deal with
    // the
    // "per individual" aspect either (update: it does, but still problem with builder creating
    // installments).
    // Decided not to try and fix it up (good deal of effort involved) but rather change the
    // TestObjectFactory.createSavingsProduct to accept a RecommendedAmountUnit parameter.
    // Unfortunately it wouldn't allow a null parameter (which is valid for centers and clients)
    // through so, where
    // necessary, I picked a value that worked for the test but was wrong in a business rule sense
    // (just as its
    // always been).
    // So the savings product test data doesn't adhere to business rules but all tests pass here and
    // in others
    // tests.
    SavingsOfferingBO savingsOffering1 =
        TestObjectFactory.createSavingsProduct(
            "SavingPrd1", "ased", currentDate, RecommendedAmountUnit.COMPLETE_GROUP);
    SavingsOfferingBO savingsOffering2 =
        TestObjectFactory.createSavingsProduct(
            "SavingPrd2", "cvdf", currentDate, RecommendedAmountUnit.COMPLETE_GROUP);
    SavingsOfferingBO savingsOffering3 =
        TestObjectFactory.createSavingsProduct(
            "SavingPrd3", "zxsd", currentDate, RecommendedAmountUnit.COMPLETE_GROUP);

    centerSavingsAccount =
        TestObjectFactory.createSavingsAccount(
            "43244334", center, Short.valueOf("16"), startDate, savingsOffering1);
    groupSavingsAccount =
        TestObjectFactory.createSavingsAccount(
            "43234434", group, Short.valueOf("16"), startDate, savingsOffering2);
    clientSavingsAccount =
        TestObjectFactory.createSavingsAccount(
            "43245434", client, Short.valueOf("16"), startDate, savingsOffering3);

    CollectionSheetEntryView bulkEntryParent =
        new CollectionSheetEntryView(getCusomerView(center), null);
    SavingsAccountView centerSavingsAccountView = getSavingsAccountView(centerSavingsAccount);
    centerSavingsAccountView.setDepositAmountEntered("100");
    centerSavingsAccountView.setWithDrawalAmountEntered("10");
    bulkEntryParent.addSavingsAccountDetail(centerSavingsAccountView);
    bulkEntryParent.setCustomerAccountDetails(getCustomerAccountView(center));

    CollectionSheetEntryView bulkEntryChild =
        new CollectionSheetEntryView(getCusomerView(group), null);
    LoanAccountView groupLoanAccountView = getLoanAccountView(groupAccount);
    SavingsAccountView groupSavingsAccountView = getSavingsAccountView(groupSavingsAccount);
    groupSavingsAccountView.setDepositAmountEntered("100");
    groupSavingsAccountView.setWithDrawalAmountEntered("10");
    bulkEntryChild.addLoanAccountDetails(groupLoanAccountView);
    bulkEntryChild.addSavingsAccountDetail(groupSavingsAccountView);
    bulkEntryChild.setCustomerAccountDetails(getCustomerAccountView(group));

    CollectionSheetEntryView bulkEntrySubChild =
        new CollectionSheetEntryView(getCusomerView(client), null);
    LoanAccountView clientLoanAccountView = getLoanAccountView(clientAccount);
    clientLoanAccountView.setAmountPaidAtDisbursement(0.0);
    SavingsAccountView clientSavingsAccountView = getSavingsAccountView(clientSavingsAccount);
    clientSavingsAccountView.setDepositAmountEntered("100");
    clientSavingsAccountView.setWithDrawalAmountEntered("10");
    bulkEntrySubChild.addLoanAccountDetails(clientLoanAccountView);
    bulkEntrySubChild.setAttendence(new Short("2"));
    bulkEntrySubChild.addSavingsAccountDetail(clientSavingsAccountView);
    bulkEntrySubChild.setCustomerAccountDetails(getCustomerAccountView(client));

    bulkEntryChild.addChildNode(bulkEntrySubChild);
    bulkEntryParent.addChildNode(bulkEntryChild);

    LoanAccountsProductView childView = bulkEntryChild.getLoanAccountDetails().get(0);
    childView.setPrdOfferingId(groupLoanAccountView.getPrdOfferingId());
    childView.setEnteredAmount("100.0");
    LoanAccountsProductView subchildView = bulkEntrySubChild.getLoanAccountDetails().get(0);
    subchildView.setDisBursementAmountEntered(clientAccount.getLoanAmount().toString());
    subchildView.setPrdOfferingId(clientLoanAccountView.getPrdOfferingId());

    ProductDto loanOfferingDto =
        new ProductDto(loanOffering1.getPrdOfferingId(), loanOffering1.getPrdOfferingShortName());
    ProductDto loanOfferingDto2 =
        new ProductDto(loanOffering2.getPrdOfferingId(), loanOffering2.getPrdOfferingShortName());

    List<ProductDto> loanProducts = Arrays.asList(loanOfferingDto, loanOfferingDto2);

    ProductDto savingsOfferingDto =
        new ProductDto(
            savingsOffering1.getPrdOfferingId(), savingsOffering1.getPrdOfferingShortName());
    ProductDto savingsOfferingDto2 =
        new ProductDto(
            savingsOffering2.getPrdOfferingId(), savingsOffering2.getPrdOfferingShortName());
    ProductDto savingsOfferingDto3 =
        new ProductDto(
            savingsOffering3.getPrdOfferingId(), savingsOffering3.getPrdOfferingShortName());
    List<ProductDto> savingsProducts =
        Arrays.asList(savingsOfferingDto, savingsOfferingDto2, savingsOfferingDto3);

    final PersonnelView loanOfficer = getPersonnelView(center.getPersonnel());
    final OfficeView officeView = null;
    final List<CustomValueListElement> attendanceTypesList =
        new ArrayList<CustomValueListElement>();

    bulkEntryParent.setCountOfCustomers(3);
    final CollectionSheetEntryGridDto bulkEntry =
        new CollectionSheetEntryGridDto(
            bulkEntryParent,
            loanOfficer,
            officeView,
            getPaymentTypeView(),
            startDate,
            "324343242",
            startDate,
            loanProducts,
            savingsProducts,
            attendanceTypesList);

    return bulkEntry;
  }
  @SuppressWarnings("unchecked")
  public void testSuccessfulGet() throws Exception {

    MeetingBO meeting =
        TestObjectFactory.createMeeting(
            TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
    center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
    group =
        TestObjectFactory.createWeeklyFeeGroupUnderCenter(
            "Group", CustomerStatus.GROUP_ACTIVE, center);
    client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
    account = getLoanAccount(group, meeting);

    // Using utility method that uses builder pattern to create savings accounts - TestObjectFactory
    // was creating
    // installments for all savings accounts (which is wrong)
    TestCollectionSheetRetrieveSavingsAccountsUtils collectionSheetRetrieveSavingsAccountsUtils =
        new TestCollectionSheetRetrieveSavingsAccountsUtils();
    centerSavingsAccount =
        collectionSheetRetrieveSavingsAccountsUtils.createSavingsAccount(
            center, "cemi", "120.00", false, false);
    groupSavingsAccount =
        collectionSheetRetrieveSavingsAccountsUtils.createSavingsAccount(
            group, "gvcg", "180.00", true, false);
    clientSavingsAccount =
        collectionSheetRetrieveSavingsAccountsUtils.createSavingsAccount(
            client, "clm", "222.00", false, false);

    request.setAttribute(Constants.CURRENTFLOWKEY, flowKey);
    CustomerView customerView = new CustomerView();
    customerView.setCustomerId(center.getCustomerId());
    customerView.setCustomerSearchId(center.getSearchId());
    customerView.setCustomerLevelId(center.getCustomerLevel().getId());

    final OfficeView officeView =
        new OfficeView(
            Short.valueOf("3"), "", OfficeLevel.BRANCHOFFICE, "levelNameKey", Integer.valueOf(-1));
    final PersonnelView personnelView = new PersonnelView(Short.valueOf("3"), "");

    SessionUtils.setAttribute(
        CollectionSheetEntryConstants.COLLECTION_SHEET_ENTRY_FORM_DTO,
        createCollectionSheetDto(customerView, officeView, personnelView),
        request);

    SessionUtils.setCollectionAttribute(
        CollectionSheetEntryConstants.PAYMENT_TYPES_LIST,
        Arrays.asList(getPaymentTypeView()),
        request);
    SessionUtils.setAttribute(
        CollectionSheetEntryConstants.ISCENTERHIERARCHYEXISTS, Constants.YES, request);

    setMasterListInSession(center.getCustomerId());
    setRequestPathInfo("/collectionsheetaction.do");
    addRequestParameter("method", "get");
    addRequestParameter("officeId", "3");
    addRequestParameter("loanOfficerId", "3");
    addRequestParameter("paymentId", "1");
    addRequestParameter(Constants.CURRENTFLOWKEY, flowKey);

    Calendar meetinDateCalendar = new GregorianCalendar();
    meetinDateCalendar.setTime(getMeetingDates(meeting));
    int year = meetinDateCalendar.get(Calendar.YEAR);
    int month = meetinDateCalendar.get(Calendar.MONTH);
    int day = meetinDateCalendar.get(Calendar.DAY_OF_MONTH);
    meetinDateCalendar = new GregorianCalendar(year, month, day);
    SessionUtils.setAttribute(
        "LastMeetingDate", new java.sql.Date(meetinDateCalendar.getTimeInMillis()), request);
    addRequestDateParameter("transactionDate", day + "/" + (month + 1) + "/" + year);
    addRequestParameter("receiptId", "1");
    addRequestDateParameter("receiptDate", "20/03/2006");
    addRequestParameter("customerId", String.valueOf(center.getCustomerId().intValue()));
    actionPerform();
    verifyNoActionErrors();
    verifyNoActionMessages();
    verifyForward("get_success");
  }
  public void testGetLastMeetingDateForCustomer() throws Exception {
    MeetingBO meeting =
        TestObjectFactory.createMeeting(
            TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
    center = TestObjectFactory.createWeeklyFeeCenter("Center_Active", meeting);
    setRequestPathInfo("/collectionsheetaction.do");
    addRequestParameter("method", "getLastMeetingDateForCustomer");
    addRequestParameter(Constants.CURRENTFLOWKEY, flowKey);
    addRequestParameter("officeId", "3");
    addRequestParameter("loanOfficerId", "1");
    addRequestParameter("customerId", String.valueOf(center.getCustomerId().intValue()));

    request.setAttribute(Constants.CURRENTFLOWKEY, flowKey);
    SessionUtils.setAttribute(
        CollectionSheetEntryConstants.COLLECTION_SHEET_ENTRY_FORM_DTO,
        createDefaultCollectionSheetDto(),
        request);

    actionPerform();
    verifyNoActionErrors();
    verifyNoActionMessages();
    verifyForward("load_success");

    if (AccountingRules.isBackDatedTxnAllowed()) {
      Assert.assertEquals(
          "The value for isBackDated Trxn Allowed",
          SessionUtils.getAttribute(CollectionSheetEntryConstants.ISBACKDATEDTRXNALLOWED, request),
          Constants.YES);
      Assert.assertEquals(
          new java.sql.Date(
                  DateUtils.getDateWithoutTimeStamp(getMeetingDates(meeting).getTime()).getTime())
              .toString(),
          SessionUtils.getAttribute("LastMeetingDate", request).toString());
      Assert.assertEquals(
          new java.util.Date(
              DateUtils.getDateWithoutTimeStamp(getMeetingDates(meeting).getTime()).getTime()),
          DateUtils.getDate(
              ((BulkEntryActionForm)
                      request
                          .getSession()
                          .getAttribute(CollectionSheetEntryConstants.BULKENTRYACTIONFORM))
                  .getTransactionDate()));
    } else {
      Assert.assertEquals(
          "The value for isBackDated Trxn Allowed",
          SessionUtils.getAttribute(CollectionSheetEntryConstants.ISBACKDATEDTRXNALLOWED, request),
          Constants.NO);
      Assert.assertEquals(
          new java.sql.Date(
                  DateUtils.getDateWithoutTimeStamp(getMeetingDates(meeting).getTime()).getTime())
              .toString(),
          SessionUtils.getAttribute("LastMeetingDate", request).toString());
      Assert.assertEquals(
          DateUtils.getUserLocaleDate(
              getUserLocale(request),
              new java.sql.Date(DateUtils.getCurrentDateWithoutTimeStamp().getTime()).toString()),
          ((BulkEntryActionForm)
                  request
                      .getSession()
                      .getAttribute(CollectionSheetEntryConstants.BULKENTRYACTIONFORM))
              .getTransactionDate());
    }
  }
  public void testSuccessfulCreate() throws Exception {
    CollectionSheetEntryGridDto bulkEntry = getSuccessfulBulkEntry();
    Calendar meetingDateCalendar = new GregorianCalendar();
    int year = meetingDateCalendar.get(Calendar.YEAR);
    int month = meetingDateCalendar.get(Calendar.MONTH);
    int day = meetingDateCalendar.get(Calendar.DAY_OF_MONTH);
    meetingDateCalendar = new GregorianCalendar(year, month, day);

    Date meetingDate = new Date(meetingDateCalendar.getTimeInMillis());
    HashMap<Integer, ClientAttendanceDto> clientAttendance =
        new HashMap<Integer, ClientAttendanceDto>();
    clientAttendance.put(1, getClientAttendanceDto(1, meetingDate));
    clientAttendance.put(2, getClientAttendanceDto(2, meetingDate));
    clientAttendance.put(3, getClientAttendanceDto(3, meetingDate));

    request.setAttribute(Constants.CURRENTFLOWKEY, flowKey);
    addRequestParameter("attendanceSelected[0]", "2");

    request.setAttribute(Constants.CURRENTFLOWKEY, flowKey);
    SessionUtils.setAttribute(CollectionSheetEntryConstants.BULKENTRY, bulkEntry, request);
    setRequestPathInfo("/collectionsheetaction.do");
    addRequestParameter("method", "preview");
    addRequestParameter(Constants.CURRENTFLOWKEY, flowKey);
    addRequestDateParameter("transactionDate", day + "/" + (month + 1) + "/" + year);

    if (SUPPLY_ENTERED_AMOUNT_PARAMETERS) {
      addParametersForEnteredAmount();
      addParametersForDisbursalEnteredAmount();
    }

    performNoErrors();

    request.setAttribute(Constants.CURRENTFLOWKEY, flowKey);
    setRequestPathInfo("/collectionsheetaction.do");
    addRequestParameter("method", "create");
    addRequestParameter(Constants.CURRENTFLOWKEY, flowKey);
    addRequestParameter("attendanceSelected[0]", "2");
    addRequestDateParameter("transactionDate", day + "/" + (month + 1) + "/" + year);
    addRequestParameter("customerId", "1");

    performNoErrors();
    verifyForward("create_success");
    Assert.assertNotNull(request.getAttribute(CollectionSheetEntryConstants.CENTER));
    Assert.assertEquals(
        request.getAttribute(CollectionSheetEntryConstants.CENTER), center.getDisplayName());

    groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
    clientAccount = TestObjectFactory.getObject(LoanBO.class, clientAccount.getAccountId());
    centerSavingsAccount =
        TestObjectFactory.getObject(SavingsBO.class, centerSavingsAccount.getAccountId());
    clientSavingsAccount =
        TestObjectFactory.getObject(SavingsBO.class, clientSavingsAccount.getAccountId());
    groupSavingsAccount =
        TestObjectFactory.getObject(SavingsBO.class, groupSavingsAccount.getAccountId());
    center = TestObjectFactory.getCustomer(center.getCustomerId());
    group = TestObjectFactory.getCustomer(group.getCustomerId());
    client = TestObjectFactory.getClient(client.getCustomerId());

    Assert.assertEquals(1, client.getClientAttendances().size());
    Assert.assertEquals(
        AttendanceType.ABSENT,
        client
            .getClientAttendanceForMeeting(new java.sql.Date(meetingDateCalendar.getTimeInMillis()))
            .getAttendanceAsEnum());
  }
  @Override
  public ParsedClientsDto save(ParsedClientsDto parsedClientsDto) {
    MifosUser user =
        (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    OfficeBO userOffice = this.officeDao.findOfficeById(userContext.getBranchId());
    userContext.setBranchGlobalNum(userOffice.getGlobalOfficeNum());

    DateTimeService dateTimeService = new DateTimeService();

    /* Construct ClientBO objects */
    List<NewClientDto> newClients = new ArrayList<NewClientDto>();

    for (ImportedClientDetail importedClient : parsedClientsDto.getSuccessfullyParsedRows()) {
      String secondMiddleName = null;
      ClientCreationDetail clientCreationDetail = importedClient.getClientCreationDetail();

      PersonnelBO formedBy = null;

      /* Client name details */
      ClientNameDetailDto clientNameDetails = clientCreationDetail.getClientNameDetailDto();
      ClientNameDetailEntity clientNameDetailEntity =
          new ClientNameDetailEntity(null, secondMiddleName, clientNameDetails);

      ClientDetailEntity clientDetailEntity = new ClientDetailEntity();
      clientDetailEntity.updateClientDetails(clientCreationDetail.getClientPersonalDetailDto());

      String clientFirstName = clientNameDetails.getFirstName();
      String clientLastName = clientNameDetails.getLastName();
      String secondLastName = clientNameDetails.getSecondLastName();

      /* Spouse/father name details */
      ClientNameDetailEntity spouseFatherNameDetailEntity = null;
      if (clientCreationDetail.getSpouseFatherName() != null) {
        spouseFatherNameDetailEntity =
            new ClientNameDetailEntity(
                null, secondMiddleName, clientCreationDetail.getSpouseFatherName());
      }
      /* Data conversion */
      DateTime dateOfBirth = new DateTime(clientCreationDetail.getDateOfBirth());
      DateTime mfiJoiningDate = new DateTime(clientCreationDetail.getMfiJoiningDate());
      DateTime trainedDateTime = null;
      if (clientCreationDetail.getTrainedDate() != null) {
        trainedDateTime = new DateTime(clientCreationDetail.getTrainedDate());
      }
      /* Status */
      CustomerStatus clientStatus = CustomerStatus.fromInt(clientCreationDetail.getClientStatus());
      CustomerStatus finalStatus = clientStatus;
      if (clientStatus == CustomerStatus.CLIENT_ACTIVE
          && clientCreationDetail.getActivationDate() == null) {
        clientStatus = CustomerStatus.CLIENT_PENDING;
      }
      /* Address */
      Address address = null;
      if (clientCreationDetail.getAddress() != null) {
        AddressDto dto = clientCreationDetail.getAddress();
        address =
            new Address(
                dto.getLine1(),
                dto.getLine2(),
                dto.getLine3(),
                dto.getCity(),
                dto.getState(),
                dto.getCountry(),
                dto.getZip(),
                dto.getPhoneNumber());
      }
      // empty list
      List<ClientInitialSavingsOfferingEntity> associatedOfferings =
          new ArrayList<ClientInitialSavingsOfferingEntity>();
      // client object
      ClientBO client;
      if (clientCreationDetail.getGroupFlag() == 1) {
        CustomerBO group =
            customerDao.findCustomerBySystemId(clientCreationDetail.getParentGroupId());

        if (clientCreationDetail.getFormedBy() != null) {
          formedBy = this.personnelDao.findPersonnelById(clientCreationDetail.getFormedBy());
        } else {
          formedBy = group.getPersonnel();
        }

        client =
            ClientBO.createNewInGroupHierarchy(
                userContext,
                clientCreationDetail.getClientName(),
                clientStatus,
                mfiJoiningDate,
                group,
                formedBy,
                clientNameDetailEntity,
                dateOfBirth,
                clientCreationDetail.getGovernmentId(),
                clientCreationDetail.isTrained(),
                trainedDateTime,
                clientCreationDetail.getGroupFlag(),
                clientFirstName,
                clientLastName,
                secondLastName,
                spouseFatherNameDetailEntity,
                clientDetailEntity,
                associatedOfferings,
                clientCreationDetail.getExternalId(),
                address,
                clientCreationDetail.getActivationDate());
      } else {
        Short officeId = clientCreationDetail.getOfficeId();
        Short officerId = clientCreationDetail.getLoanOfficerId();

        PersonnelBO loanOfficer = personnelDao.findPersonnelById(officerId);
        OfficeBO office = this.officeDao.findOfficeById(officeId);

        if (clientCreationDetail.getFormedBy() != null) {
          formedBy = this.personnelDao.findPersonnelById(clientCreationDetail.getFormedBy());
        } else {
          formedBy = loanOfficer;
        }

        int lastSearchIdCustomerValue =
            customerDao.retrieveLastSearchIdValueForNonParentCustomersInOffice(officeId);

        /* meeting */
        final MeetingDto meetingDto = importedClient.getMeeting();
        MeetingBO clientMeeting = null;
        if (meetingDto != null) {
          clientMeeting = new MeetingFactory().create(meetingDto);
          clientMeeting.setUserContext(userContext);
        }

        client =
            ClientBO.createNewOutOfGroupHierarchy(
                userContext,
                clientCreationDetail.getClientName(),
                clientStatus,
                mfiJoiningDate,
                office,
                loanOfficer,
                clientMeeting,
                formedBy,
                clientNameDetailEntity,
                dateOfBirth,
                clientCreationDetail.getGovernmentId(),
                clientCreationDetail.isTrained(),
                trainedDateTime,
                clientCreationDetail.getGroupFlag(),
                clientFirstName,
                clientLastName,
                secondLastName,
                spouseFatherNameDetailEntity,
                clientDetailEntity,
                associatedOfferings,
                clientCreationDetail.getExternalId(),
                address,
                lastSearchIdCustomerValue);

        if (clientCreationDetail.getActivationDate() != null) {
          client.setCustomerActivationDate(
              clientCreationDetail.getActivationDate().toDateMidnight().toDate());
        }
      }
      // global id
      if (importedClient.getClientGlobalNum() != null) {
        client.setGlobalCustNum(importedClient.getClientGlobalNum());
      }

      NewClientDto newClient = new NewClientDto(client, finalStatus);

      newClients.add(newClient);
    }

    /* Validate client data */
    for (NewClientDto newClient : newClients) {
      ClientBO client = newClient.getClientBO();
      try {
        client.validate();
        customerDao.validateClientForDuplicateNameOrGovtId(
            client.getDisplayName(), client.getDateOfBirth(), client.getGovernmentId());
      } catch (CustomerException ex) {
        throw new MifosRuntimeException(ex);
      }
    }

    /* Save clients */
    List<AccountFeesEntity> accountFees = new ArrayList<AccountFeesEntity>(); // empty list
    try {
      hibernateTransactionHelper.startTransaction();
      for (NewClientDto newClient : newClients) {

        ClientBO client = newClient.getClientBO();
        CustomerStatus finalStatus = newClient.getCustomerStatus();
        // status to pending approval if active

        MeetingBO meeting = client.getCustomerMeetingValue();

        customerDao.save(client);
        hibernateTransactionHelper.flushSession();

        CalendarEvent applicableCalendarEvents =
            holidayDao.findCalendarEventsForThisYearAndNext(client.getOfficeId());
        CustomerAccountBO customerAccount =
            customerAccountFactory.create(client, accountFees, meeting, applicableCalendarEvents);
        client.addAccount(customerAccount);
        customerDao.save(client);
        hibernateTransactionHelper.flushSession();

        if (client.getParentCustomer() != null) {
          customerDao.save(client.getParentCustomer());
        }

        if (client.getGlobalCustNum() == null) {
          client.generateGlobalCustomerNumber();
        }
        client.generateSearchId();
        customerDao.save(client);
        hibernateTransactionHelper.flushSession();

        if (client.getParentCustomer() != null) {
          customerDao.save(client.getParentCustomer());
        }

        /* activate client */
        if (finalStatus == CustomerStatus.CLIENT_ACTIVE) {
          hibernateTransactionHelper.flushSession();
          hibernateTransactionHelper.beginAuditLoggingFor(client);
          client.clearCustomerFlagsIfApplicable(client.getStatus(), finalStatus);

          client.updateCustomerStatus(finalStatus);
          // changeStatus(client, oldStatus, newStatus);
          if (client.getParentCustomer() != null) {
            CustomerHierarchyEntity hierarchy =
                new CustomerHierarchyEntity(client, client.getParentCustomer());
            client.addCustomerHierarchy(hierarchy);
          }

          if (client.getCustomerActivationDate() != null) {
            client.setCustomerActivationDate(client.getCustomerActivationDate());
          } else {
            client.setCustomerActivationDate(dateTimeService.getCurrentJavaDateTime());
          }
          customerAccount.createSchedulesAndFeeSchedulesForFirstTimeActiveCustomer(
              client,
              accountFees,
              meeting,
              applicableCalendarEvents,
              new DateTime(client.getCustomerActivationDate()));

          customerDao.save(client);
        }
      }
      hibernateTransactionHelper.commitTransaction();
    } catch (Exception ex) {
      hibernateTransactionHelper.rollbackTransaction();
      throw new MifosRuntimeException(ex);
    }

    return parsedClientsDto;
  }