Example usage for java.sql Date before

List of usage examples for java.sql Date before

Introduction

In this page you can find the example usage for java.sql Date before.

Prototype

public boolean before(Date when) 

Source Link

Document

Tests if this date is before the specified date.

Usage

From source file:org.kuali.coeus.common.framework.compliance.core.SpecialReviewRuleBase.java

/**
 * Validates that the first date is before or the same as the second date.
 * /*  w w w.ja  v a2s  .co m*/
 * @param firstDate The first date
 * @param secondDate The second date
 * @param errorField The field on which to display the error
 * @param firstDateTitle The title of the first date field
 * @param secondDateTitle The title of the second date field
 * @return
 */
private boolean validateDateOrder(Date firstDate, Date secondDate, String errorField, String firstDateTitle,
        String secondDateTitle) {
    boolean isValid = true;

    if (firstDate != null && secondDate != null && secondDate.before(firstDate)) {
        isValid = false;
        reportError(errorField, KeyConstants.ERROR_SPECIAL_REVIEW_DATE_SAME_OR_LATER, secondDateTitle,
                firstDateTitle);
    }

    return isValid;
}

From source file:org.kuali.coeus.propdev.impl.core.LookupableDevelopmentProposalLookupableHelperServiceImpl.java

private boolean dateInRange(Date checkDate, Date lowerLimit, Date upperLimit) {
    if (checkDate == null) {
        return true;
    }/*from  w w w.  j  a  v a  2  s  . c  o  m*/
    if (lowerLimit != null && checkDate.before(lowerLimit)) {
        return false;
    }
    if (upperLimit != null && checkDate.after(upperLimit)) {
        return false;
    }
    return true;
}

From source file:org.kuali.kfs.coa.document.validation.impl.AccountGlobalRule.java

/**
 * This method checks to see if any expiration date field rules were violated in relation to the given detail record
 *
 * @param maintenanceDocument/*from ww  w .  ja va2 s .c  om*/
 * @param detail - the account detail we are investigating
 * @return false on rules violation
 */
protected boolean checkExpirationDate(MaintenanceDocument maintenanceDocument, AccountGlobalDetail detail) {
    boolean success = true;
    Date newExpDate = newAccountGlobal.getAccountExpirationDate();

    Date prevExpDate = null;

    // get previous expiration date for possible check later
    if (maintenanceDocument.getDocumentHeader().getWorkflowDocument().isApprovalRequested()) {
        try {
            MaintenanceDocument oldMaintDoc = (MaintenanceDocument) SpringContext.getBean(DocumentService.class)
                    .getByDocumentHeaderId(maintenanceDocument.getDocumentNumber());
            AccountGlobal oldAccountGlobal = (AccountGlobal) oldMaintDoc.getDocumentBusinessObject();
            if (ObjectUtils.isNotNull(oldAccountGlobal)) {
                prevExpDate = oldAccountGlobal.getAccountExpirationDate();
            }
        } catch (WorkflowException ex) {
            LOG.warn("Error retrieving maintenance doc for doc #" + maintenanceDocument.getDocumentNumber()
                    + ". This shouldn't happen.", ex);
        }
    }

    // load the object by keys
    Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class,
            detail.getPrimaryKeys());
    if (ObjectUtils.isNotNull(account)) {
        Date oldExpDate = account.getAccountExpirationDate();

        // When updating an account expiration date, the date must be today or later
        // (except for C&G accounts). Only run this test if this maint doc
        // is an edit doc
        if (isUpdatedExpirationDateInvalid(account, newAccountGlobal)) {
            // if the date was valid upon submission, and this is an approval,
            // we're not interested unless the approver changed the value
            if (ObjectUtils.isNull(prevExpDate) || !prevExpDate.equals(newExpDate)) {
                putFieldError("accountExpirationDate",
                        KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_TODAY_LATER);
                success &= false;
            }
        }

        // If creating a new account if acct_expiration_dt is set and the fund_group is not "CG" then
        // the acct_expiration_dt must be changed to a date that is today or later
        // unless the date was valid upon submission, this is an approval action
        // and the approver hasn't changed the value
        if (maintenanceDocument.isNew() && ObjectUtils.isNotNull(newExpDate)) {
            if (ObjectUtils.isNull(prevExpDate) || !prevExpDate.equals(newExpDate)) {
                if (ObjectUtils.isNotNull(newExpDate)
                        && ObjectUtils.isNull(newAccountGlobal.getSubFundGroup())) {
                    if (ObjectUtils.isNotNull(account.getSubFundGroup())) {
                        if (!account.isForContractsAndGrants()) {
                            if (!newExpDate.after(today) && !newExpDate.equals(today)) {
                                putGlobalError(KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_TODAY_LATER);
                                success &= false;
                            }
                        }
                    }
                }
            }
        }

        // acct_expiration_dt can not be before acct_effect_dt
        Date effectiveDate = account.getAccountEffectiveDate();
        if (ObjectUtils.isNotNull(effectiveDate) && ObjectUtils.isNotNull(newExpDate)) {
            if (newExpDate.before(effectiveDate)) {
                putGlobalError(
                        KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_CANNOT_BE_BEFORE_EFFECTIVE_DATE);
                success &= false;
            }
        }
    }

    return success;
}

From source file:org.kuali.kfs.coa.document.validation.impl.AccountRule.java

/**
 * This method checks to see if any expiration date field rules were violated
 *
 * @param maintenanceDocument// ww  w . ja v  a 2 s.  c  o m
 * @return false on rules violation
 */
