List of usage examples for java.math BigDecimal toPlainString
public String toPlainString()
From source file:com.gst.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java
private void checkIfLoanIsPaidInAdvance(final Long loanId, final BigDecimal transactionAmount) { BigDecimal overpaid = this.loanReadPlatformService.retrieveTotalPaidInAdvance(loanId).getPaidInAdvance(); if (overpaid == null || overpaid.equals(new BigDecimal(0)) || transactionAmount.floatValue() > overpaid.floatValue()) { if (overpaid == null) overpaid = BigDecimal.ZERO; throw new InvalidPaidInAdvanceAmountException(overpaid.toPlainString()); }/*w ww. j a v a 2 s . c o m*/ }
From source file:edu.bu.kuali.kra.award.sapintegration.SapIntegrationServiceImpl.java
/** * Implements section 1.7.4, 1.7.5, and 1.7.6 of the functional specification. * * @param award the award for which to generate a sponsored program * @param costSharing indicates if this is a cost sharing program or not, if true then this method produces a * sponsored program structure which compiles with specification section 1.7.4, if false then it will generate * one which complies with specification section 1.7.5 * @param parentAward true if the given award is a parent award, false otherwise * @return//from www. j a v a2 s .co m */ protected ZGMSPPROGRAMSTRUCTURE constructSponsoredProgram(Award award, boolean costSharing) { CustomAwardDataHelper helper = new CustomAwardDataHelper(award); AwardBudgetExt abvoe = getLastBudgetVersion(award.getAwardDocument()); boolean awardBudgetVersionToBePosted = false; if (abvoe != null) { String budgetStatus = abvoe.getAwardBudgetStatusCode(); awardBudgetVersionToBePosted = Constants.BUDGET_STATUS_CODE_TO_BE_POSTED.equalsIgnoreCase(budgetStatus); } ZGMSPPROGRAMSTRUCTURE sponsoredProgramStructure = objectFactory.createZGMSPPROGRAMSTRUCTURE(); if (helper.getLastTransmissionDate() == null) { sponsoredProgramStructure.setSPPROGRAMUPDATE(INTERFACE_NEW); } else { sponsoredProgramStructure.setSPPROGRAMUPDATE(INTERFACE_UPDATE); } sponsoredProgramStructure.setSPPROGRAMNUMBER(award.getAccountNumber()); // Handle data which is shared between 1.7.4 and 1.7.5 // Position 1 if (StringUtils.isEmpty(award.getAccountNumber())) { sponsoredProgramStructure.setSPONSOREDPROG(award.getAwardNumber()); } else { sponsoredProgramStructure.setSPONSOREDPROG(award.getAccountNumber()); } AwardAmountInfo awardAmountInfo = getAwardAmountInfoService() .fetchLastAwardAmountInfoForAwardVersionAndFinalizedTandMDocumentNumber(award); // Position 3 sponsoredProgramStructure.setZZVALIDFROM(dateToString(awardAmountInfo.getCurrentFundEffectiveDate())); // Position 4 sponsoredProgramStructure.setZZVALIDTO(dateToString(awardAmountInfo.getObligationExpirationDate())); // Position 6 sponsoredProgramStructure.setBUSINESSAREA(convertLeadUnitToBusinessArea(award.getLeadUnitNumber(), award)); // Position 7 GMSPPROGRAMFMBTTT programFmbtTt = objectFactory.createGMSPPROGRAMFMBTTT(); GMSPPROGRAMFMBT programFmbt = objectFactory.createGMSPPROGRAMFMBT(); programFmbtTt.getItem().add(programFmbt); sponsoredProgramStructure.setTGMSPPROGRAMFMBT(programFmbtTt); programFmbt.setSPONSOREDPROG(award.getAccountNumber()); programFmbt.setFUNCTIONALAREA(convertActivityTypeToFunctionalArea(award.getActivityTypeCode(), award)); // Position 8 // If this is a cost sharing sponsored program then it is sourced from the parent award, but they don't have // budgets so the F and A rate would not be able to be calculated. // also, parent awards cant have budgets, so check to see if their are children as well AwardHierarchy hierarchy = getAwardHierarchyService().loadAwardHierarchy(award.getAwardNumber()); String overheadKey = ""; if (!awardBudgetVersionToBePosted) { // BU Customization ID: N/A mkousheh 20120504 - Get the latest child that matches that was successful transmitted AwardTransmissionChild lastTransmittedChild = getLatestChildAwardTransmitted( hierarchy.getRoot().getAward(), award.getAwardNumber(), true); if (lastTransmittedChild != null) { overheadKey = lastTransmittedChild.getOverheadKey(); } // BU Customization ID: N/A mkousheh 20120504 - Commented out the following code and replaced with the above - // BUG (it gets latest transmitted then matches the child, sometimes no matching child in the last transmission // AwardTransmission lastTransmission = getLatestAwardTransmission(hierarchy.getRoot().getAward(), true); // if (lastTransmission != null) { // AwardTransmissionChild lastChildTransmission = findMatchingTransmissionChild(lastTransmission.getTransmissionChildren(), award.getAwardNumber()); // if (lastChildTransmission != null) { // overheadKey = lastChildTransmission.getOverheadKey(); // } // } // BU Customization ID: N/A mkousheh N/A - Switching this to use value saved on last transmission child - // BigDecimal fAndARate = calculateApplicableFandARate(award); // if(fAndARate != null) { // sponsoredProgramStructure.setOVERHEADKEY(StringUtils.leftPad(fAndARate.toPlainString(), 6, "0")); // } } else if (!costSharing && !hierarchy.hasChildren() && awardBudgetVersionToBePosted) { BigDecimal fAndARate = calculateApplicableFandARate(award); if (fAndARate != null && (((AwardExtension) award.getExtension()).getSteppedUpRate() == null || "NA".equalsIgnoreCase(((AwardExtension) award.getExtension()).getSteppedUpRate()))) { overheadKey = StringUtils.leftPad(fAndARate.toPlainString(), 6, "0"); } else { // get the system parameter for these values and lookup the mapping value based on the date overheadKey = getParameterService().getSubParameterValueAsString(AwardDocument.class, BUConstants.FEDERAL_RATE_DATE_OVERHEAD_KEY_FIELD_MAPPINGS, ((AwardExtension) award.getExtension()).getSteppedUpRate()); if (fAndARate == null || StringUtils.isBlank(overheadKey)) { overheadKey = ("000.00"); } } } sponsoredProgramStructure.setOVERHEADKEY(overheadKey); GlobalVariables.getUserSession().addObject("overheadKey-".concat(award.getAwardNumber()), (Object) overheadKey); LOG.info("Writing overheadKey to session: " + overheadKey); // Position 9 programFmbt.setFUNDSCENTER(StringUtils.rightPad(award.getLeadUnitNumber(), 10, "0")); // Position 11 sponsoredProgramStructure.setZZREFERENCE(award.getAwardNumber()); // Position 12 sponsoredProgramStructure.setZZAWARDNO(award.getSponsorAwardNumber()); // Position 13 sponsoredProgramStructure.setZZDOCNO(award.getDocumentFundingId()); AwardBudgetExt budget = null; if (!costSharing) { budget = award.getAwardDocument().getBudgetVersionOverview(); if (budget == null) { throw new IllegalArgumentException( "Award with number " + award.getAwardNumber() + " does not have a budget."); } } // BU Customization ID: N/A mkousheh 20110706 - In case of CostSharing check if updated boolean costSharesHaveChanged = false; if (costSharing) { AwardCostShare tmpAwardCostShare = getMostRecentAwardCostShare(award); if (tmpAwardCostShare != null && ((AwardExtension) award.getExtension()).getLastTransmissionDate() != null && tmpAwardCostShare.getUpdateTimestamp() != null && ((AwardExtension) award.getExtension()) .getLastTransmissionDate().before(tmpAwardCostShare.getUpdateTimestamp())) { costSharesHaveChanged = true; } } // if (!costSharesHaveChanged) { // Position 17 if (awardBudgetVersionToBePosted && budget != null && budget.getTotalDirectCost() != null) { sponsoredProgramStructure.setBUDGETTDC(budget.getTotalDirectCost().bigDecimalValue()); } else { sponsoredProgramStructure.setBUDGETTDC(ScaleTwoDecimal.ZERO.bigDecimalValue()); } // Position 18 if (awardBudgetVersionToBePosted && budget != null && budget.getTotalIndirectCost() != null) { sponsoredProgramStructure.setBUDGETFA(budget.getTotalIndirectCost().bigDecimalValue()); } else { sponsoredProgramStructure.setBUDGETFA(ScaleTwoDecimal.ZERO.bigDecimalValue()); } // } // BU Customization ID: N/A mkousheh 20110712 - If Parent Award Transaction is NoCostExtention or Administrative Changes Set Budget to zero if (hierarchy.getRoot().getAward().getAwardTransactionTypeCode() != null) { if (hierarchy.getRoot().getAward().getAwardTransactionTypeCode().equals(10) || hierarchy.getRoot().getAward().getAwardTransactionTypeCode().equals(6)) { sponsoredProgramStructure.setBUDGETTDC(ScaleTwoDecimal.ZERO.bigDecimalValue()); sponsoredProgramStructure.setBUDGETFA(ScaleTwoDecimal.ZERO.bigDecimalValue()); } } // Position 19 boolean fringeNotAllowed = helper.isFringeNotAllowed(); sponsoredProgramStructure .setFRINGECODE(FringeCodeMapping.mapToSapFringeCode(fringeNotAllowed, award.getAccountTypeCode())); /** * Data which is only part of 1.7.4 */ if (!costSharing && !hierarchy.hasChildren()) { // Position 10 sponsoredProgramStructure.setZZORDCAT(convertChildType(helper.getChildType(), award)); // Position 14 String offCampus = null; if (!awardBudgetVersionToBePosted) { // BU Customization ID: N/A mkousheh 20120504 - Get the latest child that matches that was successful transmitted // AwardTransmission lastTransmission = getLatestAwardTransmission(hierarchy.getRoot().getAward(), true); // if (lastTransmission != null) { // AwardTransmissionChild lastChildTransmission = findMatchingTransmissionChild(lastTransmission.getTransmissionChildren(), award.getAwardNumber()); // if (lastChildTransmission != null) { // offCampus = lastChildTransmission.getOffCampus(); // } // } AwardTransmissionChild lastTransmittedChild = getLatestChildAwardTransmitted( hierarchy.getRoot().getAward(), award.getAwardNumber(), true); if (lastTransmittedChild != null) { offCampus = lastTransmittedChild.getOffCampus(); } } else if (budget != null) { offCampus = budget.getOnOffCampusFlag(); } sponsoredProgramStructure.setZZOFFCAMPUS(offCampus); GlobalVariables.getUserSession().addObject("offCampus-".concat(award.getAwardNumber()), (Object) offCampus); LOG.info("Writing offCampus to session: " + offCampus); // Position 16 String baseCode = null; if (!awardBudgetVersionToBePosted) { // BU Customization ID: N/A mkousheh 20120504 - Get the latest child that matches that was successful transmitted // AwardTransmission lastTransmission = getLatestAwardTransmission(hierarchy.getRoot().getAward(), true); // if (lastTransmission != null) { // AwardTransmissionChild lastChildTransmission = findMatchingTransmissionChild(lastTransmission.getTransmissionChildren(), award.getAwardNumber()); // if (lastChildTransmission != null) { // baseCode = lastChildTransmission.getBaseCode(); // } // } AwardTransmissionChild lastTransmittedChild = getLatestChildAwardTransmitted( hierarchy.getRoot().getAward(), award.getAwardNumber(), true); if (lastTransmittedChild != null) { baseCode = lastTransmittedChild.getBaseCode(); } } else if (budget != null) { // AAP removed per whit - && awardBudgetVersionToBePosted baseCode = budget.getOhRateClassCode(); } sponsoredProgramStructure.setBASECODE(baseCode); GlobalVariables.getUserSession().addObject("baseCode-".concat(award.getAwardNumber()), (Object) baseCode); LOG.info("Writing baseCode to session: " + baseCode); // Position 20 sponsoredProgramStructure.setDESCRIPTION(helper.getChildDescription()); // Position 21 // BU Customization ID: N/A mkousheh 20110816 - SUBRecipient no longer needed // ZFIGMSUBRECIPIENTTAB awardApprovedSubawards = objectFactory.createZFIGMSUBRECIPIENTTAB(); // sponsoredProgramStructure.setTSUBRECIPIENT(awardApprovedSubawards); // List<AwardApprovedSubaward> subawards = award.getAwardApprovedSubawards(); // for (AwardApprovedSubaward subaward : subawards) { // GMSUBRECIPIENT awardApprovedSubaward = objectFactory.createGMSUBRECIPIENT(); // awardApprovedSubawards.getItem().add(awardApprovedSubaward); // awardApprovedSubaward.setSUBRECIPIENT(subaward.getOrganizationId()); // awardApprovedSubaward.setSUBNAME(subaward.getOrganizationName()); // awardApprovedSubaward.setSUBAMOUNT(subaward.getAmount().bigDecimalValue()); // } // AwardApprovedSubaward awardApprovedSubaward = getMostRecentAwardApprovedSubaward(award); // if (awardApprovedSubaward != null) { // ZGMSUBRECIPIENT subRecipent = new ZGMSUBRECIPIENT(); // subRecipent.setSUBRECIPIENT(awardApprovedSubaward.getOrganizationId()); // subRecipent.setSUBNAME(awardApprovedSubaward.getOrganizationName()); // subRecipent.setSUBAMOUNT(awardApprovedSubaward.getAmount().bigDecimalValue()); // sponsoredProgramStructure.setZZSUBRECIPIENT(subRecipent); // sponsoredProgramStructure.setZZSUBRECIPIENT(awardApprovedSubaward.getOrganizationId()); // } // Position 22 sponsoredProgramStructure.setKCRMSTATUS(StringUtils.leftPad(award.getStatusCode().toString(), 2, "0")); // Position 23 sponsoredProgramStructure.setSPONSOR(award.getSponsorCode()); // Position 24 sponsoredProgramStructure.setPRIMESPONSOR(award.getPrimeSponsorCode()); /** * Specification section 1.7.6 */ ZFIGMSPRESPONSIBLETABKCRM sponsoredProgramPersons = objectFactory.createZFIGMSPRESPONSIBLETABKCRM(); sponsoredProgramStructure.setTRESPONSIBLE(sponsoredProgramPersons); List<AwardPerson> persons = award.getProjectPersons(); for (AwardPerson person : persons) { ZGMSPRESPONSIBLEKCRM sponsoredProgramPerson = objectFactory.createZGMSPRESPONSIBLEKCRM(); sponsoredProgramPersons.getItem().add(sponsoredProgramPerson); sponsoredProgramPerson.setSPONSOREDPROG(award.getAccountNumber()); sponsoredProgramPerson.setOBJECTID(person.getPersonId()); sponsoredProgramPerson.setOBJECTNAME(person.getFullName()); // BUKC-0062: SAP Interface - Handle multiple PIs for NIH awards when transmit to SAP if (person.isMultiplePi()) { sponsoredProgramPerson.setRESPONSIBILITY("PI"); } else { sponsoredProgramPerson.setRESPONSIBILITY( convertProjectRoleToResponsibility(person.getContactRoleCode(), award)); } } // BU Customization ID: N/A mkousheh 20110828 - Add DAs to SponsoredPrograms for (AwardUnitContact awardContact : award.getAwardUnitContacts()) { if ("2".equals(awardContact.getUnitAdministratorTypeCode())) { ZGMSPRESPONSIBLEKCRM sponsoredProgramPerson = objectFactory.createZGMSPRESPONSIBLEKCRM(); sponsoredProgramPersons.getItem().add(sponsoredProgramPerson); sponsoredProgramPerson.setOBJECTID(awardContact.getPersonId()); sponsoredProgramPerson.setOBJECTNAME(awardContact.getFullName()); sponsoredProgramPerson.setRESPONSIBILITY("DA"); } if ("6".equals(awardContact.getUnitAdministratorTypeCode())) { ZGMSPRESPONSIBLEKCRM sponsoredProgramPerson = objectFactory.createZGMSPRESPONSIBLEKCRM(); sponsoredProgramPersons.getItem().add(sponsoredProgramPerson); sponsoredProgramPerson.setOBJECTID(awardContact.getPersonId()); sponsoredProgramPerson.setOBJECTNAME(awardContact.getPerson().getFullName()); sponsoredProgramPerson.setRESPONSIBILITY("OAV"); } // BUKC-0140: Add new Admin Type (Clinical Trial Admin) if ("8".equals(awardContact.getUnitAdministratorTypeCode())) { ZGMSPRESPONSIBLEKCRM sponsoredProgramPerson = objectFactory.createZGMSPRESPONSIBLEKCRM(); sponsoredProgramPersons.getItem().add(sponsoredProgramPerson); sponsoredProgramPerson.setOBJECTID(awardContact.getPersonId()); sponsoredProgramPerson.setOBJECTNAME(awardContact.getPerson().getFullName()); sponsoredProgramPerson.setRESPONSIBILITY("CTAD"); } } } /** * Data which is only part of 1.7.5 */ ScaleTwoDecimal costSharCommitmentMinusMemoMatch = getTotalCostShareCommitmentAmountMinusMemoMatch(award); if (costSharing && costSharCommitmentMinusMemoMatch != null && costSharCommitmentMinusMemoMatch.isPositive()) { // Position 2 // Sponsored_Program_type - according to Whit - this does not need to be sent // Position 10 sponsoredProgramStructure.setZZORDCAT("CS1"); // Position 14 sponsoredProgramStructure.setZZOFFCAMPUS("Y"); // Position 21 sponsoredProgramStructure.setKCRMSTATUS(award.getStatusCode().toString()); sponsoredProgramStructure.setBUDGETTDC(costSharCommitmentMinusMemoMatch.bigDecimalValue()); // getTotalDirectCost() // BU Customization ID: N/A mkousheh 20120731 - Remove the work around as SAP team fixed the issue on their side /* // Temporary fix for Cost Sharing. When we send an update for a Cost Sharing Sponsored Program the Budget_TDC and Budget_FA should default to 0.00 AwardTransmission lastTransmission = getLatestAwardTransmission(hierarchy.getRoot().getAward(), true); if (lastTransmission != null) { AwardTransmissionChild lastChildTransmission = findMatchingTransmissionChild(lastTransmission.getTransmissionChildren(), award.getAwardNumber()); if (isCostSharing(award) && helper.getLastTransmissionDate() != null) { sponsoredProgramStructure.setBUDGETTDC(ScaleTwoDecimal.ZERO.bigDecimalValue()); sponsoredProgramStructure.setBUDGETFA(ScaleTwoDecimal.ZERO.bigDecimalValue()); } } // end temporary fix */ // BU Customization ID: N/A mkousheh 20120808 - Set 000.00 for overhead rate when cost sharing sponsoredProgramStructure.setOVERHEADKEY("000.00"); AwardCostShare awardCostShare = getMostRecentAwardCostShare(award); if (awardCostShare != null && awardCostShare.getDestination() != null) { sponsoredProgramStructure.setSPONSOREDPROG(awardCostShare.getDestination()); } else { sponsoredProgramStructure.setSPONSOREDPROG(award.getAwardNumber()); } } return sponsoredProgramStructure; }
From source file:org.openbravo.costing.AverageCostAdjustment.java
@Override protected void getRelatedTransactionsByAlgorithm() { // Search all transactions after the date of the adjusted line and recalculate the costs of them // to adjust differences MaterialTransaction basetrx = getTransaction(); // Transactions of closing inventories are managed by generic CostAdjustmentProcess adjusting // the cost of the related opening inventory. if (basetrx.getPhysicalInventoryLine() != null && basetrx.getPhysicalInventoryLine().getRelatedInventory() != null) { return;/*w w w . jav a 2 s . co m*/ } BigDecimal signMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum()); Date trxDate = basetrx.getTransactionProcessDate(); BigDecimal adjustmentBalance = BigDecimal.ZERO; BigDecimal unitCostAdjustmentBalance = BigDecimal.ZERO; // Initialize adjustment balance looping through all cost adjustment lines of current // transaction. log.debug("Initialize adjustment balance"); CostAdjustmentLine baseCAL = getCostAdjLine(); for (CostAdjustmentLine costAdjLine : getTrxAdjustmentLines(basetrx)) { if (costAdjLine.isSource() && !costAdjLine.isRelatedTransactionAdjusted() && !costAdjLine.getId().equals(strCostAdjLineId)) { searchRelatedTransactionCosts(costAdjLine); } costAdjLine.setRelatedTransactionAdjusted(Boolean.TRUE); if (!costAdjLine.getId().equals(strCostAdjLineId)) { costAdjLine.setParentCostAdjustmentLine(baseCAL); } OBDal.getInstance().save(costAdjLine); // If the cost adjustment line has Transaction Costs those adjustment amount are included // in the Current Value Amount and not in the Adjustment Balance if (!costAdjLine.getTransactionCostList().isEmpty()) { continue; } BigDecimal adjustmentAmt = costAdjLine.getAdjustmentAmount(); if (!strCostCurrencyId.equals(costAdjLine.getCurrency().getId())) { adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt, costAdjLine.getCurrency(), getCostCurrency(), costAdjLine.getAccountingDate(), getCostOrg(), FinancialUtils.PRECISION_STANDARD); } adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(signMultiplier)); if (costAdjLine.isUnitCost()) { unitCostAdjustmentBalance = unitCostAdjustmentBalance.add(adjustmentAmt); } } // Initialize current stock qty and value amt. BigDecimal currentStock = CostAdjustmentUtils.getStockOnTransactionDate(getCostOrg(), basetrx, getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed); BigDecimal currentValueAmt = CostAdjustmentUtils.getValuedStockOnTransactionDate(getCostOrg(), basetrx, getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed, getCostCurrency()); log.debug( "Adjustment balance: " + adjustmentBalance.toPlainString() + ", current stock {}, current value {}", currentStock.toPlainString(), currentValueAmt.toPlainString()); // Initialize current unit cost including the cost adjustments. Costing costing = AverageAlgorithm.getProductCost(trxDate, basetrx.getProduct(), getCostDimensions(), getCostOrg()); if (costing == null) { throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName() + ", @Product@: " + basetrx.getProduct().getName() + ", @Date@: " + OBDateUtils.formatDate(trxDate)); } BigDecimal cost = null; // If current stock is zero the cost is not modified until a related transaction that modifies // the stock is found. if (currentStock.signum() != 0) { cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission, RoundingMode.HALF_UP); } log.debug("Starting average cost {}", cost == null ? "not cost" : cost.toPlainString()); if (cost != null && (AverageAlgorithm.modifiesAverage(trxType) || !baseCAL.isBackdatedTrx())) { BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(basetrx, true, getCostCurrency()); BigDecimal trxPrice = null; if (basetrx.getMovementQuantity().signum() == 0) { trxPrice = BigDecimal.ZERO; } else { trxPrice = trxUnitCost.add(unitCostAdjustmentBalance).divide(basetrx.getMovementQuantity().abs(), costCurPrecission, RoundingMode.HALF_UP); } if (checkNegativeStockCorrection && currentStock.compareTo(basetrx.getMovementQuantity()) < 0 && cost.compareTo(trxPrice) != 0 && !baseCAL.isNegativeStockCorrection() && AverageAlgorithm.modifiesAverage(trxType)) { // stock was negative and cost different than trx price then Negative Stock Correction // is added BigDecimal trxSignMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum()); BigDecimal negCorrAmt = trxPrice.multiply(currentStock) .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt) .subtract(adjustmentBalance); adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier)); // If there is a difference insert a cost adjustment line. CostAdjustmentLine newCAL = insertCostAdjustmentLine(basetrx, negCorrAmt, null); newCAL.setNegativeStockCorrection(Boolean.TRUE); newCAL.setRelatedTransactionAdjusted(Boolean.TRUE); newCAL.setUnitCost(Boolean.FALSE); OBDal.getInstance().save(newCAL); cost = trxPrice; log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(), cost.toPlainString()); } if (basetrx.getMaterialMgmtCostingList().size() == 0) { Date newDate = new Date(); Date dateTo = costing.getEndingDate(); costing.setEndingDate(newDate); OBDal.getInstance().save(costing); Costing newCosting = OBProvider.getInstance().get(Costing.class); newCosting.setCost(cost); newCosting.setCurrency( (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCostCurrencyId)); newCosting.setStartingDate(newDate); newCosting.setEndingDate(dateTo); newCosting.setInventoryTransaction(basetrx); newCosting.setProduct(basetrx.getProduct()); if (isManufacturingProduct) { newCosting.setOrganization( (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0")); } else { newCosting.setOrganization( (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId)); } newCosting.setQuantity(basetrx.getMovementQuantity()); newCosting.setTotalMovementQuantity(currentStock); newCosting.setPrice(cost); newCosting.setCostType("AVA"); newCosting.setManual(Boolean.FALSE); newCosting.setPermanent(Boolean.TRUE); newCosting.setProduction(trxType == TrxType.ManufacturingProduced); newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse)); OBDal.getInstance().save(newCosting); OBDal.getInstance().flush(); } else { Costing curCosting = basetrx.getMaterialMgmtCostingList().get(0); if (curCosting.getCost().compareTo(cost) != 0 || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) { curCosting.setPermanent(Boolean.FALSE); OBDal.getInstance().save(curCosting); OBDal.getInstance().flush(); // Update existing costing if (curCosting.getCost().compareTo(cost) != 0) { if (curCosting.getOriginalCost() == null) { curCosting.setOriginalCost(curCosting.getCost()); } curCosting.setCost(cost); curCosting.setPrice(trxPrice); } curCosting.setTotalMovementQuantity(currentStock); curCosting.setPermanent(Boolean.TRUE); OBDal.getInstance().flush(); OBDal.getInstance().save(curCosting); } } } // Modify isManufacturingProduct flag in case it has changed at some point. isManufacturingProduct = ((String) DalUtil.getId(costing.getOrganization())).equals("0"); ScrollableResults trxs = getRelatedTransactions(); String strCurrentCurId = strCostCurrencyId; try { while (trxs.next()) { MaterialTransaction trx = (MaterialTransaction) trxs.get()[0]; log.debug("Process related transaction {}", trx.getIdentifier()); BigDecimal trxSignMultiplier = new BigDecimal(trx.getMovementQuantity().signum()); BigDecimal trxAdjAmt = BigDecimal.ZERO; BigDecimal trxUnitCostAdjAmt = BigDecimal.ZERO; if (StringUtils.isNotEmpty(bdCostingId) && !isBackdatedTransaction(trx)) { // If there is a backdated source adjustment pending modify the dates of its m_costing. updateBDCostingTimeRange(trx); // This update is done only on the first related transaction. bdCostingId = ""; } if (!strCurrentCurId.equals(trx.getCurrency().getId())) { Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId); Organization costOrg = getCostOrg(); currentValueAmt = FinancialUtils.getConvertedAmount(currentValueAmt, curCurrency, trx.getCurrency(), trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_STANDARD); if (cost != null) { cost = FinancialUtils.getConvertedAmount(cost, curCurrency, trx.getCurrency(), trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_COSTING); } strCurrentCurId = trx.getCurrency().getId(); } List<CostAdjustmentLine> existingAdjLines = getTrxAdjustmentLines(trx); for (CostAdjustmentLine existingCAL : existingAdjLines) { if (existingCAL.isSource() && !existingCAL.isRelatedTransactionAdjusted()) { searchRelatedTransactionCosts(existingCAL); } if (existingCAL.getTransactionCostList().isEmpty() && !existingCAL.isRelatedTransactionAdjusted()) { BigDecimal adjustmentAmt = existingCAL.getAdjustmentAmount(); if (!strCurrentCurId.equals(existingCAL.getCurrency().getId())) { Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId); adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt, existingCAL.getCurrency(), curCurrency, existingCAL.getAccountingDate(), getCostOrg(), FinancialUtils.PRECISION_STANDARD); } trxAdjAmt = trxAdjAmt.add(adjustmentAmt); adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(trxSignMultiplier)); if (existingCAL.isUnitCost()) { trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(adjustmentAmt); } } existingCAL.setRelatedTransactionAdjusted(Boolean.TRUE); existingCAL.setParentCostAdjustmentLine((CostAdjustmentLine) OBDal.getInstance() .getProxy(CostAdjustmentLine.ENTITY_NAME, strCostAdjLineId)); OBDal.getInstance().save(existingCAL); } log.debug("Current trx adj amount of existing CALs {}", trxAdjAmt.toPlainString()); BigDecimal trxCost = CostAdjustmentUtils.getTrxCost(trx, false, OBDal.getInstance().get(Currency.class, strCurrentCurId)); BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(trx, true, OBDal.getInstance().get(Currency.class, strCurrentCurId)); currentValueAmt = currentValueAmt.add(trxCost.multiply(trxSignMultiplier)); currentStock = currentStock.add(trx.getMovementQuantity()); log.debug("Updated current stock {} and, current value {}", currentStock.toPlainString(), currentValueAmt.toPlainString()); TrxType currentTrxType = TrxType.getTrxType(trx); if (AverageAlgorithm.modifiesAverage(currentTrxType)) { // Recalculate average, if current stock is zero the average is not modified if (currentStock.signum() != 0) { cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission, RoundingMode.HALF_UP); } if (cost == null) { continue; } log.debug("New average cost: {}", cost.toPlainString()); Costing curCosting = trx.getMaterialMgmtCostingList().get(0); BigDecimal trxPrice = null; if (trx.getMovementQuantity().signum() == 0) { trxPrice = BigDecimal.ZERO; } else { trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(), costCurPrecission, RoundingMode.HALF_UP); } if (checkNegativeStockCorrection && currentStock.compareTo(trx.getMovementQuantity()) < 0 && cost.compareTo(trxPrice) != 0) { // stock was negative and cost different than trx price then Negative Stock Correction // is added BigDecimal negCorrAmt = trxPrice.multiply(currentStock) .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt) .subtract(adjustmentBalance); adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier)); trxAdjAmt = trxAdjAmt.add(negCorrAmt.multiply(trxSignMultiplier)); // If there is a difference insert a cost adjustment line. CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx, negCorrAmt, null); newCAL.setNegativeStockCorrection(Boolean.TRUE); newCAL.setRelatedTransactionAdjusted(Boolean.TRUE); newCAL.setUnitCost(Boolean.FALSE); OBDal.getInstance().save(newCAL); cost = trxPrice; log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(), cost.toPlainString()); } if (curCosting.getCost().compareTo(cost) == 0 && StringUtils.isEmpty(bdCostingId) && curCosting.getTotalMovementQuantity().compareTo(currentStock) == 0) { // new cost hasn't changed and total movement qty is equal to current stock, following // transactions will have the same cost, so no more // related transactions are needed to include. // If bdCosting is not empty it is needed to loop through the next related transaction // to set the new time ringe of the costing. log.debug("New cost matches existing cost. Adjustment finished."); return; } else { // Update existing costing curCosting.setPermanent(Boolean.FALSE); OBDal.getInstance().save(curCosting); OBDal.getInstance().flush(); if (curCosting.getCost().compareTo(cost) != 0) { if (curCosting.getOriginalCost() == null) { curCosting.setOriginalCost(curCosting.getCost()); } curCosting.setPrice(trxPrice); curCosting.setCost(cost); } curCosting.setTotalMovementQuantity(currentStock); curCosting.setPermanent(Boolean.TRUE); OBDal.getInstance().save(curCosting); } } else if (cost != null && !isVoidedTrx(trx, currentTrxType)) { if (!trx.isCostPermanent()) { // Check current trx unit cost matches new expected cost BigDecimal expectedCost = cost.multiply(trx.getMovementQuantity().abs()) .setScale(stdCurPrecission, RoundingMode.HALF_UP); BigDecimal unitCost = CostAdjustmentUtils.getTrxCost(trx, true, OBDal.getInstance().get(Currency.class, strCurrentCurId)); unitCost = unitCost.add(trxAdjAmt); log.debug("Is adjustment needed? Expected {} vs Current {}", expectedCost.toPlainString(), unitCost.toPlainString()); if (expectedCost.compareTo(unitCost) != 0) { trxAdjAmt = trxAdjAmt.add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier)); trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(expectedCost.subtract(unitCost)); adjustmentBalance = adjustmentBalance .add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier)); // If there is a difference insert a cost adjustment line. CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx, expectedCost.subtract(unitCost), null); newCAL.setRelatedTransactionAdjusted(Boolean.TRUE); OBDal.getInstance().save(newCAL); log.debug("Adjustment added. Amount {}.", expectedCost.subtract(unitCost).toPlainString()); } } if (trx.getMaterialMgmtCostingList().size() != 0) { Costing curCosting = trx.getMaterialMgmtCostingList().get(0); if (currentStock.signum() != 0) { cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission, RoundingMode.HALF_UP); } BigDecimal trxPrice = null; if (trx.getMovementQuantity().signum() == 0) { trxPrice = BigDecimal.ZERO; } else { trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(), costCurPrecission, RoundingMode.HALF_UP); } if (curCosting.getCost().compareTo(cost) != 0 || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) { curCosting.setPermanent(Boolean.FALSE); OBDal.getInstance().save(curCosting); OBDal.getInstance().flush(); if (curCosting.getCost().compareTo(cost) != 0) { if (curCosting.getOriginalCost() == null) { curCosting.setOriginalCost(curCosting.getCost()); } curCosting.setPrice(trxPrice); curCosting.setCost(cost); } curCosting.setTotalMovementQuantity(currentStock); curCosting.setPermanent(Boolean.TRUE); OBDal.getInstance().save(curCosting); } } } OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } } finally { trxs.close(); } if (getCostingRule().getEndingDate() == null && cost != null) { // This is the current costing rule. Check if current average cost needs to be updated. Costing currentCosting = AverageAlgorithm.getProductCost(new Date(), basetrx.getProduct(), getCostDimensions(), getCostOrg()); if (currentCosting == null) { throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName() + ", @Product@: " + basetrx.getProduct().getName() + ", @Date@: " + OBDateUtils.formatDate(new Date())); } if (currentCosting.getCost().compareTo(cost) != 0) { basetrx = getTransaction(); Date newDate = new Date(); Date dateTo = currentCosting.getEndingDate(); currentCosting.setEndingDate(newDate); OBDal.getInstance().save(currentCosting); Costing newCosting = OBProvider.getInstance().get(Costing.class); newCosting.setCost(cost); newCosting.setCurrency( (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCurrentCurId)); newCosting.setStartingDate(newDate); newCosting.setEndingDate(dateTo); newCosting.setInventoryTransaction(null); newCosting.setProduct(basetrx.getProduct()); if (isManufacturingProduct) { newCosting.setOrganization( (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0")); } else { newCosting.setOrganization( (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId)); } newCosting.setQuantity(null); newCosting.setTotalMovementQuantity(currentStock); newCosting.setPrice(cost); newCosting.setCostType("AVA"); newCosting.setManual(Boolean.FALSE); newCosting.setPermanent(Boolean.TRUE); newCosting.setProduction(trxType == TrxType.ManufacturingProduced); newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse)); OBDal.getInstance().save(newCosting); } } }
From source file:edu.ku.kuali.kra.award.sapintegration.SapIntegrationServiceImpl.java
/** * Implements section 1.7.4, 1.7.5, and 1.7.6 of the functional * specification./*from w w w . j a v a 2 s. c o m*/ * * @param award * the award for which to generate a sponsored program * @param costSharing * indicates if this is a cost sharing program or not, if true * then this method produces a sponsored program structure which * compiles with specification section 1.7.4, if false then it * will generate one which complies with specification section * 1.7.5 * @param parentAward * true if the given award is a parent award, false otherwise * @return */ protected ZGMSPPROGRAMSTRUCTURE constructSponsoredProgram(Award award, boolean costSharing) { CustomAwardDataHelper helper = new CustomAwardDataHelper(award); AwardBudgetExt abvoe = getLastBudgetVersion(award.getAwardDocument()); boolean awardBudgetVersionToBePosted = false; if (abvoe != null) { String budgetStatus = abvoe.getAwardBudgetStatusCode(); awardBudgetVersionToBePosted = Constants.BUDGET_STATUS_CODE_TO_BE_POSTED.equalsIgnoreCase(budgetStatus); } ZGMSPPROGRAMSTRUCTURE sponsoredProgramStructure = objectFactory.createZGMSPPROGRAMSTRUCTURE(); if (helper.getLastTransmissionDate() == null) { sponsoredProgramStructure.setSPPROGRAMUPDATE(INTERFACE_NEW); } else { sponsoredProgramStructure.setSPPROGRAMUPDATE(INTERFACE_UPDATE); } sponsoredProgramStructure.setSPPROGRAMNUMBER(award.getAccountNumber()); // Handle data which is shared between 1.7.4 and 1.7.5 // Position 1 if (StringUtils.isEmpty(award.getAccountNumber())) { sponsoredProgramStructure.setSPONSOREDPROG(award.getAwardNumber()); } else { sponsoredProgramStructure.setSPONSOREDPROG(award.getAccountNumber()); } AwardAmountInfo awardAmountInfo = getAwardAmountInfoService() .fetchLastAwardAmountInfoForAwardVersionAndFinalizedTandMDocumentNumber(award); // Position 3 sponsoredProgramStructure.setZZVALIDFROM(dateToString(awardAmountInfo.getCurrentFundEffectiveDate())); // Position 4 sponsoredProgramStructure.setZZVALIDTO(dateToString(awardAmountInfo.getObligationExpirationDate())); // Position 6 sponsoredProgramStructure.setBUSINESSAREA(convertLeadUnitToBusinessArea(award.getLeadUnitNumber(), award)); // Position 7 GMSPPROGRAMFMBTTT programFmbtTt = objectFactory.createGMSPPROGRAMFMBTTT(); GMSPPROGRAMFMBT programFmbt = objectFactory.createGMSPPROGRAMFMBT(); programFmbtTt.getItem().add(programFmbt); sponsoredProgramStructure.setTGMSPPROGRAMFMBT(programFmbtTt); programFmbt.setSPONSOREDPROG(award.getAccountNumber()); programFmbt.setFUNCTIONALAREA(convertActivityTypeToFunctionalArea(award.getActivityTypeCode(), award)); // Position 8 // If this is a cost sharing sponsored program then it is sourced from // the parent award, but they don't have // budgets so the F and A rate would not be able to be calculated. // also, parent awards cant have budgets, so check to see if their are // children as well AwardHierarchy hierarchy = getAwardHierarchyService().loadAwardHierarchy(award.getAwardNumber()); String overheadKey = ""; if (!awardBudgetVersionToBePosted) { // BU Customization ID: N/A mkousheh 20120504 - Get the latest child // that matches that was successful transmitted AwardTransmissionChild lastTransmittedChild = getLatestChildAwardTransmitted( hierarchy.getRoot().getAward(), award.getAwardNumber(), true); if (lastTransmittedChild != null) { overheadKey = lastTransmittedChild.getOverheadKey(); } // BU Customization ID: N/A mkousheh 20120504 - Commented out the // following code and replaced with the above - // BUG (it gets latest transmitted then matches the child, sometimes // no matching child in the last transmission // AwardTransmission lastTransmission = // getLatestAwardTransmission(hierarchy.getRoot().getAward(), true); // if (lastTransmission != null) { // AwardTransmissionChild lastChildTransmission = // findMatchingTransmissionChild(lastTransmission.getTransmissionChildren(), // award.getAwardNumber()); // if (lastChildTransmission != null) { // overheadKey = lastChildTransmission.getOverheadKey(); // } // } // BU Customization ID: N/A mkousheh N/A - Switching this to use // value saved on last transmission child - // BigDecimal fAndARate = calculateApplicableFandARate(award); // if(fAndARate != null) { // sponsoredProgramStructure.setOVERHEADKEY(StringUtils.leftPad(fAndARate.toPlainString(), // 6, "0")); // } } else if (!costSharing && !hierarchy.hasChildren() && awardBudgetVersionToBePosted) { BigDecimal fAndARate = calculateApplicableFandARate(award); if (fAndARate != null && (((AwardExtension) award.getExtension()).getFederalRateDate() == null || "NA".equalsIgnoreCase(((AwardExtension) award.getExtension()).getFederalRateDate()))) { overheadKey = StringUtils.leftPad(fAndARate.toPlainString(), 6, "0"); } else { // get the system parameter for these values and lookup the // mapping value based on the date overheadKey = getParameterService().getSubParameterValueAsString(AwardDocument.class, BUConstants.FEDERAL_RATE_DATE_OVERHEAD_KEY_FIELD_MAPPINGS, ((AwardExtension) award.getExtension()).getFederalRateDate()); if (fAndARate == null || StringUtils.isBlank(overheadKey)) { overheadKey = ("000.00"); } } } sponsoredProgramStructure.setOVERHEADKEY(overheadKey); GlobalVariables.getUserSession().addObject("overheadKey-".concat(award.getAwardNumber()), (Object) overheadKey); LOG.info("Writing overheadKey to session: " + overheadKey); // Position 9 programFmbt.setFUNDSCENTER(StringUtils.rightPad(award.getLeadUnitNumber(), 10, "0")); // Position 11 sponsoredProgramStructure.setZZREFERENCE(award.getAwardNumber()); // Position 12 sponsoredProgramStructure.setZZAWARDNO(award.getSponsorAwardNumber()); // Position 13 sponsoredProgramStructure.setZZDOCNO(award.getDocumentFundingId()); AwardBudgetExt budget = null; if (!costSharing) { budget = award.getAwardDocument().getBudgetVersionOverview(); if (budget == null) { throw new IllegalArgumentException( "Award with number " + award.getAwardNumber() + " does not have a budget."); } } // BU Customization ID: N/A mkousheh 20110706 - In case of CostSharing // check if updated boolean costSharesHaveChanged = false; if (costSharing) { AwardCostShare tmpAwardCostShare = getMostRecentAwardCostShare(award); if (tmpAwardCostShare != null && ((AwardExtension) award.getExtension()).getLastTransmissionDate() != null && tmpAwardCostShare.getUpdateTimestamp() != null && ((AwardExtension) award.getExtension()) .getLastTransmissionDate().before(tmpAwardCostShare.getUpdateTimestamp())) { costSharesHaveChanged = true; } } // if (!costSharesHaveChanged) { // Position 17 if (awardBudgetVersionToBePosted && budget != null && budget.getTotalDirectCost() != null) { sponsoredProgramStructure.setBUDGETTDC(budget.getTotalDirectCost().bigDecimalValue()); } else { sponsoredProgramStructure.setBUDGETTDC(ScaleTwoDecimal.ZERO.bigDecimalValue()); } // Position 18 if (awardBudgetVersionToBePosted && budget != null && budget.getTotalIndirectCost() != null) { sponsoredProgramStructure.setBUDGETFA(budget.getTotalIndirectCost().bigDecimalValue()); } else { sponsoredProgramStructure.setBUDGETFA(ScaleTwoDecimal.ZERO.bigDecimalValue()); } // } // BU Customization ID: N/A mkousheh 20110712 - If Parent Award // Transaction is NoCostExtention or Administrative Changes Set Budget // to zero if (hierarchy.getRoot().getAward().getAwardTransactionTypeCode() != null) { if (hierarchy.getRoot().getAward().getAwardTransactionTypeCode().equals(10) || hierarchy.getRoot().getAward().getAwardTransactionTypeCode().equals(6)) { sponsoredProgramStructure.setBUDGETTDC(ScaleTwoDecimal.ZERO.bigDecimalValue()); sponsoredProgramStructure.setBUDGETFA(ScaleTwoDecimal.ZERO.bigDecimalValue()); } } // Position 19 boolean fringeNotAllowed = helper.isFringeNotAllowed(); sponsoredProgramStructure .setFRINGECODE(FringeCodeMapping.mapToSapFringeCode(fringeNotAllowed, award.getAccountTypeCode())); /** * Data which is only part of 1.7.4 */ if (!costSharing && !hierarchy.hasChildren()) { // Position 10 sponsoredProgramStructure.setZZORDCAT(convertChildType(helper.getChildType(), award)); // Position 14 String offCampus = null; if (!awardBudgetVersionToBePosted) { // BU Customization ID: N/A mkousheh 20120504 - Get the latest // child that matches that was successful transmitted // AwardTransmission lastTransmission = // getLatestAwardTransmission(hierarchy.getRoot().getAward(), // true); // if (lastTransmission != null) { // AwardTransmissionChild lastChildTransmission = // findMatchingTransmissionChild(lastTransmission.getTransmissionChildren(), // award.getAwardNumber()); // if (lastChildTransmission != null) { // offCampus = lastChildTransmission.getOffCampus(); // } // } AwardTransmissionChild lastTransmittedChild = getLatestChildAwardTransmitted( hierarchy.getRoot().getAward(), award.getAwardNumber(), true); if (lastTransmittedChild != null) { offCampus = lastTransmittedChild.getOffCampus(); } } else if (budget != null) { offCampus = budget.getOnOffCampusFlag(); } sponsoredProgramStructure.setZZOFFCAMPUS(offCampus); GlobalVariables.getUserSession().addObject("offCampus-".concat(award.getAwardNumber()), (Object) offCampus); LOG.info("Writing offCampus to session: " + offCampus); // Position 16 String baseCode = null; if (!awardBudgetVersionToBePosted) { // BU Customization ID: N/A mkousheh 20120504 - Get the latest // child that matches that was successful transmitted // AwardTransmission lastTransmission = // getLatestAwardTransmission(hierarchy.getRoot().getAward(), // true); // if (lastTransmission != null) { // AwardTransmissionChild lastChildTransmission = // findMatchingTransmissionChild(lastTransmission.getTransmissionChildren(), // award.getAwardNumber()); // if (lastChildTransmission != null) { // baseCode = lastChildTransmission.getBaseCode(); // } // } AwardTransmissionChild lastTransmittedChild = getLatestChildAwardTransmitted( hierarchy.getRoot().getAward(), award.getAwardNumber(), true); if (lastTransmittedChild != null) { baseCode = lastTransmittedChild.getBaseCode(); } } else if (budget != null) { // AAP removed per whit - && // awardBudgetVersionToBePosted baseCode = budget.getOhRateClassCode(); } sponsoredProgramStructure.setBASECODE(baseCode); GlobalVariables.getUserSession().addObject("baseCode-".concat(award.getAwardNumber()), (Object) baseCode); LOG.info("Writing baseCode to session: " + baseCode); // Position 20 sponsoredProgramStructure.setDESCRIPTION(helper.getChildDescription()); // Position 21 // BU Customization ID: N/A mkousheh 20110816 - SUBRecipient no // longer needed // ZFIGMSUBRECIPIENTTAB awardApprovedSubawards = // objectFactory.createZFIGMSUBRECIPIENTTAB(); // sponsoredProgramStructure.setTSUBRECIPIENT(awardApprovedSubawards); // List<AwardApprovedSubaward> subawards = // award.getAwardApprovedSubawards(); // for (AwardApprovedSubaward subaward : subawards) { // GMSUBRECIPIENT awardApprovedSubaward = // objectFactory.createGMSUBRECIPIENT(); // awardApprovedSubawards.getItem().add(awardApprovedSubaward); // awardApprovedSubaward.setSUBRECIPIENT(subaward.getOrganizationId()); // awardApprovedSubaward.setSUBNAME(subaward.getOrganizationName()); // awardApprovedSubaward.setSUBAMOUNT(subaward.getAmount().bigDecimalValue()); // } // AwardApprovedSubaward awardApprovedSubaward = // getMostRecentAwardApprovedSubaward(award); // if (awardApprovedSubaward != null) { // ZGMSUBRECIPIENT subRecipent = new ZGMSUBRECIPIENT(); // subRecipent.setSUBRECIPIENT(awardApprovedSubaward.getOrganizationId()); // subRecipent.setSUBNAME(awardApprovedSubaward.getOrganizationName()); // subRecipent.setSUBAMOUNT(awardApprovedSubaward.getAmount().bigDecimalValue()); // sponsoredProgramStructure.setZZSUBRECIPIENT(subRecipent); // sponsoredProgramStructure.setZZSUBRECIPIENT(awardApprovedSubaward.getOrganizationId()); // } // Position 22 sponsoredProgramStructure.setKCRMSTATUS(StringUtils.leftPad(award.getStatusCode().toString(), 2, "0")); // Position 23 sponsoredProgramStructure.setSPONSOR(award.getSponsorCode()); // Position 24 sponsoredProgramStructure.setPRIMESPONSOR(award.getPrimeSponsorCode()); /** * Specification section 1.7.6 */ ZFIGMSPRESPONSIBLETABKCRM sponsoredProgramPersons = objectFactory.createZFIGMSPRESPONSIBLETABKCRM(); sponsoredProgramStructure.setTRESPONSIBLE(sponsoredProgramPersons); List<AwardPerson> persons = award.getProjectPersons(); for (AwardPerson person : persons) { ZGMSPRESPONSIBLEKCRM sponsoredProgramPerson = objectFactory.createZGMSPRESPONSIBLEKCRM(); sponsoredProgramPersons.getItem().add(sponsoredProgramPerson); sponsoredProgramPerson.setSPONSOREDPROG(award.getAccountNumber()); sponsoredProgramPerson.setOBJECTID(person.getPersonId()); sponsoredProgramPerson.setOBJECTNAME(person.getFullName()); // BUKC-0062: SAP Interface - Handle multiple PIs for NIH awards // when transmit to SAP if (person.isMultiplePi()) { sponsoredProgramPerson.setRESPONSIBILITY("PI"); } else { sponsoredProgramPerson.setRESPONSIBILITY( convertProjectRoleToResponsibility(person.getContactRoleCode(), award)); } } // BU Customization ID: N/A mkousheh 20110828 - Add DAs to // SponsoredPrograms for (AwardUnitContact awardContact : award.getAwardUnitContacts()) { if ("2".equals(awardContact.getUnitAdministratorTypeCode())) { ZGMSPRESPONSIBLEKCRM sponsoredProgramPerson = objectFactory.createZGMSPRESPONSIBLEKCRM(); sponsoredProgramPersons.getItem().add(sponsoredProgramPerson); sponsoredProgramPerson.setOBJECTID(awardContact.getPersonId()); sponsoredProgramPerson.setOBJECTNAME(awardContact.getFullName()); sponsoredProgramPerson.setRESPONSIBILITY("DA"); } if ("6".equals(awardContact.getUnitAdministratorTypeCode())) { ZGMSPRESPONSIBLEKCRM sponsoredProgramPerson = objectFactory.createZGMSPRESPONSIBLEKCRM(); sponsoredProgramPersons.getItem().add(sponsoredProgramPerson); sponsoredProgramPerson.setOBJECTID(awardContact.getPersonId()); sponsoredProgramPerson.setOBJECTNAME(awardContact.getPerson().getFullName()); sponsoredProgramPerson.setRESPONSIBILITY("OAV"); } // BUKC-0140: Add new Admin Type (Clinical Trial Admin) if ("8".equals(awardContact.getUnitAdministratorTypeCode())) { ZGMSPRESPONSIBLEKCRM sponsoredProgramPerson = objectFactory.createZGMSPRESPONSIBLEKCRM(); sponsoredProgramPersons.getItem().add(sponsoredProgramPerson); sponsoredProgramPerson.setOBJECTID(awardContact.getPersonId()); sponsoredProgramPerson.setOBJECTNAME(awardContact.getPerson().getFullName()); sponsoredProgramPerson.setRESPONSIBILITY("CTAD"); } } } /** * Data which is only part of 1.7.5 */ ScaleTwoDecimal costSharCommitmentMinusMemoMatch = getTotalCostShareCommitmentAmountMinusMemoMatch(award); if (costSharing && costSharCommitmentMinusMemoMatch != null && costSharCommitmentMinusMemoMatch.isPositive()) { // Position 2 // Sponsored_Program_type - according to Whit - this does not need // to be sent // Position 10 sponsoredProgramStructure.setZZORDCAT("CS1"); // Position 14 sponsoredProgramStructure.setZZOFFCAMPUS("Y"); // Position 21 sponsoredProgramStructure.setKCRMSTATUS(award.getStatusCode().toString()); sponsoredProgramStructure.setBUDGETTDC(costSharCommitmentMinusMemoMatch.bigDecimalValue()); // getTotalDirectCost() // BU Customization ID: N/A mkousheh 20120731 - Remove the work // around as SAP team fixed the issue on their side /* * // Temporary fix for Cost Sharing. When we send an update for a * Cost Sharing Sponsored Program the Budget_TDC and Budget_FA * should default to 0.00 AwardTransmission lastTransmission = * getLatestAwardTransmission(hierarchy.getRoot().getAward(), true); * if (lastTransmission != null) { AwardTransmissionChild * lastChildTransmission = * findMatchingTransmissionChild(lastTransmission * .getTransmissionChildren(), award.getAwardNumber()); if * (isCostSharing(award) && helper.getLastTransmissionDate() != * null) { sponsoredProgramStructure.setBUDGETTDC(KualiDecimal.ZERO. * bigDecimalValue()); * sponsoredProgramStructure.setBUDGETFA(KualiDecimal * .ZERO.bigDecimalValue()); * * } } // end temporary fix */ // BU Customization ID: N/A mkousheh 20120808 - Set 000.00 for // overhead rate when cost sharing sponsoredProgramStructure.setOVERHEADKEY("000.00"); AwardCostShare awardCostShare = getMostRecentAwardCostShare(award); if (awardCostShare != null && awardCostShare.getDestination() != null) { sponsoredProgramStructure.setSPONSOREDPROG(awardCostShare.getDestination()); } else { sponsoredProgramStructure.setSPONSOREDPROG(award.getAwardNumber()); } } return sponsoredProgramStructure; }
From source file:org.openbravo.erpCommon.ad_forms.RequisitionToOrder.java
private OBError processPurchaseOrder(VariablesSecureApp vars, String strSelected, String strOrderDate, String strVendor, String strPriceListId, String strOrg, String strWarehouse) throws IOException, ServletException { StringBuffer textMessage = new StringBuffer(); Connection conn = null;//from w w w .jav a 2 s . c om OBError myMessage = null; myMessage = new OBError(); myMessage.setTitle(""); String strPriceListVersionId = RequisitionToOrderData.getPricelistVersion(this, strPriceListId, strOrderDate); RequisitionToOrderData[] noprice = RequisitionToOrderData.selectNoPrice(this, vars.getLanguage(), strPriceListVersionId, strSelected); if (noprice != null && noprice.length > 0) { textMessage.append(Utility.messageBD(this, "LinesWithNoPrice", vars.getLanguage())).append("<br><ul>"); for (int i = 0; i < noprice.length; i++) { textMessage.append("<li>").append(noprice[i].product); } textMessage.append("</ul>"); myMessage.setType("Error"); myMessage.setMessage(textMessage.toString()); return myMessage; } RequisitionToOrderData[] data1 = RequisitionToOrderData.selectVendorData(this, strVendor); if (data1[0].poPaymenttermId == null || data1[0].poPaymenttermId.equals("")) { myMessage.setType("Error"); myMessage.setMessage(Utility.messageBD(this, "VendorWithNoPaymentTerm", vars.getLanguage())); return myMessage; } if ("".equals(RequisitionToOrderData.cBPartnerLocationId(this, strVendor))) { myMessage.setType("Error"); myMessage.setMessage(Utility.messageBD(this, "NoBPLocation", vars.getLanguage())); return myMessage; } try { conn = getTransactionConnection(); String strCOrderId = SequenceIdData.getUUID(); String docTargetType = RequisitionToOrderData.cDoctypeTarget(conn, this, vars.getClient(), strOrg); String strDocumentNo = Utility.getDocumentNo(this, vars, "", "C_Order", docTargetType, docTargetType, false, true); String cCurrencyId = RequisitionToOrderData.selectCurrency(this, strPriceListId); try { RequisitionToOrderData.insertCOrder(conn, this, strCOrderId, vars.getClient(), strOrg, vars.getUser(), strDocumentNo, "DR", "CO", "0", docTargetType, strOrderDate, strOrderDate, strOrderDate, strVendor, RequisitionToOrderData.cBPartnerLocationId(this, strVendor), RequisitionToOrderData.billto(this, strVendor).equals("") ? RequisitionToOrderData.cBPartnerLocationId(this, strVendor) : RequisitionToOrderData.billto(this, strVendor), cCurrencyId, isAlternativeFinancialFlow() ? "P" : data1[0].paymentrulepo, data1[0].poPaymenttermId, data1[0].invoicerule.equals("") ? "I" : data1[0].invoicerule, data1[0].deliveryrule.equals("") ? "A" : data1[0].deliveryrule, "I", data1[0].deliveryviarule.equals("") ? "D" : data1[0].deliveryviarule, strWarehouse, strPriceListId, "", "", "", data1[0].poPaymentmethodId); } catch (ServletException ex) { myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage()); releaseRollbackConnection(conn); return myMessage; } int line = 0; String strCOrderlineID = ""; BigDecimal qty = new BigDecimal("0"); BigDecimal qtyOrder = new BigDecimal("0"); BigDecimal quantity = new BigDecimal("0"); BigDecimal quantityOrder = new BigDecimal("0"); boolean insertLine = false; RequisitionToOrderData[] lines = RequisitionToOrderData.linesToOrder(this, strOrderDate, strOrg, strWarehouse, RequisitionToOrderData.billto(this, strVendor).equals("") ? RequisitionToOrderData.cBPartnerLocationId(this, strVendor) : RequisitionToOrderData.billto(this, strVendor), RequisitionToOrderData.cBPartnerLocationId(this, strVendor), cCurrencyId, strPriceListVersionId, strSelected); for (int i = 0; lines != null && i < lines.length; i++) { if ("".equals(lines[i].tax)) { RequisitionLine rl = OBDal.getInstance().get(RequisitionLine.class, lines[i].mRequisitionlineId); myMessage.setType("Error"); myMessage.setMessage(String.format(OBMessageUtils.messageBD("NoTaxRequisition"), rl.getLineNo(), rl.getRequisition().getDocumentNo())); releaseRollbackConnection(conn); return myMessage; } if (i == 0) strCOrderlineID = SequenceIdData.getUUID(); if (i == lines.length - 1) { insertLine = true; qtyOrder = qty; quantityOrder = quantity; } else if (!lines[i + 1].mProductId.equals(lines[i].mProductId) || !lines[i + 1].mAttributesetinstanceId.equals(lines[i].mAttributesetinstanceId) || !lines[i + 1].description.equals(lines[i].description) || !lines[i + 1].priceactual.equals(lines[i].priceactual) || !StringUtils.equals(lines[i + 1].mProductUomId, lines[i].mProductUomId)) { insertLine = true; qtyOrder = qty; qty = new BigDecimal(0); quantityOrder = quantity; quantity = new BigDecimal(0); } else { qty = qty.add(new BigDecimal(lines[i].lockqty)); quantity = quantity.add(new BigDecimal(lines[i].quantityorder)); } lines[i].cOrderlineId = strCOrderlineID; if (insertLine) { insertLine = false; line += 10; BigDecimal qtyAux = new BigDecimal(lines[i].lockqty); qtyOrder = qtyOrder.add(qtyAux); BigDecimal quantityAux = new BigDecimal(lines[i].quantityorder); quantityOrder = quantityOrder.add(quantityAux); if (log4j.isDebugEnabled()) log4j.debug("Lockqty: " + lines[i].lockqty + " qtyorder: " + qtyOrder.toPlainString() + " new BigDecimal: " + (new BigDecimal(lines[i].lockqty)).toString() + " qtyAux: " + qtyAux.toString()); try { RequisitionToOrderData.insertCOrderline(conn, this, strCOrderlineID, vars.getClient(), strOrg, vars.getUser(), strCOrderId, Integer.toString(line), strVendor, RequisitionToOrderData.cBPartnerLocationId(this, strVendor), strOrderDate, lines[i].needbydate, lines[i].description, lines[i].mProductId, lines[i].mAttributesetinstanceId, strWarehouse, lines[i].mProductUomId, lines[i].cUomId, quantityOrder != null && BigDecimal.ZERO.compareTo(quantityOrder) != 0 ? quantityOrder.toPlainString() : "", qtyOrder.toPlainString(), cCurrencyId, lines[i].pricelist, lines[i].priceactual, strPriceListId, lines[i].pricelimit, lines[i].tax, "", lines[i].discount, lines[i].grossUnit, lines[i].grossAmt); } catch (ServletException ex) { myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage()); releaseRollbackConnection(conn); return myMessage; } strCOrderlineID = SequenceIdData.getUUID(); } } unlockRequisitionLines(vars, strSelected); for (int i = 0; lines != null && i < lines.length; i++) { String strRequisitionOrderId = SequenceIdData.getUUID(); try { RequisitionToOrderData.insertRequisitionOrder(conn, this, strRequisitionOrderId, vars.getClient(), strOrg, vars.getUser(), lines[i].mRequisitionlineId, lines[i].cOrderlineId, lines[i].lockqty); } catch (ServletException ex) { myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage()); releaseRollbackConnection(conn); return myMessage; } if (lines[i].toClose.equals("Y")) RequisitionToOrderData.requisitionStatus(conn, this, lines[i].mRequisitionlineId, vars.getUser()); } OBError myMessageAux = cOrderPost(conn, vars, strCOrderId); releaseCommitConnection(conn); String strWindowName = WindowTabsData.selectWindowInfo(this, vars.getLanguage(), "181"); textMessage.append(strWindowName).append(" ").append(strDocumentNo).append(": "); if (myMessageAux.getMessage().equals("")) textMessage.append(Utility.messageBD(this, "Success", vars.getLanguage())); else textMessage.append(myMessageAux.getMessage()); myMessage.setType(myMessageAux.getType()); myMessage.setMessage(textMessage.toString()); return myMessage; } catch (Exception e) { try { if (conn != null) releaseRollbackConnection(conn); } catch (Exception ignored) { } e.printStackTrace(); log4j.warn("Rollback in transaction"); myMessage.setType("Error"); myMessage.setMessage(Utility.messageBD(this, "ProcessRunError", vars.getLanguage())); return myMessage; } }
From source file:org.apache.pig.test.TestBuiltin.java
@Test public void testAVGIntermediate() throws Exception { String[] avgTypes = { "AVGIntermediate", "DoubleAvgIntermediate", "LongAvgIntermediate", "IntAvgIntermediate", "FloatAvgIntermediate", "BigDecimalAvgIntermediate", "BigIntegerAvgIntermediate" }; for (int k = 0; k < avgTypes.length; k++) { EvalFunc<?> avg = evalFuncMap.get(avgTypes[k]); String inputType = getInputType(avgTypes[k]); Tuple tup = inputMap.get(inputType); // The tuple we got above has a bag with input // values. Input to the Intermediate.exec() however comes // from the map which would put each value and a count of // 1 in a tuple and send it down. So lets create a bag with // tuples that have two fields - the value and a count 1. DataBag bag = (DataBag) tup.get(0); DataBag bg = bagFactory.newDefaultBag(); for (Tuple t : bag) { Tuple newTuple = tupleFactory.newTuple(2); newTuple.set(0, t.get(0));/* ww w. j a v a 2 s.co m*/ if (inputType == "BigDecimal") { newTuple.set(1, BigDecimal.ONE); } else if (inputType == "BigInteger") { newTuple.set(1, BigInteger.ONE); } else { newTuple.set(1, new Long(1)); } bg.add(newTuple); } Tuple intermediateInput = tupleFactory.newTuple(); intermediateInput.append(bg); Object output = avg.exec(intermediateInput); if (inputType == "Long" || inputType == "Integer" || inputType == "IntegerAsLong") { Long l = (Long) ((Tuple) output).get(0); String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k]) + " ( (output) " + l + " == " + getExpected(avgTypes[k]) + " (expected) )]"; assertEquals(msg, getExpected(avgTypes[k]), l); } else if (inputType == "BigDecimal") { BigDecimal f1 = (BigDecimal) ((Tuple) output).get(0); String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k]) + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]"; assertEquals(msg, ((BigDecimal) getExpected(avgTypes[k])).toPlainString(), f1.toPlainString()); } else if (inputType == "BigInteger") { BigInteger f1 = (BigInteger) ((Tuple) output).get(0); String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k]) + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]"; assertEquals(msg, ((BigInteger) getExpected(avgTypes[k])).toString(), f1.toString()); } else { Double f1 = (Double) ((Tuple) output).get(0); String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k]) + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]"; assertEquals(msg, (Double) getExpected(avgTypes[k]), f1, 0.00001); } if (inputType == "BigDecimal") { BigDecimal f2 = (BigDecimal) ((Tuple) output).get(1); assertEquals("[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 4", "4", f2.toPlainString()); } else if (inputType == "BigInteger") { BigInteger f2 = (BigInteger) ((Tuple) output).get(1); assertEquals("[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 4", "4", f2.toString()); } else { Long f2 = (Long) ((Tuple) output).get(1); assertEquals( "[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 11", 11, f2.longValue()); } } }
From source file:org.marketcetera.strategy.LanguageTestBase.java
/** * Executes a single iteration of the <code>getOptionPositionAsOf</code> test. * * @param inOptionRoot a <code>String</code> value * @param inExpiry a <code>String</code> value * @param inStrikePrice a <code>BigDecimal</code> value * @param inOptionType an <code>OptionType</code> value * @param inDate a <code>Date</code> value * @param inExpectedPosition a <code>BigDecimal</code> value * @throws Exception if an unexpected error occurs *///from w w w. j a va 2 s . c o m private void doOptionPositionAsOfTest(String inOptionRoot, String inExpiry, BigDecimal inStrikePrice, OptionType inOptionType, Date inDate, BigDecimal inExpectedPosition) throws Exception { StrategyCoordinates strategy = getPositionsStrategy(); setPropertiesToNull(); AbstractRunningStrategy.setProperty("optionPositionAsOfDuringStop", "not-empty"); if (inOptionRoot != null) { AbstractRunningStrategy.setProperty("optionRoot", inOptionRoot); } if (inExpiry != null) { AbstractRunningStrategy.setProperty("expiry", inExpiry); } if (inStrikePrice != null) { AbstractRunningStrategy.setProperty("strikePrice", inStrikePrice.toPlainString()); } if (inOptionType != null) { AbstractRunningStrategy.setProperty("optionType", inOptionType.toString()); } if (inDate != null) { AbstractRunningStrategy.setProperty("date", Long.toString(inDate.getTime())); } verifyStrategyStartsAndStops(strategy.getName(), getLanguage(), strategy.getFile(), null, null, null); // verify expected results assertEquals((inExpectedPosition == null ? null : inExpectedPosition.toString()), AbstractRunningStrategy.getProperty("optionPositionAsOf")); assertNull(AbstractRunningStrategy.getProperty("optionPositionAsOfDuringStop")); }
From source file:com.yucheng.cmis.pvp.app.component.PvpAuthorizeComponent.java
/** * ??/* w ww . ja va 2 s. c o m*/ * * * * *120= * @param rate * @return */ public static String getCoreTradeRate(Double rate) { BigDecimal reality = new BigDecimal(rate); reality = reality.multiply(new BigDecimal(120)); reality = reality.divide(new BigDecimal(1), 5, BigDecimal.ROUND_HALF_UP); return reality.toPlainString(); }
From source file:atlas.kingj.roi.FrmMain.java
public static String getSignificant(double value, int sigFigs) { MathContext mc = new MathContext(sigFigs, RoundingMode.DOWN); BigDecimal bigDecimal = new BigDecimal(value, mc); return bigDecimal.toPlainString(); }