protected boolean checkExpirationDate(MaintenanceDocument maintenanceDocument) {

    LOG.info("checkExpirationDate called");

    boolean success = true;

    Date oldExpDate = oldAccount.getAccountExpirationDate();
    Date newExpDate = newAccount.getAccountExpirationDate();
    Date today = new Date(getDateTimeService().getCurrentTimestamp().getTime());
    today.setTime(DateUtils.truncate(today, Calendar.DAY_OF_MONTH).getTime()); // remove any time components

    // When updating an account expiration date, the date must be today or later
    // Only run this test if this maintenance doc
    // is an edit doc

    if (isUpdatedExpirationDateInvalid(maintenanceDocument)) {
        Account newAccount = (Account) maintenanceDocument.getNewMaintainableObject().getBusinessObject();
        if (newAccount.isClosed()) {
            /*If the Account is being closed and the date is before today's date, the EXP date can only be today*/
            putFieldError("accountExpirationDate",
                    KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_CANNOT_BE_CLOSED_EXP_DATE_INVALID);
        } else {
            /*If the Account is not being closed and the date is before today's date, the EXP date can only be today or at a later date*/
            putFieldError("accountExpirationDate",
                    KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_TODAY_LATER);
        }
        success &= false;
    }

    // a continuation account is required if the expiration date is completed.
    if (ObjectUtils.isNotNull(newExpDate)) {
        if (StringUtils.isBlank(newAccount.getContinuationAccountNumber())) {
            putFieldError("continuationAccountNumber",
                    KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_CONTINUATION_ACCT_REQD_IF_EXP_DATE_COMPLETED);
        }
        if (StringUtils.isBlank(newAccount.getContinuationFinChrtOfAcctCd())) {
            putFieldError("continuationFinChrtOfAcctCd",
                    KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_CONTINUATION_FINCODE_REQD_IF_EXP_DATE_COMPLETED);
            success &= false;
        }
    }

    // If creating a new account if acct_expiration_dt is set then
    // the acct_expiration_dt must be changed to a date that is today or later
    if (maintenanceDocument.isNew() && ObjectUtils.isNotNull(newExpDate)) {
        Collection<String> fundGroups = SpringContext.getBean(ParameterService.class)
                .getParameterValuesAsString(Account.class,
                        KFSConstants.ChartApcParms.EXPIRATION_DATE_BACKDATING_FUND_GROUPS);
        if (fundGroups == null || ObjectUtils.isNull(newAccount.getSubFundGroup())
                || !fundGroups.contains(newAccount.getSubFundGroup().getFundGroupCode())) {
            if (!newExpDate.after(today) && !newExpDate.equals(today)) {
                putFieldError("accountExpirationDate",
                        KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_TODAY_LATER);
                success &= false;
            }
        }
    }

    // acct_expiration_dt can not be before acct_effect_dt
    Date effectiveDate = newAccount.getAccountEffectiveDate();
    if (ObjectUtils.isNotNull(effectiveDate) && ObjectUtils.isNotNull(newExpDate)) {
        if (newExpDate.before(effectiveDate)) {
            putFieldError("accountExpirationDate",
                    KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_CANNOT_BE_BEFORE_EFFECTIVE_DATE);
            success &= false;
        }
    }

    return success;
}

From source file:org.kuali.kfs.coa.document.validation.impl.AccountRule.java

/**
 * This method checks to see if the new expiration date is different from the old expiration and if it has if it is invalid
 *
 * @param maintDoc//from  w w  w.  j a v  a2s. com
 * @return true if expiration date has changed and is invalid
 */
protected boolean isUpdatedExpirationDateInvalid(MaintenanceDocument maintDoc) {

    // if this isn't an Edit document, we're not interested
    if (!maintDoc.isEdit()) {
        return false;
    }

    Date oldExpDate = oldAccount.getAccountExpirationDate();
    Date newExpDate = newAccount.getAccountExpirationDate();
    Date today = new Date(getDateTimeService().getCurrentDate().getTime());
    today.setTime(DateUtils.truncate(today, Calendar.DAY_OF_MONTH).getTime()); // remove any time components

    // if the date was valid upon submission, and this is an approval,
    // we're not interested unless the approver changed the value
    if (maintDoc.getDocumentHeader().getWorkflowDocument().isApprovalRequested()) {
        try {
            MaintenanceDocument oldMaintDoc = (MaintenanceDocument) SpringContext.getBean(DocumentService.class)
                    .getByDocumentHeaderId(maintDoc.getDocumentNumber());
            Account oldAccount = (Account) oldMaintDoc.getDocumentBusinessObject();

            if (ObjectUtils.isNotNull(oldAccount.getAccountExpirationDate())
                    && oldAccount.getAccountExpirationDate().equals(newExpDate)) {
                return false;
            }
        } catch (WorkflowException ex) {
            LOG.warn("Error retrieving maintenance doc for doc #" + maintDoc.getDocumentNumber()
                    + ". This shouldn't happen.", ex);
        }
    }

    // When updating an account expiration date, the date must be today or later
    // Only run this test if this maintenance doc
    // is an edit doc
    boolean expDateHasChanged = false;

    // if the old version of the account had no expiration date, and the new
    // one has a date
    if (ObjectUtils.isNull(oldExpDate) && ObjectUtils.isNotNull(newExpDate)) {
        expDateHasChanged = true;
    }

    // if there was an old and a new expDate, but they're different
    else if (ObjectUtils.isNotNull(oldExpDate) && ObjectUtils.isNotNull(newExpDate)) {
        if (!oldExpDate.equals(newExpDate)) {
            expDateHasChanged = true;
        }
    }

    // if the expiration date hasn't changed, we're not interested
    if (!expDateHasChanged) {
        return false;
    }

    // make a shortcut to the newAccount
    Account newAccount = (Account) maintDoc.getNewMaintainableObject().getBusinessObject();

    /* expirationDate must be today or later than today (cannot be before today).
     * This rule doesn't apply to certain fund groups (C&G perhaps) according to
     * the parameter.
     */
    Collection<String> fundGroups = SpringContext.getBean(ParameterService.class).getParameterValuesAsString(
            Account.class, KFSConstants.ChartApcParms.EXPIRATION_DATE_BACKDATING_FUND_GROUPS);
    if (fundGroups != null && ObjectUtils.isNotNull(newAccount.getSubFundGroup())
            && fundGroups.contains(newAccount.getSubFundGroup().getFundGroupCode())) {
        return false;
    }
    return newExpDate.before(today);
}

From source file:org.kuali.kfs.coa.document.validation.impl.OrgRule.java

/**
 * This checks the following conditions:
 * <ul>/* w  w  w  . j  av a2 s.c  om*/
 * <li>begin date must be greater than or equal to end date</li>
 * <li>start date must be greater than or equal to today if new Document</li>
 * <li>Reports To Chart/Org should not be same as this Chart/Org</li>
 * </ul>
 *
 * @param document
 * @return true if it passes all the rules, false otherwise
 */
protected boolean checkSimpleRules(MaintenanceDocument document) {

    boolean success = true;
    String lastReportsToChartOfAccountsCode;
    String lastReportsToOrganizationCode;
    boolean continueSearch;
    Organization tempOrg;
    Integer loopCount;
    Integer maxLoopCount = 40;

    // begin date must be greater than or equal to end date
    if ((ObjectUtils.isNotNull(newOrg.getOrganizationBeginDate())
            && (ObjectUtils.isNotNull(newOrg.getOrganizationEndDate())))) {

        Date beginDate = newOrg.getOrganizationBeginDate();
        Date endDate = newOrg.getOrganizationEndDate();

        if (endDate.before(beginDate)) {
            putFieldError("organizationEndDate",
                    KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_END_DATE_GREATER_THAN_BEGIN_DATE);
            success &= false;
        }
    }

    // start date must be greater than or equal to today if new Document
    if ((ObjectUtils.isNotNull(newOrg.getOrganizationBeginDate()) && (document.isNew()))) {
        Timestamp today = getDateTimeService().getCurrentTimestamp();
        today.setTime(DateUtils.truncate(today, Calendar.DAY_OF_MONTH).getTime());
        if (newOrg.getOrganizationBeginDate().before(today)) {
            putFieldError("organizationBeginDate", KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_STARTDATE_IN_PAST);
            success &= false;
        }
    }

    // Reports To Chart/Org should not be same as this Chart/Org
    // However, allow special case where organization type is listed in the business rules
    if (ObjectUtils.isNotNull(newOrg.getReportsToChartOfAccountsCode())
            && ObjectUtils.isNotNull(newOrg.getReportsToOrganizationCode())
            && ObjectUtils.isNotNull(newOrg.getChartOfAccountsCode())
            && ObjectUtils.isNotNull(newOrg.getOrganizationCode())) {
        if (!getOrgMustReportToSelf(newOrg)) {

            if ((newOrg.getReportsToChartOfAccountsCode().equals(newOrg.getChartOfAccountsCode()))
                    && (newOrg.getReportsToOrganizationCode().equals(newOrg.getOrganizationCode()))) {
                putFieldError("reportsToOrganizationCode",
                        KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_CANNOT_BE_SAME_ORG);
                success = false;
            } else {
                // Don't allow a circular reference on Reports to Chart/Org
                // terminate the search when a top-level org is found
                lastReportsToChartOfAccountsCode = newOrg.getReportsToChartOfAccountsCode();
                lastReportsToOrganizationCode = newOrg.getReportsToOrganizationCode();
                continueSearch = true;
                loopCount = 0;
                do {
                    tempOrg = orgService.getByPrimaryId(lastReportsToChartOfAccountsCode,
                            lastReportsToOrganizationCode);
                    loopCount++;
                    ;
                    if (ObjectUtils.isNull(tempOrg)) {
                        continueSearch = false;
                        // if a null is returned on the first iteration, then the reports-to org does not exist
                        // fail the validation
                        if (loopCount == 1) {
                            putFieldError("reportsToOrganizationCode",
                                    KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_MUST_EXIST);
                            success = false;
                        }
                    } else {
                        // on the first iteration, check whether the reports-to organization is active
                        if (loopCount == 1 && !tempOrg.isActive()) {
                            putFieldError("reportsToOrganizationCode",
                                    KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_MUST_EXIST);
                            success = false;
                            continueSearch = false;
                        } else {
                            // LOG.info("Found Org = " + lastReportsToChartOfAccountsCode + "/" +
                            // lastReportsToOrganizationCode);
                            lastReportsToChartOfAccountsCode = tempOrg.getReportsToChartOfAccountsCode();
                            lastReportsToOrganizationCode = tempOrg.getReportsToOrganizationCode();

                            if ((tempOrg.getReportsToChartOfAccountsCode()
                                    .equals(newOrg.getChartOfAccountsCode()))
                                    && (tempOrg.getReportsToOrganizationCode()
                                            .equals(newOrg.getOrganizationCode()))) {
                                putFieldError("reportsToOrganizationCode",
                                        KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_CANNOT_BE_CIRCULAR_REF_TO_SAME_ORG);
                                success = false;
                                continueSearch = false;
                            }
                        }
                    }
                    if (loopCount > maxLoopCount) {
                        continueSearch = false;
                    }
                    // stop the search if we reach an org that must report to itself
                    if (continueSearch && /*REFACTORME*/SpringContext.getBean(ParameterEvaluatorService.class)
                            .getParameterEvaluator(Organization.class,
                                    KFSConstants.ChartApcParms.ORG_MUST_REPORT_TO_SELF_ORG_TYPES,
                                    tempOrg.getOrganizationTypeCode())
                            .evaluationSucceeds()) {
                        continueSearch = false;
                    }

                } while (continueSearch == true);
            } // end else (checking for circular ref)
        } else { // org must report to self (university level organization)
            if (!(newOrg.getReportsToChartOfAccountsCode().equals(newOrg.getChartOfAccountsCode())
                    && newOrg.getReportsToOrganizationCode().equals(newOrg.getOrganizationCode()))) {
                putFieldError("reportsToOrganizationCode",
                        KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_MUST_BE_SAME_ORG);
                success = false;
            }
            // org must be the only one of that type
            String topLevelOrgTypeCode = SpringContext.getBean(ParameterService.class)
                    .getParameterValueAsString(Organization.class,
                            KFSConstants.ChartApcParms.ORG_MUST_REPORT_TO_SELF_ORG_TYPES);
            List<Organization> topLevelOrgs = orgService.getActiveOrgsByType(topLevelOrgTypeCode);
            if (!topLevelOrgs.isEmpty()) {
                // is the new org in the topLevelOrgs list? If not, then there's an error; if so, we're editing the top level
                // org
                if (!topLevelOrgs.contains(newOrg)) {
                    putFieldError("organizationTypeCode",
                            KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_ONLY_ONE_TOP_LEVEL_ORG,
                            topLevelOrgs.get(0).getChartOfAccountsCode() + "-"
                                    + topLevelOrgs.get(0).getOrganizationCode());
                    success = false;
                }
            }
        }
    }

    return success;
}

From source file:org.kuali.kfs.fp.document.DisbursementVoucherDocument.java

/**
 * Convenience method to set dv payee detail fields based on a given vendor.
 *
 * @param vendor//from   w w  w .  j  ava2 s  .c  o  m
 */
public void templateVendor(VendorDetail vendor, VendorAddress vendorAddress) {
    if (vendor == null) {
        return;
    }

    this.getDvPayeeDetail().setDisbursementVoucherPayeeTypeCode(KFSConstants.PaymentPayeeTypes.VENDOR);
    this.getDvPayeeDetail().setDisbVchrPayeeIdNumber(vendor.getVendorNumber());
    this.getDvPayeeDetail().setDisbVchrPayeePersonName(vendor.getVendorName());

    this.getDvPayeeDetail().setDisbVchrAlienPaymentCode(vendor.getVendorHeader().getVendorForeignIndicator());

    if (ObjectUtils.isNotNull(vendorAddress)
            && ObjectUtils.isNotNull(vendorAddress.getVendorAddressGeneratedIdentifier())) {
        this.getDvPayeeDetail().setDisbVchrVendorAddressIdNumber(
                vendorAddress.getVendorAddressGeneratedIdentifier().toString());
        this.getDvPayeeDetail().setDisbVchrPayeeLine1Addr(vendorAddress.getVendorLine1Address());
        this.getDvPayeeDetail().setDisbVchrPayeeLine2Addr(vendorAddress.getVendorLine2Address());
        this.getDvPayeeDetail().setDisbVchrPayeeCityName(vendorAddress.getVendorCityName());
        this.getDvPayeeDetail().setDisbVchrPayeeStateCode(vendorAddress.getVendorStateCode());
        this.getDvPayeeDetail().setDisbVchrPayeeZipCode(vendorAddress.getVendorZipCode());
        this.getDvPayeeDetail().setDisbVchrPayeeCountryCode(vendorAddress.getVendorCountryCode());
    } else {
        this.getDvPayeeDetail().setDisbVchrVendorAddressIdNumber(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeLine1Addr(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeLine2Addr(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeCityName(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeStateCode(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeZipCode(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeCountryCode(StringUtils.EMPTY);
    }

    this.getDvPayeeDetail().setDisbVchrAlienPaymentCode(vendor.getVendorHeader().getVendorForeignIndicator());
    this.getDvPayeeDetail().setDvPayeeSubjectPaymentCode(
            VendorConstants.VendorTypes.SUBJECT_PAYMENT.equals(vendor.getVendorHeader().getVendorTypeCode()));
    this.getDvPayeeDetail().setDisbVchrEmployeePaidOutsidePayrollCode(
            getVendorService().isVendorInstitutionEmployee(vendor.getVendorHeaderGeneratedIdentifier()));

    this.getDvPayeeDetail().setHasMultipleVendorAddresses(1 < vendor.getVendorAddresses().size());

    boolean w9AndW8Checked = false;
    if ((ObjectUtils.isNotNull(vendor.getVendorHeader().getVendorW9ReceivedIndicator())
            && vendor.getVendorHeader().getVendorW9ReceivedIndicator() == true)
            || (ObjectUtils.isNotNull(vendor.getVendorHeader().getVendorW8BenReceivedIndicator())
                    && vendor.getVendorHeader().getVendorW8BenReceivedIndicator() == true)) {

        w9AndW8Checked = true;
    }

    //    this.disbVchrPayeeW9CompleteCode = vendor.getVendorHeader().getVendorW8BenReceivedIndicator()  == null ? false : vendor.getVendorHeader().getVendorW8BenReceivedIndicator();
    this.disbVchrPayeeW9CompleteCode = w9AndW8Checked;

    Date vendorFederalWithholdingTaxBeginDate = vendor.getVendorHeader()
            .getVendorFederalWithholdingTaxBeginningDate();
    Date vendorFederalWithholdingTaxEndDate = vendor.getVendorHeader().getVendorFederalWithholdingTaxEndDate();
    java.util.Date today = getDateTimeService().getCurrentDate();
    if ((vendorFederalWithholdingTaxBeginDate != null && vendorFederalWithholdingTaxBeginDate.before(today))
            && (vendorFederalWithholdingTaxEndDate == null
                    || vendorFederalWithholdingTaxEndDate.after(today))) {
        this.disbVchrPayeeTaxControlCode = DisbursementVoucherConstants.TAX_CONTROL_CODE_BEGIN_WITHHOLDING;
    }

    // if vendor is foreign, default alien payment code to true
    if (getVendorService().isVendorForeign(vendor.getVendorHeaderGeneratedIdentifier())) {
        getDvPayeeDetail().setDisbVchrAlienPaymentCode(true);
    }
}

From source file:org.kuali.kfs.module.ar.batch.service.impl.VerifyBillingFrequencyServiceImpl.java

@Override
public Date[] getStartDateAndEndDateOfPreviousBillingPeriod(ContractsAndGrantsBillingAward award,
        AccountingPeriod currPeriod) {//from ww  w  . j  av  a2  s.com
    Date[] startDt_EndDt = new Date[2];
    Date previousAccountingPeriodEndDay = null;
    Date previousAccountingPeriodStartDay = null;
    Date tmpEndDate;
    Date lastBilledDate = award.getLastBilledDate();
    String billingFrequency = award.getBillingFrequencyCode();
    ArrayList<Date> periodEndDateListOfCurrFiscalYear = getSortedListOfPeriodEndDatesOfCurrentFiscalYear(
            currPeriod);

    // this is used later on when obtaining the last date of the previous fiscal year as the previousAccountPeriodEndDay
    // it subtracts one from the fiscal year for the currPeriod passed in rather than assuming we want the
    // previous fiscal year to the current active fiscal year, just in case a past period is sent in as currPeriod
    // this is mostly just to facilitate unit tests but does make the code more robust (theoretically at least)
    int previousYear = currPeriod.getUniversityFiscalYear() - 1;

    int periodEndDateListOfCurrFiscalYearSize = 0;
    if (periodEndDateListOfCurrFiscalYear != null) {
        periodEndDateListOfCurrFiscalYearSize = periodEndDateListOfCurrFiscalYear.size();
    }

    // 2.billed monthly. ( Milestone and Predetermined Scheduled billing frequencies will also be invoiced as monthly.)
    if (billingFrequency.equalsIgnoreCase(ArConstants.MONTHLY_BILLING_SCHEDULE_CODE)
            || billingFrequency.equalsIgnoreCase(ArConstants.MILESTONE_BILLING_SCHEDULE_CODE)
            || billingFrequency.equalsIgnoreCase(ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {
        // 2.1 find end date
        if (lastBilledDate != null) {
            if (periodEndDateListOfCurrFiscalYearSize > 0 && currPeriod.getUniversityFiscalPeriodEndDate()
                    .equals(periodEndDateListOfCurrFiscalYear.get(0))) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime()); // assume the calendar date, discussion
            } else {
                int i = -1;
                for (i = 0; i < periodEndDateListOfCurrFiscalYear.size(); i++) {
                    if (currPeriod.getUniversityFiscalPeriodEndDate()
                            .equals(periodEndDateListOfCurrFiscalYear.get(i))) {
                        break;
                    }
                }

                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i - 1);
            }
        } else {
            if (periodEndDateListOfCurrFiscalYearSize > 0 && currPeriod.getUniversityFiscalPeriodEndDate()
                    .equals(periodEndDateListOfCurrFiscalYear.get(0))) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                // get end date by award's beginning date
                // if the lastBilledDate = null, means the the award is billed from its start date till the previous period end
                // date, so the calculation would be:
                int i = -1;
                for (i = 0; i < periodEndDateListOfCurrFiscalYear.size(); i++) {
                    if (currPeriod.getUniversityFiscalPeriodEndDate()
                            .equals(periodEndDateListOfCurrFiscalYear.get(i))) {
                        break;
                    }
                }

                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i - 1);
            }
        }

        // 2.2 find start date
        // PreviousAccountingPeriodStartDate = previous accounting period endDate of previous accounting period + 1 day
        // for example current date is 2012.8.16, then PreviousAccountingPeriodStartDate = 2012.6.30 + 1day, which is 2012.7.1

        AccountingPeriod period = accountingPeriodService.getByDate(previousAccountingPeriodEndDay);
        if (period.getUniversityFiscalYear().intValue() < currPeriod.getUniversityFiscalYear().intValue()) {

            if (lastBilledDate == null) {
                previousAccountingPeriodStartDay = award.getAwardBeginningDate();
            } else {
                ArrayList<Date> acctPeriodEndDateListOfPreviousFiscalYear = getSortedListOfPeriodEndDatesOfCurrentFiscalYear(
                        period);

                int i = -1;
                for (i = acctPeriodEndDateListOfPreviousFiscalYear.size() - 1; i >= 0; i -= 1) {
                    tmpEndDate = acctPeriodEndDateListOfPreviousFiscalYear.get(i);

                    if (tmpEndDate.before(previousAccountingPeriodEndDay)) {
                        previousAccountingPeriodStartDay = calculateNextDay(tmpEndDate);
                        break;
                    }
                }

            }
        } else if (period.getUniversityFiscalYear().intValue() == currPeriod.getUniversityFiscalYear()
                .intValue()) {
            if (lastBilledDate == null) {
                previousAccountingPeriodStartDay = award.getAwardBeginningDate();
            } else {
                if (periodEndDateListOfCurrFiscalYearSize > 0
                        && previousAccountingPeriodEndDay.equals(periodEndDateListOfCurrFiscalYear.get(0))) {
                    final Date firstDayOfCurrentFiscalYear = new Date(universityDateService
                            .getFirstDateOfFiscalYear(currPeriod.getUniversityFiscalYear()).getTime());
                    previousAccountingPeriodStartDay = firstDayOfCurrentFiscalYear;
                } else {
                    int i = -1;
                    for (i = 0; i < periodEndDateListOfCurrFiscalYear.size(); i++) {
                        tmpEndDate = periodEndDateListOfCurrFiscalYear.get(i);

                        if (!tmpEndDate.before(previousAccountingPeriodEndDay)) {
                            break;
                        }
                    }
                    previousAccountingPeriodStartDay = calculateNextDay(
                            periodEndDateListOfCurrFiscalYear.get(i - 1));
                }
            }
        }
    }

    // 3.billed quarterly
    if (billingFrequency.equalsIgnoreCase(ArConstants.QUATERLY_BILLING_SCHEDULE_CODE)) {
        // 3.1 find end date
        if (lastBilledDate != null) {
            if (periodEndDateListOfCurrFiscalYearSize > 2 && !currPeriod.getUniversityFiscalPeriodEndDate()
                    .after(periodEndDateListOfCurrFiscalYear.get(2))) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                int i = 0;
                for (i = 2; i < periodEndDateListOfCurrFiscalYear.size(); i += 3) {
                    // find the PreviousAccountingPeriodEndDate by current fiscal period end date and last billed date.
                    // for exmple, if current date is 2011.10.8, then the code will get out from for loop when looping to i =5
                    // (2011.12.31), so previous end date is 2011.9.30(i=5-3=2)
                    if (!currPeriod.getUniversityFiscalPeriodEndDate()
                            .after(periodEndDateListOfCurrFiscalYear.get(i))) {
                        break;
                    }
                }
                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i - 3);
            }

        } else {

            if (periodEndDateListOfCurrFiscalYearSize > 0 && currPeriod.getUniversityFiscalPeriodEndDate()
                    .equals(periodEndDateListOfCurrFiscalYear.get(0))) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                Date dt = accountingPeriodService.getByDate(award.getAwardBeginningDate())
                        .getUniversityFiscalPeriodEndDate();

                int i = -1;
                for (i = 2; i < periodEndDateListOfCurrFiscalYear.size(); i += 3) {
                    // find the closest period end date by the award beginning date,
                    // for exmple award is created on 7/15/2012 and billed quarterly, then the next billing date for this award is
                    // 9/30/2012
                    if (!dt.after(periodEndDateListOfCurrFiscalYear.get(i))) {
                        break;
                    }
                }
                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i);

            }
        }
        // 3.2 find start date
        // PreviousAccountingPeriodStartDate falls into previous fiscal year
        AccountingPeriod period = accountingPeriodService.getByDate(previousAccountingPeriodEndDay);
        if (lastBilledDate == null) {
            previousAccountingPeriodStartDay = award.getAwardBeginningDate();
        } else {
            if (period.getUniversityFiscalYear().intValue() < currPeriod.getUniversityFiscalYear().intValue()) {

                ArrayList<Date> acctPeriodEndDateListOfPreviousFiscalYear = getSortedListOfPeriodEndDatesOfCurrentFiscalYear(
                        period);

                int j = -1;
                for (j = acctPeriodEndDateListOfPreviousFiscalYear.size() - 1; j >= 0; j -= 3) {
                    tmpEndDate = acctPeriodEndDateListOfPreviousFiscalYear.get(j);

                    if (tmpEndDate.before(previousAccountingPeriodEndDay)) {
                        previousAccountingPeriodStartDay = calculateNextDay(tmpEndDate);
                        break;
                    }
                }

            } else if (period.getUniversityFiscalYear().intValue() == currPeriod.getUniversityFiscalYear()
                    .intValue()) {

                if (periodEndDateListOfCurrFiscalYearSize > 2
                        && !previousAccountingPeriodEndDay.after(periodEndDateListOfCurrFiscalYear.get(2))) {
                    final Date firstDayOfCurrentFiscalYear = new Date(universityDateService
                            .getFirstDateOfFiscalYear(currPeriod.getUniversityFiscalYear()).getTime());
                    previousAccountingPeriodStartDay = firstDayOfCurrentFiscalYear;
                } else {
                    int i = -1;
                    for (i = 2; i < periodEndDateListOfCurrFiscalYear.size(); i += 3) {
                        tmpEndDate = periodEndDateListOfCurrFiscalYear.get(i);

                        if (!tmpEndDate.before(previousAccountingPeriodEndDay)) {
                            break;
                        }
                    }
                    previousAccountingPeriodStartDay = calculateNextDay(
                            periodEndDateListOfCurrFiscalYear.get(i - 3));
                }
            }
        }
    }

    // 4.billed semi-annually
    if (billingFrequency.equalsIgnoreCase(ArConstants.SEMI_ANNUALLY_BILLING_SCHEDULE_CODE)) {
        // 4.1 find end date
        if (lastBilledDate != null) {
            // if the current month is in the first fiscal semi-year of the current year,
            // then get the last day of the previous fiscal year as PreviousAccountingPeriodEndDate
            if (!currPeriod.getUniversityFiscalPeriodEndDate()
                    .after(periodEndDateListOfCurrFiscalYear.get(5))) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                int i = -1;
                for (i = 5; i < periodEndDateListOfCurrFiscalYear.size(); i += 6) {
                    if (!currPeriod.getUniversityFiscalPeriodEndDate()
                            .after(periodEndDateListOfCurrFiscalYear.get(i))) {
                        break;
                    }
                }
                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i - 6);
            }
        } else {
            Date dt = accountingPeriodService.getByDate(award.getAwardBeginningDate())
                    .getUniversityFiscalPeriodEndDate();

            if (accountingPeriodService.getByDate(award.getAwardBeginningDate()).getUniversityFiscalYear()
                    .compareTo(currPeriod.getUniversityFiscalYear()) < 0) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                for (int i = 5; i < periodEndDateListOfCurrFiscalYear.size(); i += 6) {
                    // find the closest period end date by the award beginning date,
                    // for exmple award is created on 7/15/2012 and billed annually, then the next billing date for this award
                    // is 12/31/2012
                    if (dt.before(periodEndDateListOfCurrFiscalYear.get(i))
                            || dt.equals(periodEndDateListOfCurrFiscalYear.get(i))) {
                        previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i);
                        break;
                    }
                }
            }
        }

        // 4.2 find start date
        // PreviousAccountingPeriodStartDate falls into previous fiscal year
        AccountingPeriod period = accountingPeriodService.getByDate(previousAccountingPeriodEndDay);
        if (lastBilledDate == null) {
            previousAccountingPeriodStartDay = award.getAwardBeginningDate();
        } else {
            if (period.getUniversityFiscalYear() < currPeriod.getUniversityFiscalYear()) {
                ArrayList<Date> periodEndDateListOfPreviousFiscalYear = getSortedListOfPeriodEndDatesOfCurrentFiscalYear(
                        period);

                int i = -1;
                for (i = periodEndDateListOfPreviousFiscalYear.size() - 1; i >= 0; i -= 6) {
                    tmpEndDate = periodEndDateListOfPreviousFiscalYear.get(i);

                    if (tmpEndDate.before(previousAccountingPeriodEndDay)) {
                        previousAccountingPeriodStartDay = calculateNextDay(tmpEndDate);
                        break;
                    }
                }

            }
            // PreviousAccountingPeriodStartDate falls into current fiscal year
            else if (period.getUniversityFiscalYear().intValue() == currPeriod.getUniversityFiscalYear()
                    .intValue()) {

                // previousAccoutingPeriodEndDay falls in the first fiscal period
                if (!previousAccountingPeriodEndDay.after(periodEndDateListOfCurrFiscalYear.get(5))) {
                    final Date firstDayOfCurrentFiscalYear = new Date(universityDateService
                            .getFirstDateOfFiscalYear(currPeriod.getUniversityFiscalYear()).getTime());
                    previousAccountingPeriodStartDay = firstDayOfCurrentFiscalYear;
                }
                // previousAccoutingPeriodEndDay does not falls in the first fiscal period
                else {
                    int i = -1;
                    for (i = 5; i < periodEndDateListOfCurrFiscalYear.size(); i += 6) {
                        tmpEndDate = periodEndDateListOfCurrFiscalYear.get(i);

                        if (!tmpEndDate.before(previousAccountingPeriodEndDay)) {
                            break;
                        }
                    }
                    previousAccountingPeriodStartDay = calculateNextDay(
                            periodEndDateListOfCurrFiscalYear.get(i - 6));

                }
            }
        }
    }

    // 5.billed annually
    if (billingFrequency.equalsIgnoreCase(ArConstants.ANNUALLY_BILLING_SCHEDULE_CODE)) {
        // 5.1 find end date
        if (lastBilledDate != null) {
            previousAccountingPeriodEndDay = new Date(
                    universityDateService.getLastDateOfFiscalYear(previousYear).getTime()); // assume the calendar date, discussion needed
        } else {
            if (accountingPeriodService.getByDate(award.getAwardBeginningDate()).getUniversityFiscalYear()
                    .compareTo(currPeriod.getUniversityFiscalYear()) < 0) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(11);
            }
        }

        // 5.2 find start date
        if (lastBilledDate == null) {
            previousAccountingPeriodStartDay = award.getAwardBeginningDate();
        } else {
            previousAccountingPeriodStartDay = new Date(
                    universityDateService.getFirstDateOfFiscalYear(previousYear).getTime());
        }
    }

    // 6.billed for LOC Review - A Random billing period
    if (billingFrequency.equalsIgnoreCase(ArConstants.LOC_BILLING_SCHEDULE_CODE)) {

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        previousAccountingPeriodEndDay = new Date(cal.getTime().getTime());

        // 5.2 find start date
        if (lastBilledDate == null) {
            previousAccountingPeriodStartDay = award.getAwardBeginningDate();
        } else {
            previousAccountingPeriodStartDay = calculateNextDay(lastBilledDate);
        }
    }

    startDt_EndDt[0] = previousAccountingPeriodStartDay;
    startDt_EndDt[1] = previousAccountingPeriodEndDay;
    return startDt_EndDt;
}

From source file:org.kuali.kfs.module.ar.document.CustomerInvoiceDocument.java

/**
 * If this invoice is a reversal, set the open indicator to false
 *
 * @see org.kuali.kfs.sys.document.FinancialSystemTransactionalDocumentBase#prepareForSave()
 *//*from ww w. jav  a 2 s . c o  m*/
@Override
public void prepareForSave() {
    if (this.isInvoiceReversal()) {
        setOpenInvoiceIndicator(false);
    }

    //  make sure the docHeader gets its doc total right.  This is here because there's an ordering
    // bug in the struts classes for invoice that is preventing this from being set right.  There is
    // probably a better way to fix this that can be pursued later.
    getFinancialSystemDocumentHeader().setFinancialDocumentTotalAmount(getTotalDollarAmount());

    captureWorkflowHeaderInformation();

    //  invoice recurrence stuff, if there is a recurrence object
    if (ObjectUtils.isNotNull(this.getCustomerInvoiceRecurrenceDetails()) && getProcessRecurrenceFlag()) {

        //  wire up the recurrence customer number if one exists
        if (ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getCustomerNumber())) {
            this.getCustomerInvoiceRecurrenceDetails()
                    .setCustomerNumber(this.getAccountsReceivableDocumentHeader().getCustomerNumber());
        }

        customerInvoiceRecurrenceDetails.setInvoiceNumber(getDocumentNumber());

        // calc recurrence number if only end-date specified
        if (ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentTotalRecurrenceNumber())
                && ObjectUtils
                        .isNotNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate())) {

            Calendar beginCalendar = Calendar.getInstance();
            beginCalendar.setTime(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate());
            Date beginDate = this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate();
            Calendar endCalendar = Calendar.getInstance();

            endCalendar.setTime(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate());
            Date endDate = this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate();
            Calendar nextCalendar = Calendar.getInstance();
            Date nextDate = beginDate;

            int totalRecurrences = 0;
            int addCounter = 0;
            String intervalCode = this.getCustomerInvoiceRecurrenceDetails()
                    .getDocumentRecurrenceIntervalCode();
            if (intervalCode.equals("M")) {
                addCounter = 1;
            }
            if (intervalCode.equals("Q")) {
                addCounter = 3;
            }
            /* perform this loop while begin_date is less than or equal to end_date */
            while (!(beginDate.after(endDate))) {
                beginCalendar.setTime(beginDate);
                beginCalendar.add(Calendar.MONTH, addCounter);
                beginDate = KfsDateUtils.convertToSqlDate(beginCalendar.getTime());
                totalRecurrences++;

                nextDate = beginDate;
                nextCalendar.setTime(nextDate);
                nextCalendar.add(Calendar.MONTH, addCounter);
                nextDate = KfsDateUtils.convertToSqlDate(nextCalendar.getTime());
                if (endDate.after(beginDate) && endDate.before(nextDate)) {
                    totalRecurrences++;
                    break;
                }
            }
            if (totalRecurrences > 0) {
                this.getCustomerInvoiceRecurrenceDetails().setDocumentTotalRecurrenceNumber(totalRecurrences);
            }
        }

        //  calc end-date if only recurrence-number is specified
        if (ObjectUtils.isNotNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentTotalRecurrenceNumber())
                && ObjectUtils
                        .isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate())) {

            Calendar beginCalendar = Calendar.getInstance();
            beginCalendar.setTime(new Timestamp(
                    this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate().getTime()));
            Calendar endCalendar = Calendar.getInstance();
            endCalendar = beginCalendar;

            int addCounter = 0;
            Integer documentTotalRecurrenceNumber = this.getCustomerInvoiceRecurrenceDetails()
                    .getDocumentTotalRecurrenceNumber();
            String intervalCode = this.getCustomerInvoiceRecurrenceDetails()
                    .getDocumentRecurrenceIntervalCode();
            if (intervalCode.equals("M")) {
                addCounter = -1;
                addCounter += documentTotalRecurrenceNumber * 1;
            }
            if (intervalCode.equals("Q")) {
                addCounter = -3;
                addCounter += documentTotalRecurrenceNumber * 3;
            }
            endCalendar.add(Calendar.MONTH, addCounter);
            this.getCustomerInvoiceRecurrenceDetails()
                    .setDocumentRecurrenceEndDate(KfsDateUtils.convertToSqlDate(endCalendar.getTime()));
        }
    }

    // Force upper case
    //TODO Force to upper case here since DD forceUpperCase doesn't work. Revert this temp fix after Rice fix.
    setBilledByOrganizationCode(StringUtils.upperCase(billedByOrganizationCode));
    accountsReceivableDocumentHeader.setProcessingOrganizationCode(
            StringUtils.upperCase(accountsReceivableDocumentHeader.getProcessingOrganizationCode()));
    accountsReceivableDocumentHeader
            .setCustomerNumber(StringUtils.upperCase(accountsReceivableDocumentHeader.getCustomerNumber()));

    if (ObjectUtils.isNull(getCustomerShipToAddressIdentifier())) {
        setCustomerShipToAddress(null);
        setCustomerShipToAddressOnInvoice(null);
    }

}

From source file:org.kuali.kfs.module.ar.document.service.impl.ContractsGrantsBillingAwardVerificationServiceImpl.java

/**
 * @see org.kuali.kfs.module.ar.document.service.ContractsGrantsInvoiceDocumentService#hasNoMilestonesToInvoice(org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAward)
 *//*w w w . j ava  2  s .co m*/
@Override
public boolean hasMilestonesToInvoice(ContractsAndGrantsBillingAward award) {
    boolean hasMilestonesToInvoice = true;
    if (award.getBillingFrequencyCode().equalsIgnoreCase(ArConstants.MILESTONE_BILLING_SCHEDULE_CODE)) {
        List<Milestone> milestones = new ArrayList<Milestone>();
        List<Milestone> validMilestones = new ArrayList<Milestone>();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put(KFSPropertyConstants.PROPOSAL_NUMBER, award.getProposalNumber());
        map.put(KFSPropertyConstants.ACTIVE, true);
        milestones = (List<Milestone>) businessObjectService.findMatching(Milestone.class, map);

        // To retrieve the previous period end Date to check for milestones and billing schedule.

        Timestamp ts = new Timestamp(new java.util.Date().getTime());
        java.sql.Date today = new java.sql.Date(ts.getTime());
        AccountingPeriod currPeriod = accountingPeriodService.getByDate(today);
        java.sql.Date[] pair = verifyBillingFrequencyService
                .getStartDateAndEndDateOfPreviousBillingPeriod(award, currPeriod);
        java.sql.Date invoiceDate = pair[1];

        for (Milestone awdMilestone : milestones) {
            if (awdMilestone.getMilestoneActualCompletionDate() != null
                    && !invoiceDate.before(awdMilestone.getMilestoneActualCompletionDate())
                    && !awdMilestone.isBilled()
                    && awdMilestone.getMilestoneAmount().isGreaterThan(KualiDecimal.ZERO)) {
                validMilestones.add(awdMilestone);
            }
        }
        if (CollectionUtils.isEmpty(validMilestones)) {
            hasMilestonesToInvoice = false;
        }
    }
    return hasMilestonesToInvoice;
}