List of usage examples for java.math BigDecimal equals
@Override public boolean equals(Object x)
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractChannelController.java
@RequestMapping(value = ("/editcatalogproductpricing"), method = RequestMethod.POST) public String editCatalogProductPricing(@RequestParam(value = "channelId", required = true) String channelId, @RequestParam(value = "currencyValData", required = true) String currencyValData, ModelMap map) throws JSONException { logger.debug("### editCatalogProductPricing method starting...(POST)"); boolean status = false; try {// www.j av a 2 s . c o m Channel channel = channelService.getChannelById(channelId); JSONArray jsonArray = new JSONArray(currencyValData); List<ProductCharge> productCharges = new ArrayList<ProductCharge>(); for (int index = 0; index < jsonArray.length(); index++) { JSONObject jsonObj = jsonArray.getJSONObject(index); BigDecimal previousVal = new BigDecimal(jsonObj.get("previousvalue").toString()); BigDecimal newVal = new BigDecimal(jsonObj.get("value").toString()); String currencyCode = jsonObj.get("currencycode").toString(); String productId = jsonObj.get("productId").toString(); if (!previousVal.equals(newVal)) { Product product = productService.locateProductById(productId); CurrencyValue currencyValue = currencyValueService.locateBYCurrencyCode(currencyCode); ProductCharge productCharge = new ProductCharge(); productCharge.setProduct(product); productCharge.setCurrencyValue(currencyValue); productCharge.setPrice(newVal); productCharges.add(productCharge); } } productService.updatePricesForProducts(productCharges, channel); status = true; } catch (ServiceException ex) { throw new InvalidAjaxRequestException(ex.getMessage()); } logger.debug("### editCatalogProductPricing method starting...(POST)"); return status == true ? "success" : "failure"; }
From source file:net.pms.util.Rational.java
/** * Returns an instance with the given {@code numerator} and * {@code denominator}./*from www. j av a 2 s .c o m*/ * * @param numerator the numerator. * @param denominator the denominator. * @return An instance that represents the value of {@code numerator}/ * {@code denominator}. */ @Nullable public static Rational valueOf(@Nullable BigDecimal numerator, @Nullable BigDecimal denominator) { if (numerator == null || denominator == null) { return null; } if (numerator.signum() == 0 && denominator.signum() == 0) { return NaN; } if (denominator.signum() == 0) { return numerator.signum() > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY; } if (numerator.signum() == 0) { return ZERO; } if (numerator.equals(denominator)) { return ONE; } if (denominator.signum() < 0) { numerator = numerator.negate(); denominator = denominator.negate(); } int scale = Math.max(numerator.scale(), denominator.scale()); if (scale > 0) { numerator = numerator.scaleByPowerOfTen(scale); denominator = denominator.scaleByPowerOfTen(scale); } BigInteger biNumerator = numerator.toBigIntegerExact(); BigInteger biDenominator = denominator.toBigIntegerExact(); BigInteger reducedNumerator; BigInteger reducedDenominator; BigInteger greatestCommonDivisor = calculateGreatestCommonDivisor(biNumerator, biDenominator); if (BigInteger.ONE.equals(greatestCommonDivisor)) { reducedNumerator = biNumerator; reducedDenominator = biDenominator; } else { reducedNumerator = biNumerator.divide(greatestCommonDivisor); reducedDenominator = biDenominator.divide(greatestCommonDivisor); } return new Rational(biNumerator, biDenominator, greatestCommonDivisor, reducedNumerator, reducedDenominator); }
From source file:mx.edu.um.mateo.inventario.dao.impl.EntradaDaoHibernate.java
private Entrada preparaParaCerrar(Entrada entrada, Usuario usuario, Date fecha) throws NoCuadraException, NoSePuedeCerrarEnCeroException { BigDecimal iva = entrada.getIva(); BigDecimal total = entrada.getTotal(); entrada.setIva(BigDecimal.ZERO); entrada.setTotal(BigDecimal.ZERO); for (LoteEntrada lote : entrada.getLotes()) { Producto producto = lote.getProducto(); producto.setPrecioUnitario(costoPromedio(lote)); if (!entrada.getDevolucion()) { producto.setUltimoPrecio(lote.getPrecioUnitario()); }/*from w w w. j a v a 2 s .co m*/ producto.setExistencia(producto.getExistencia().add(lote.getCantidad())); producto.setFechaModificacion(fecha); currentSession().update(producto); auditaProducto(producto, usuario, Constantes.ACTUALIZAR, entrada.getId(), null, fecha); BigDecimal subtotal = lote.getPrecioUnitario().multiply(lote.getCantidad()); entrada.setIva(entrada.getIva().add(lote.getIva())); entrada.setTotal(entrada.getTotal().add(subtotal.add(lote.getIva()))); } if (total.equals(BigDecimal.ZERO)) { throw new NoSePuedeCerrarEnCeroException("No se puede cerrar la entrada en cero"); } // Si tanto el iva o el total difieren mas de un 5% del valor que // viene en la factura lanzar excepcion if (iva.compareTo(entrada.getIva()) != 0 || total.compareTo(entrada.getTotal()) != 0) { BigDecimal variacion = new BigDecimal("0.05"); BigDecimal topeIva = entrada.getIva().multiply(variacion); BigDecimal topeTotal = entrada.getTotal().multiply(variacion); if (iva.compareTo(entrada.getIva()) < 0 || total.compareTo(entrada.getTotal()) < 0) { if (iva.compareTo(entrada.getIva().subtract(topeIva)) >= 0 && total.compareTo(entrada.getTotal().subtract(topeTotal)) >= 0) { // todavia puede pasar } else { throw new NoCuadraException("No se puede cerrar porque no cuadran los totales"); } } else { if (iva.compareTo(entrada.getIva().add(topeIva)) <= 0 && total.compareTo(entrada.getTotal().add(topeTotal)) <= 0) { // todavia puede pasar } else { throw new NoCuadraException("No se puede cerrar porque no cuadran los totales"); } } } return entrada; }
From source file:com.xumpy.timesheets.services.implementations.JobsGraphics.java
public OverviewWorkDetails getOverviewWorkDetails(List<Jobs> jobs) throws ParseException { MathContext mc = new MathContext(3, RoundingMode.HALF_UP); OverviewWorkDetailsSrvPojo overviewWorkDetails = new OverviewWorkDetailsSrvPojo(); List<WorkingDay> workingDays = calculateWorkingDates(jobs); overviewWorkDetails.setHoursToWorkPerDay(new BigDecimal(8)); // Hardcoded BigDecimal hoursPayedPerDay = new BigDecimal(0, mc); BigDecimal workedWeekHours = new BigDecimal(0, mc); BigDecimal workedWeekendHours = new BigDecimal(0, mc); BigDecimal weekDays = new BigDecimal(0, mc); BigDecimal weekendDays = new BigDecimal(0, mc); BigDecimal workedWeekDays = new BigDecimal(0, mc); BigDecimal workedWeekendDays = new BigDecimal(0, mc); BigDecimal overtimeHours = new BigDecimal(0, mc); BigDecimal overtimeDays = new BigDecimal(0, mc); for (WorkingDay workingDay : workingDays) { if (CustomDateUtils.isWeekDay(workingDay.getDate())) { weekDays = weekDays.add(new BigDecimal(1)); workedWeekHours = workedWeekHours.add(workingDay.getActualWorkHours(), mc); workedWeekDays = workedWeekDays.add(new BigDecimal(1)); } else {// w ww .j ava 2 s . c o m weekendDays = weekendDays.add(new BigDecimal(1)); workedWeekendHours = workedWeekendHours.add(workingDay.getActualWorkHours(), mc); workedWeekendDays = workedWeekendDays.add(new BigDecimal(1)); } overtimeHours = overtimeHours.add(workingDay.getOvertimeHours(), mc); for (Jobs jobPerDay : workingDay.getJobs()) { if (jobPerDay.getJobsGroup().getCompany() != null) { if (hoursPayedPerDay .compareTo(jobPerDay.getJobsGroup().getCompany().getDailyPayedHours()) < 0) { hoursPayedPerDay = jobPerDay.getJobsGroup().getCompany().getDailyPayedHours(); } } } if (!hoursPayedPerDay.equals(new BigDecimal(0))) { overtimeDays = overtimeHours.divide(hoursPayedPerDay, mc); } else { overtimeDays = workedWeekDays.add(workedWeekendDays); } } overviewWorkDetails.setHoursPayedPerDay(hoursPayedPerDay); overviewWorkDetails.setWorkedWeekHours(workedWeekHours); overviewWorkDetails.setWorkedWeekendHours(workedWeekendHours); overviewWorkDetails.setWeekDays(weekDays); overviewWorkDetails.setWeekendDays(weekendDays); overviewWorkDetails.setWorkedWeekDays(workedWeekDays); overviewWorkDetails.setWorkedWeekendDays(workedWeekendDays); overviewWorkDetails.setOvertimeHours(overtimeHours); overviewWorkDetails.setOvertimeDays(overtimeDays); return overviewWorkDetails; }
From source file:org.egov.works.web.actions.estimate.FinancialDetailAction.java
public void search(final String src) { if (APP.equalsIgnoreCase(src) && abstractEstimate != null && abstractEstimate.getFinancialDetails().get(0) != null) financialDetail = abstractEstimate.getFinancialDetails().get(0); if (financialDetail != null && financialDetail.getFund() != null && financialDetail.getFund().getId() != null && financialDetail.getFund().getId() != -1) queryParamMap.put("fundid", financialDetail.getFund().getId()); if (financialDetail != null && financialDetail.getFunction() != null && financialDetail.getFunction().getId() != null && financialDetail.getFunction().getId() != -1) queryParamMap.put("functionid", financialDetail.getFunction().getId()); if (financialDetail != null && financialDetail.getBudgetGroup() != null && financialDetail.getBudgetGroup().getId() != null && financialDetail.getBudgetGroup().getId() != -1) { final List<BudgetGroup> budgetheadid = new ArrayList<BudgetGroup>(); budgetheadid.add(financialDetail.getBudgetGroup()); queryParamMap.put("budgetheadid", budgetheadid); }/* w w w.j a v a 2 s. co m*/ if (APP.equalsIgnoreCase(src) && financialDetail != null && financialDetail.getAbstractEstimate().getUserDepartment() != null) queryParamMap.put("deptid", financialDetail.getAbstractEstimate().getUserDepartment().getId()); else if (getUserDepartment() != null && getUserDepartment() != -1) queryParamMap.put("deptid", getUserDepartment()); if (APP.equalsIgnoreCase(src) && abstractEstimate != null && abstractEstimate.getLeastFinancialYearForEstimate() != null && abstractEstimate.getLeastFinancialYearForEstimate().getId() != null) { queryParamMap.put("financialyearid", financialDetail.getAbstractEstimate().getLeastFinancialYearForEstimate().getId()); queryParamMap.put("fromDate", financialDetail.getAbstractEstimate().getLeastFinancialYearForEstimate().getStartingDate()); queryParamMap.put("toDate", new Date()); } else if (getReportDate() != null) { if (!DateUtils.compareDates(new Date(), getReportDate())) throw new ValidationException(Arrays.asList(new ValidationError( "greaterthan.currentDate.reportDate", getText("greaterthan.currentDate.reportDate")))); CFinancialYear finyear = null; try { finyear = abstractEstimateService.getCurrentFinancialYear(getReportDate()); } catch (final ApplicationRuntimeException noFinYearExp) { if (noFinYearExp.getMessage().equals("Financial Year Id does not exist.")) throw new ValidationException(Arrays .asList(new ValidationError(noFinYearExp.getMessage(), noFinYearExp.getMessage()))); else throw noFinYearExp; } if (finyear != null && finyear.getId() != null) queryParamMap.put("financialyearid", finyear.getId()); queryParamMap.put("toDate", getReportDate()); } if (!queryParamMap.isEmpty() && getFieldErrors().isEmpty()) { BigDecimal planningBudgetPerc = new BigDecimal(0); try { totalGrant = budgetDetailsDAO.getBudgetedAmtForYear(queryParamMap); planningBudgetPerc = getPlanningBudgetPercentage(queryParamMap); } catch (final ValidationException valEx) { logger.error(valEx); } // String appValue = // worksService.getWorksConfigValue(PERCENTAGE_GRANT); if (planningBudgetPerc != null && !planningBudgetPerc.equals(0)) { setAppValueLabel(planningBudgetPerc.toString()); totalGrantPerc = totalGrant.multiply(planningBudgetPerc.divide(new BigDecimal(100))); queryParamMap.put("totalGrantPerc", totalGrantPerc); } final Map<String, List> approvedBudgetFolioDetailsMap = abstractEstimateService .getApprovedAppropriationDetailsForBugetHead(queryParamMap); approvedBudgetFolioDetails = new ArrayList<BudgetFolioDetail>(); if (approvedBudgetFolioDetailsMap != null && !approvedBudgetFolioDetailsMap.isEmpty()) { approvedBudgetFolioDetails = approvedBudgetFolioDetailsMap.get("budgetFolioList"); setReportLatestValues(approvedBudgetFolioDetailsMap); } } }
From source file:au.org.ala.delta.editor.slotfile.directive.DirOutDefault.java
@Override public void writeDirectiveArguments(DirectiveInOutState state) { _deltaWriter.setIndent(2);/* w w w .j ava2 s. com*/ MutableDeltaDataSet dataSet = state.getDataSet(); Directive curDirective = state.getCurrentDirective().getDirective(); // Dir directive; DirectiveArguments directiveArgs = state.getCurrentDirective().getDirectiveArguments(); int argType = curDirective.getArgType(); String temp = ""; DirectiveType directiveType = state.getCurrentDirective().getType(); List<Integer> dataList = null; int prevNo, curNo; List<DirectiveArgument<?>> args = null; switch (argType) { case DirectiveArgType.DIRARG_NONE: case DirectiveArgType.DIRARG_TRANSLATION: case DirectiveArgType.DIRARG_INTKEY_INCOMPLETE: break; case DirectiveArgType.DIRARG_TEXT: // What about multiple lines of text? // Should line breaks ALWAYS be // preserved? case DirectiveArgType.DIRARG_COMMENT: // Will actually be handled within // DirComment _deltaWriter.setIndent(0); case DirectiveArgType.DIRARG_FILE: case DirectiveArgType.DIRARG_OTHER: case DirectiveArgType.DIRARG_INTERNAL: writeText(directiveArgs, argType); break; case DirectiveArgType.DIRARG_INTEGER: case DirectiveArgType.DIRARG_REAL: if (directiveArgs.size() > 0) { _textBuffer.append(' '); _textBuffer.append(directiveArgs.getFirstArgumentValueAsString()); } break; case DirectiveArgType.DIRARG_CHAR: case DirectiveArgType.DIRARG_ITEM: if (directiveArgs.size() > 0) { _textBuffer.append(' '); curNo = directiveArgs.getFirstArgumentIdAsInt(); _textBuffer.append(curNo); } break; case DirectiveArgType.DIRARG_CHARLIST: case DirectiveArgType.DIRARG_ITEMLIST: if (directiveArgs.size() > 0) { dataList = new ArrayList<Integer>(); for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) dataList.add((Integer) vectIter.getId()); _textBuffer.append(' '); appendRange(dataList, ' ', true, _textBuffer); } break; case DirectiveArgType.DIRARG_TEXTLIST: // Special handling for "legacy" data, when this was stored as a // simple, large // text block... if (directiveArgs.size() == 1 && directiveArgs.getFirstArgumentIdAsInt() <= 0 && directiveArgs.getFirstArgumentText().length() > 1) { writeText(directiveArgs, DirectiveArgType.DIRARG_TEXT); break; } // Otherwise drop through... case DirectiveArgType.DIRARG_CHARTEXTLIST: case DirectiveArgType.DIRARG_ITEMTEXTLIST: case DirectiveArgType.DIRARG_ITEMFILELIST: { writeTextList(dataSet, directiveArgs, argType, temp); break; } case DirectiveArgType.DIRARG_CHARINTEGERLIST: case DirectiveArgType.DIRARG_CHARREALLIST: case DirectiveArgType.DIRARG_ITEMREALLIST: writeNumberList(directiveArgs); break; case DirectiveArgType.DIRARG_CHARGROUPS: for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) { dataList = new ArrayList<Integer>(vectIter.getDataList()); _textBuffer.append(' '); appendRange(dataList, ':', true, _textBuffer); } break; case DirectiveArgType.DIRARG_ITEMCHARLIST: writeItemCharacterList(dataSet, directiveArgs, directiveType); break; case DirectiveArgType.DIRARG_ALLOWED: args = directiveArgs.getDirectiveArguments(); Collections.sort(args); for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) { curNo = (Integer) vectIter.getId(); _textBuffer.append(' '); _textBuffer.append(curNo); _textBuffer.append(','); List<Integer> tmpData = vectIter.getDataList(); if (tmpData.size() < 3) throw new RuntimeException("ED_INTERNAL_ERROR"); temp = Integer.toString(tmpData.get(0)); _textBuffer.append(temp + ':'); temp = Integer.toString(tmpData.get(1)); _textBuffer.append(temp + ':'); temp = Integer.toString(tmpData.get(2)); _textBuffer.append(temp); } break; case DirectiveArgType.DIRARG_KEYSTATE: writeKeyStates(dataSet, directiveArgs); break; case DirectiveArgType.DIRARG_PRESET: for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) { curNo = (Integer) vectIter.getId(); _textBuffer.append(' '); _textBuffer.append(curNo); _textBuffer.append(','); if (vectIter.getData().size() < 2) throw new RuntimeException("ED_INTERNAL_ERROR"); _textBuffer.append(vectIter.getDataList().get(0)); _textBuffer.append(':'); _textBuffer.append(vectIter.getDataList().get(1)); } break; case DirectiveArgType.DIRARG_INTKEY_ONOFF: if (directiveArgs.size() > 0 && directiveArgs.getFirstArgumentValue() != 0.0) { _textBuffer.append(' '); if (directiveArgs.getFirstArgumentValue() < 0.0) _textBuffer.append("Off"); else if (directiveArgs.getFirstArgumentValue() > 0.0) _textBuffer.append("On"); } break; case DirectiveArgType.DIRARG_INTKEY_ITEM: if (directiveArgs.size() > 0) { if (directiveArgs.getFirstArgumentIdAsInt() > 0) { _textBuffer.append(' '); curNo = directiveArgs.getFirstArgumentIdAsInt(); _textBuffer.append(curNo); } else appendKeyword(_textBuffer, directiveArgs.getFirstArgumentText()); } break; case DirectiveArgType.DIRARG_KEYWORD_CHARLIST: case DirectiveArgType.DIRARG_KEYWORD_ITEMLIST: case DirectiveArgType.DIRARG_INTKEY_CHARLIST: case DirectiveArgType.DIRARG_INTKEY_ITEMLIST: dataList = new ArrayList<Integer>(); for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) { if ((Integer) vectIter.getId() > 0) dataList.add((Integer) vectIter.getId()); else appendKeyword(_textBuffer, vectIter.getText(), (argType == DirectiveArgType.DIRARG_KEYWORD_CHARLIST || argType == DirectiveArgType.DIRARG_KEYWORD_ITEMLIST) && vectIter == directiveArgs.get(0)); } if (dataList.size() > 0) { _textBuffer.append(' '); appendRange(dataList, ' ', true, _textBuffer); } break; case DirectiveArgType.DIRARG_INTKEY_CHARREALLIST: if (directiveArgs.size() > 0) { // Will sort all keywords to appear before actual character // numbers, and group characters appropriately args = directiveArgs.getDirectiveArguments(); Collections.sort(args); curNo = Integer.MAX_VALUE; prevNo = Integer.MAX_VALUE; dataList = new ArrayList<Integer>(); BigDecimal curVal = BigDecimal.ZERO; BigDecimal prevVal = BigDecimal.ZERO; boolean firstChar = true; for (int i = 0; i <= args.size(); i++) // Note that vectIter is allowed to equal .end() // This allows the last value to be handled correctly within the // loop. // Be careful not to de-reference vectIter when this happens. { if (i != args.size()) { DirectiveArgument<?> vectIter = args.get(i); curVal = vectIter.getValue(); if ((Integer) vectIter.getId() <= 0) { appendKeyword(_textBuffer, vectIter.getText()); if (!(curVal.compareTo(BigDecimal.ZERO) < 0.0)) { _textBuffer.append(','); _textBuffer.append(curVal.toPlainString()); } continue; } curNo = (Integer) vectIter.getId(); } if (firstChar || (prevNo == curNo - 1 && prevVal.equals(curVal))) { dataList.add(curNo); firstChar = false; } else if (dataList.size() > 0) { _textBuffer.append(' '); appendRange(dataList, ' ', false, _textBuffer); if (!(prevVal.compareTo(BigDecimal.ZERO) < 0.0)) { _textBuffer.append(','); _textBuffer.append(prevVal.toPlainString()); } dataList = new ArrayList<Integer>(); dataList.add(curNo); } prevNo = curNo; prevVal = curVal; } } break; case DirectiveArgType.DIRARG_INTKEY_ITEMCHARSET: writeIntItemCharSetArgs(argType, directiveArgs, _textBuffer); break; case DirectiveArgType.DIRARG_INTKEY_ATTRIBUTES: writeIntkeyAttributesArgs(directiveArgs, _textBuffer, dataSet); break; default: break; } outputTextBuffer(0, 2, false); }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractChannelController.java
@RequestMapping(value = ("/editcatalogproductbundlepricing"), method = RequestMethod.POST) public String editCatalogProductBundlePricing( @RequestParam(value = "channelId", required = true) String channelId, @RequestParam(value = "bundleId", required = true) String bundleId, @RequestParam(value = "currencyValData", required = true) String currencyValData, ModelMap map) throws JSONException { logger.debug("### editCatalogProductBundlePricing method starting...(POST)"); boolean status = false; try {/*from ww w. j av a 2 s . c o m*/ Channel channel = channelService.getChannelById(channelId); ProductBundle productBundle = productBundleService.locateProductBundleById(bundleId); JSONArray jsonArray = new JSONArray(currencyValData); Revision futureRevision = channelService.getFutureRevision(channel); for (int index = 0; index < jsonArray.length(); index++) { JSONObject jsonObj = jsonArray.getJSONObject(index); BigDecimal previousVal = new BigDecimal(jsonObj.get("previousvalue").toString()); BigDecimal newVal = new BigDecimal(jsonObj.get("value").toString()); String currencyCode = jsonObj.get("currencycode").toString(); String isRecurring = jsonObj.getString("isRecurring").toString(); boolean isRecurringCharge = false; if (isRecurring.equals("1")) { isRecurringCharge = true; } if (!previousVal.equals(newVal)) { CurrencyValue currencyValue = currencyValueService.locateBYCurrencyCode(currencyCode); productBundleService.updatePriceForBundle(productBundle, channel, currencyValue, newVal, futureRevision, isRecurringCharge); } } status = true; } catch (ServiceException ex) { throw new InvalidAjaxRequestException(ex.getMessage()); } logger.debug("### editCatalogProductBundlePricing method ending...(POST)"); return status == true ? "success" : "failure"; }
From source file:org.kuali.kpme.tklm.leave.approval.service.LeaveApprovalServiceImpl.java
public List<Map<String, Object>> getLeaveApprovalDetailSections(String principalId, LeaveCalendarDocumentHeader lcdh, DateTime beginDate, DateTime endDate, List<LocalDateTime> leaveSummaryDates, String week, Map<String, Boolean> enableWeekDetails) { List<Map<String, Object>> acRows = new ArrayList<Map<String, Object>>(); //CalendarEntry calendarEntry = LmServiceLocator.getLeaveCalendarService().getLeaveCalendarDocument(lcdh.getDocumentId()).getCalendarEntry(); //CalendarEntries calendarEntry = TkServiceLocator.getCalendarEntriesService().getCalendarEntriesByBeginAndEndDate(lcdh.getBeginDate(), lcdh.getEndDate()); LeaveSummaryContract leaveSummary;/*from w w w . j a va2 s . c om*/ PrincipalHRAttributes pha; // List<Date> leaveSummaryDates = LmServiceLocator.getLeaveSummaryService().getLeaveSummaryDates(calendarEntry); try { leaveSummary = LmServiceLocator.getLeaveSummaryService().getLeaveSummaryAsOfDate(principalId, endDate.toLocalDate()); pha = HrServiceLocator.getPrincipalHRAttributeService().getPrincipalCalendar(principalId, endDate.toLocalDate()); } catch (Exception e) { leaveSummary = null; pha = null; } List<LeaveBlock> leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocks(principalId, beginDate.toLocalDate(), endDate.toLocalDate()); Map<LocalDateTime, Map<String, BigDecimal>> accrualCategoryLeaveHours = getAccrualCategoryLeaveHours( leaveBlocks, leaveSummaryDates); //get all accrual categories of this employee if (pha != null) { List<? extends AccrualCategoryContract> acList = HrServiceLocator.getAccrualCategoryService() .getActiveAccrualCategoriesForLeavePlan(pha.getLeavePlan(), endDate.toLocalDate()); for (AccrualCategoryContract ac : acList) { List<BigDecimal> acDayDetails = new ArrayList<BigDecimal>(); Map<String, Object> displayMap = new HashMap<String, Object>(); BigDecimal totalAmount = BigDecimal.ZERO; displayMap.put("accrualCategory", ac.getAccrualCategory()); int index = 0; for (LocalDateTime leaveSummaryDate : leaveSummaryDates) { if (leaveSummaryDate.compareTo(beginDate.toLocalDateTime()) >= 0 && leaveSummaryDate.compareTo(endDate.toLocalDateTime()) <= 0) { acDayDetails.add(index, null); if (accrualCategoryLeaveHours.get(leaveSummaryDate) != null) { Map<String, BigDecimal> leaveHours = accrualCategoryLeaveHours.get(leaveSummaryDate); if (leaveHours.containsKey(ac.getAccrualCategory())) { BigDecimal amount = leaveHours.get(ac.getAccrualCategory()); totalAmount = totalAmount.add(amount); acDayDetails.set(index, amount); } } index++; } } LeaveSummaryRowContract lsr = leaveSummary == null ? null : leaveSummary.getLeaveSummaryRowForAccrualCtgy(ac.getAccrualCategory()); if (!totalAmount.equals(BigDecimal.ZERO)) { enableWeekDetails.put(week, Boolean.TRUE); } displayMap.put("periodUsage", totalAmount); displayMap.put("availableBalance", BigDecimal.ZERO); displayMap.put("availableBalance", lsr == null ? BigDecimal.ZERO : lsr.getLeaveBalance()); displayMap.put("daysDetail", acDayDetails); displayMap.put("daysSize", acDayDetails.size()); acRows.add(displayMap); } } return acRows; }
From source file:pcgen.gui2.facade.Gui2InfoFactory.java
/** * @see pcgen.facade.core.InfoFactory#getHTMLInfo(AbilityFacade) *//*from w ww. j a v a 2s. c om*/ @Override public String getHTMLInfo(AbilityFacade abilityFacade) { if (!(abilityFacade instanceof Ability)) { return EMPTY_STRING; } Ability ability = (Ability) abilityFacade; final HtmlInfoBuilder infoText = new HtmlInfoBuilder(); infoText.appendTitleElement(OutputNameFormatting.piString(ability)); infoText.appendLineBreak(); infoText.appendI18nFormattedElement("Ability.Info.Type", //$NON-NLS-1$ StringUtil.join(ability.getTrueTypeList(true), ". ")); //$NON-NLS-1$ BigDecimal costStr = ability.getSafe(ObjectKey.SELECTION_COST); if (!costStr.equals(BigDecimal.ONE)) { infoText.appendI18nFormattedElement("Ability.Info.Cost", //$NON-NLS-1$ COST_FMT.format(costStr)); } if (ability.getSafe(ObjectKey.MULTIPLE_ALLOWED)) { infoText.appendSpacer(); infoText.append(LanguageBundle.getString("Ability.Info.Multiple")); //$NON-NLS-1$ } if (ability.getSafe(ObjectKey.STACKS)) { infoText.appendSpacer(); infoText.append(LanguageBundle.getString("Ability.Info.Stacks")); //$NON-NLS-1$ } appendFacts(infoText, ability); final String cString = PrerequisiteUtilities.preReqHTMLStringsForList(pc, null, ability.getPrerequisiteList(), false); if (!cString.isEmpty()) { infoText.appendI18nFormattedElement("in_InfoRequirements", //$NON-NLS-1$ cString); } String aString = AllowUtilities.getAllowInfo(pc, ability); if (!aString.isEmpty()) { infoText.appendLineBreak(); infoText.appendI18nElement("in_requirements", aString); //$NON-NLS-1$ } infoText.appendLineBreak(); infoText.appendI18nFormattedElement("in_InfoDescription", //$NON-NLS-1$ getDescription(abilityFacade)); List<CNAbility> wrappedAbility = getWrappedAbility(ability); if (ability.getSafeSizeOfMapFor(MapKey.ASPECT) > 0) { Set<AspectName> aspectKeys = ability.getKeysFor(MapKey.ASPECT); StringBuilder buff = new StringBuilder(100); for (AspectName key : aspectKeys) { if (buff.length() > 0) { buff.append(", "); } //Assert here that the actual text displayed is not critical buff.append(Aspect.printAspect(pc, key, wrappedAbility)); } infoText.appendLineBreak(); infoText.appendI18nFormattedElement("Ability.Info.Aspects", //$NON-NLS-1$ buff.toString()); } final String bene = BenefitFormatting.getBenefits(pc, wrappedAbility); if (bene != null && !bene.isEmpty()) { infoText.appendLineBreak(); infoText.appendI18nFormattedElement("Ability.Info.Benefit", //$NON-NLS-1$ BenefitFormatting.getBenefits(pc, wrappedAbility)); } infoText.appendLineBreak(); infoText.appendI18nFormattedElement("in_InfoSource", //$NON-NLS-1$ ability.getSource()); return infoText.toString(); }
From source file:org.ofbiz.order.shoppingcart.ShoppingCartServices.java
public static Map<String, Object> loadCartFromOrder(DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); GenericValue userLogin = (GenericValue) context.get("userLogin"); String orderId = (String) context.get("orderId"); Boolean skipInventoryChecks = (Boolean) context.get("skipInventoryChecks"); Boolean skipProductChecks = (Boolean) context.get("skipProductChecks"); boolean includePromoItems = Boolean.TRUE.equals(context.get("includePromoItems")); Locale locale = (Locale) context.get("locale"); if (UtilValidate.isEmpty(skipInventoryChecks)) { skipInventoryChecks = Boolean.FALSE; }/*from w ww . ja v a2 s . c om*/ if (UtilValidate.isEmpty(skipProductChecks)) { skipProductChecks = Boolean.FALSE; } // get the order header GenericValue orderHeader = null; try { orderHeader = delegator.findOne("OrderHeader", UtilMisc.toMap("orderId", orderId), false); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // initial require cart info OrderReadHelper orh = new OrderReadHelper(orderHeader); String productStoreId = orh.getProductStoreId(); String orderTypeId = orh.getOrderTypeId(); String currency = orh.getCurrency(); String website = orh.getWebSiteId(); String currentStatusString = orh.getCurrentStatusString(); // create the cart ShoppingCart cart = new ShoppingCart(delegator, productStoreId, website, locale, currency); cart.setDoPromotions(!includePromoItems); cart.setOrderType(orderTypeId); cart.setChannelType(orderHeader.getString("salesChannelEnumId")); cart.setInternalCode(orderHeader.getString("internalCode")); cart.setOrderDate(UtilDateTime.nowTimestamp()); cart.setOrderId(orderHeader.getString("orderId")); cart.setOrderName(orderHeader.getString("orderName")); cart.setOrderStatusId(orderHeader.getString("statusId")); cart.setOrderStatusString(currentStatusString); cart.setFacilityId(orderHeader.getString("originFacilityId")); try { cart.setUserLogin(userLogin, dispatcher); } catch (CartItemModifyException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // set the order name String orderName = orh.getOrderName(); if (orderName != null) { cart.setOrderName(orderName); } // set the role information GenericValue placingParty = orh.getPlacingParty(); if (placingParty != null) { cart.setPlacingCustomerPartyId(placingParty.getString("partyId")); } GenericValue billFromParty = orh.getBillFromParty(); if (billFromParty != null) { cart.setBillFromVendorPartyId(billFromParty.getString("partyId")); } GenericValue billToParty = orh.getBillToParty(); if (billToParty != null) { cart.setBillToCustomerPartyId(billToParty.getString("partyId")); } GenericValue shipToParty = orh.getShipToParty(); if (shipToParty != null) { cart.setShipToCustomerPartyId(shipToParty.getString("partyId")); } GenericValue endUserParty = orh.getEndUserParty(); if (endUserParty != null) { cart.setEndUserCustomerPartyId(endUserParty.getString("partyId")); cart.setOrderPartyId(endUserParty.getString("partyId")); } // load order attributes List<GenericValue> orderAttributesList = null; try { orderAttributesList = delegator.findByAnd("OrderAttribute", UtilMisc.toMap("orderId", orderId), null, false); if (UtilValidate.isNotEmpty(orderAttributesList)) { for (GenericValue orderAttr : orderAttributesList) { String name = orderAttr.getString("attrName"); String value = orderAttr.getString("attrValue"); cart.setOrderAttribute(name, value); } } } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // load the payment infos List<GenericValue> orderPaymentPrefs = null; try { List<EntityExpr> exprs = UtilMisc .toList(EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId)); exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_RECEIVED")); exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED")); exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_DECLINED")); exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_SETTLED")); EntityCondition cond = EntityCondition.makeCondition(exprs, EntityOperator.AND); orderPaymentPrefs = delegator.findList("OrderPaymentPreference", cond, null, null, null, false); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (UtilValidate.isNotEmpty(orderPaymentPrefs)) { Iterator<GenericValue> oppi = orderPaymentPrefs.iterator(); while (oppi.hasNext()) { GenericValue opp = oppi.next(); String paymentId = opp.getString("paymentMethodId"); if (paymentId == null) { paymentId = opp.getString("paymentMethodTypeId"); } BigDecimal maxAmount = opp.getBigDecimal("maxAmount"); String overflow = opp.getString("overflowFlag"); ShoppingCart.CartPaymentInfo cpi = null; if ((overflow == null || !"Y".equals(overflow)) && oppi.hasNext()) { cpi = cart.addPaymentAmount(paymentId, maxAmount); Debug.logInfo("Added Payment: " + paymentId + " / " + maxAmount, module); } else { cpi = cart.addPayment(paymentId); Debug.logInfo("Added Payment: " + paymentId + " / [no max]", module); } // for finance account the finAccountId needs to be set if ("FIN_ACCOUNT".equals(paymentId)) { cpi.finAccountId = opp.getString("finAccountId"); } // set the billing account and amount cart.setBillingAccount(orderHeader.getString("billingAccountId"), orh.getBillingAccountMaxAmount()); } } else { Debug.logInfo("No payment preferences found for order #" + orderId, module); } List<GenericValue> orderItemShipGroupList = orh.getOrderItemShipGroups(); for (GenericValue orderItemShipGroup : orderItemShipGroupList) { // should be sorted by shipGroupSeqId int newShipInfoIndex = cart.addShipInfo(); // shouldn't be gaps in it but allow for that just in case String cartShipGroupIndexStr = orderItemShipGroup.getString("shipGroupSeqId"); int cartShipGroupIndex = NumberUtils.toInt(cartShipGroupIndexStr); if (newShipInfoIndex != (cartShipGroupIndex - 1)) { int groupDiff = cartShipGroupIndex - cart.getShipGroupSize(); for (int i = 0; i < groupDiff; i++) { newShipInfoIndex = cart.addShipInfo(); } } CartShipInfo cartShipInfo = cart.getShipInfo(newShipInfoIndex); cartShipInfo.shipAfterDate = orderItemShipGroup.getTimestamp("shipAfterDate"); cartShipInfo.shipBeforeDate = orderItemShipGroup.getTimestamp("shipByDate"); cartShipInfo.shipmentMethodTypeId = orderItemShipGroup.getString("shipmentMethodTypeId"); cartShipInfo.carrierPartyId = orderItemShipGroup.getString("carrierPartyId"); cartShipInfo.supplierPartyId = orderItemShipGroup.getString("supplierPartyId"); cartShipInfo.setMaySplit(orderItemShipGroup.getBoolean("maySplit")); cartShipInfo.giftMessage = orderItemShipGroup.getString("giftMessage"); cartShipInfo.setContactMechId(orderItemShipGroup.getString("contactMechId")); cartShipInfo.shippingInstructions = orderItemShipGroup.getString("shippingInstructions"); cartShipInfo.setFacilityId(orderItemShipGroup.getString("facilityId")); cartShipInfo.setVendorPartyId(orderItemShipGroup.getString("vendorPartyId")); cartShipInfo.setShipGroupSeqId(orderItemShipGroup.getString("shipGroupSeqId")); cartShipInfo.shipTaxAdj .addAll(orh.getOrderHeaderAdjustmentsTax(orderItemShipGroup.getString("shipGroupSeqId"))); } List<GenericValue> orderItems = orh.getOrderItems(); long nextItemSeq = 0; if (UtilValidate.isNotEmpty(orderItems)) { for (GenericValue item : orderItems) { // get the next item sequence id String orderItemSeqId = item.getString("orderItemSeqId"); orderItemSeqId = orderItemSeqId.replaceAll("\\P{Digit}", ""); // get product Id String productId = item.getString("productId"); GenericValue product = null; // creates survey responses for Gift cards same as last Order // created Map<String, Object> surveyResponseResult = null; try { long seq = Long.parseLong(orderItemSeqId); if (seq > nextItemSeq) { nextItemSeq = seq; } } catch (NumberFormatException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if ("ITEM_REJECTED".equals(item.getString("statusId")) || "ITEM_CANCELLED".equals(item.getString("statusId"))) continue; try { product = delegator.findOne("Product", UtilMisc.toMap("productId", productId), false); if ("DIGITAL_GOOD".equals(product.getString("productTypeId"))) { Map<String, Object> surveyResponseMap = FastMap.newInstance(); Map<String, Object> answers = FastMap.newInstance(); List<GenericValue> surveyResponseAndAnswers = delegator.findByAnd("SurveyResponseAndAnswer", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId), null, false); if (UtilValidate.isNotEmpty(surveyResponseAndAnswers)) { String surveyId = EntityUtil.getFirst(surveyResponseAndAnswers).getString("surveyId"); for (GenericValue surveyResponseAndAnswer : surveyResponseAndAnswers) { answers.put((surveyResponseAndAnswer.get("surveyQuestionId").toString()), surveyResponseAndAnswer.get("textResponse")); } surveyResponseMap.put("answers", answers); surveyResponseMap.put("surveyId", surveyId); surveyResponseResult = dispatcher.runSync("createSurveyResponse", surveyResponseMap); } } } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } catch (GenericServiceException e) { Debug.logError(e.toString(), module); return ServiceUtil.returnError(e.toString()); } // do not include PROMO items if (!includePromoItems && item.get("isPromo") != null && "Y".equals(item.getString("isPromo"))) { continue; } // not a promo item; go ahead and add it in BigDecimal amount = item.getBigDecimal("selectedAmount"); if (amount == null) { amount = BigDecimal.ZERO; } BigDecimal quantity = item.getBigDecimal("quantity"); if (quantity == null) { quantity = BigDecimal.ZERO; } BigDecimal unitPrice = null; if ("Y".equals(item.getString("isModifiedPrice"))) { unitPrice = item.getBigDecimal("unitPrice"); } int itemIndex = -1; if (item.get("productId") == null) { // non-product item String itemType = item.getString("orderItemTypeId"); String desc = item.getString("itemDescription"); try { // TODO: passing in null now for itemGroupNumber, but // should reproduce from OrderItemGroup records itemIndex = cart.addNonProductItem(itemType, desc, null, unitPrice, quantity, null, null, null, dispatcher); } catch (CartItemModifyException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } else { // product item String prodCatalogId = item.getString("prodCatalogId"); // prepare the rental data Timestamp reservStart = null; BigDecimal reservLength = null; BigDecimal reservPersons = null; String accommodationMapId = null; String accommodationSpotId = null; GenericValue workEffort = null; String workEffortId = orh.getCurrentOrderItemWorkEffort(item); if (workEffortId != null) { try { workEffort = delegator.findOne("WorkEffort", UtilMisc.toMap("workEffortId", workEffortId), false); } catch (GenericEntityException e) { Debug.logError(e, module); } } if (workEffort != null && "ASSET_USAGE".equals(workEffort.getString("workEffortTypeId"))) { reservStart = workEffort.getTimestamp("estimatedStartDate"); reservLength = OrderReadHelper.getWorkEffortRentalLength(workEffort); reservPersons = workEffort.getBigDecimal("reservPersons"); accommodationMapId = workEffort.getString("accommodationMapId"); accommodationSpotId = workEffort.getString("accommodationSpotId"); } // end of rental data // check for AGGREGATED products ProductConfigWrapper configWrapper = null; String configId = null; try { product = delegator.findOne("Product", UtilMisc.toMap("productId", productId), false); if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "AGGREGATED")) { List<GenericValue> productAssocs = delegator.findByAnd("ProductAssoc", UtilMisc.toMap("productAssocTypeId", "PRODUCT_CONF", "productIdTo", product.getString("productId")), null, false); productAssocs = EntityUtil.filterByDate(productAssocs); if (UtilValidate.isNotEmpty(productAssocs)) { productId = EntityUtil.getFirst(productAssocs).getString("productId"); configId = product.getString("configId"); } } } catch (GenericEntityException e) { Debug.logError(e, module); } if (UtilValidate.isNotEmpty(configId)) { configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher, configId, productId, productStoreId, prodCatalogId, website, currency, locale, userLogin); } try { itemIndex = cart.addItemToEnd(productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, accommodationMapId, accommodationSpotId, null, null, prodCatalogId, configWrapper, item.getString("orderItemTypeId"), dispatcher, null, unitPrice == null ? null : false, skipInventoryChecks, skipProductChecks); } catch (ItemNotFoundException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } catch (CartItemModifyException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } // flag the item w/ the orderItemSeqId so we can reference it ShoppingCartItem cartItem = cart.findCartItem(itemIndex); cartItem.setIsPromo(item.get("isPromo") != null && "Y".equals(item.getString("isPromo"))); cartItem.setOrderItemSeqId(item.getString("orderItemSeqId")); try { cartItem.setItemGroup(cart.addItemGroup(item.getRelatedOne("OrderItemGroup", true))); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // attach surveyResponseId for each item if (UtilValidate.isNotEmpty(surveyResponseResult)) { cartItem.setAttribute("surveyResponseId", surveyResponseResult.get("surveyResponseId")); } // attach addition item information cartItem.setStatusId(item.getString("statusId")); cartItem.setItemType(item.getString("orderItemTypeId")); cartItem.setItemComment(item.getString("comments")); cartItem.setQuoteId(item.getString("quoteId")); cartItem.setQuoteItemSeqId(item.getString("quoteItemSeqId")); cartItem.setProductCategoryId(item.getString("productCategoryId")); cartItem.setDesiredDeliveryDate(item.getTimestamp("estimatedDeliveryDate")); cartItem.setShipBeforeDate(item.getTimestamp("shipBeforeDate")); cartItem.setShipAfterDate(item.getTimestamp("shipAfterDate")); cartItem.setShoppingList(item.getString("shoppingListId"), item.getString("shoppingListItemSeqId")); cartItem.setIsModifiedPrice("Y".equals(item.getString("isModifiedPrice"))); cartItem.setName(item.getString("itemDescription")); cartItem.setExternalId(item.getString("externalId")); // load order item attributes List<GenericValue> orderItemAttributesList = null; try { orderItemAttributesList = delegator.findByAnd("OrderItemAttribute", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId), null, false); if (UtilValidate.isNotEmpty(orderItemAttributesList)) { for (GenericValue orderItemAttr : orderItemAttributesList) { String name = orderItemAttr.getString("attrName"); String value = orderItemAttr.getString("attrValue"); cartItem.setOrderItemAttribute(name, value); } } } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // load order item contact mechs List<GenericValue> orderItemContactMechList = null; try { orderItemContactMechList = delegator.findByAnd("OrderItemContactMech", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId), null, false); if (UtilValidate.isNotEmpty(orderItemContactMechList)) { for (GenericValue orderItemContactMech : orderItemContactMechList) { String contactMechPurposeTypeId = orderItemContactMech .getString("contactMechPurposeTypeId"); String contactMechId = orderItemContactMech.getString("contactMechId"); cartItem.addContactMech(contactMechPurposeTypeId, contactMechId); } } } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // set the PO number on the cart cart.setPoNumber(item.getString("correspondingPoId")); // get all item adjustments EXCEPT tax adjustments List<GenericValue> itemAdjustments = orh.getOrderItemAdjustments(item); if (itemAdjustments != null) { for (GenericValue itemAdjustment : itemAdjustments) { if (!isTaxAdjustment(itemAdjustment)) cartItem.addAdjustment(itemAdjustment); } } } // setup the OrderItemShipGroupAssoc records if (UtilValidate.isNotEmpty(orderItems)) { int itemIndex = 0; for (GenericValue item : orderItems) { // if rejected or cancelled ignore, just like above // otherwise all indexes will be off by one! if ("ITEM_REJECTED".equals(item.getString("statusId")) || "ITEM_CANCELLED".equals(item.getString("statusId"))) continue; List<GenericValue> orderItemAdjustments = orh.getOrderItemAdjustments(item); // set the item's ship group info List<GenericValue> shipGroupAssocs = orh.getOrderItemShipGroupAssocs(item); for (int g = 0; g < shipGroupAssocs.size(); g++) { GenericValue sgAssoc = shipGroupAssocs.get(g); BigDecimal shipGroupQty = OrderReadHelper.getOrderItemShipGroupQuantity(sgAssoc); if (shipGroupQty == null) { shipGroupQty = BigDecimal.ZERO; } String cartShipGroupIndexStr = sgAssoc.getString("shipGroupSeqId"); int cartShipGroupIndex = NumberUtils.toInt(cartShipGroupIndexStr); cartShipGroupIndex = cartShipGroupIndex - 1; if (cartShipGroupIndex > 0) { cart.positionItemToGroup(itemIndex, shipGroupQty, 0, cartShipGroupIndex, false); } // because the ship groups are setup before loading // items, and the ShoppingCart.addItemToEnd // method is called when loading items above and it // calls ShoppingCart.setItemShipGroupQty, // this may not be necessary here, so check it first as // calling it here with 0 quantity and // such ends up removing cart items from the group, // which causes problems later with inventory // reservation, tax calculation, etc. ShoppingCart.CartShipInfo csi = cart.getShipInfo(cartShipGroupIndex); ShoppingCartItem cartItem = cart.findCartItem(itemIndex); if (cartItem == null || cartItem.getQuantity() == null || BigDecimal.ZERO.equals(cartItem.getQuantity()) || shipGroupQty.equals(cartItem.getQuantity())) { Debug.logInfo("In loadCartFromOrder not adding item [" + item.getString("orderItemSeqId") + "] to ship group with index [" + itemIndex + "]; group quantity is [" + shipGroupQty + "] item quantity is [" + (cartItem != null ? cartItem.getQuantity() : "no cart item") + "] cartShipGroupIndex is [" + cartShipGroupIndex + "], csi.shipItemInfo.size(): " + csi.shipItemInfo.size(), module); } else { cart.setItemShipGroupQty(itemIndex, shipGroupQty, cartShipGroupIndex); } List<GenericValue> shipGroupItemAdjustments = EntityUtil.filterByAnd(orderItemAdjustments, UtilMisc.toMap("shipGroupSeqId", cartShipGroupIndexStr)); if (cartItem == null) { Debug.logWarning("In loadCartFromOrder could not find cart item for itemIndex=" + itemIndex + ", for orderId=" + orderId, module); } else { CartShipItemInfo cartShipItemInfo = csi.getShipItemInfo(cartItem); if (cartShipItemInfo == null) { Debug.logWarning( "In loadCartFromOrder could not find CartShipItemInfo for itemIndex=" + itemIndex + ", for orderId=" + orderId, module); } else { List<GenericValue> itemTaxAdj = cartShipItemInfo.itemTaxAdj; for (GenericValue shipGroupItemAdjustment : shipGroupItemAdjustments) { if (isTaxAdjustment(shipGroupItemAdjustment)) itemTaxAdj.add(shipGroupItemAdjustment); } } } } itemIndex++; } } // set the item seq in the cart if (nextItemSeq > 0) { try { cart.setNextItemSeq(nextItemSeq + 1); } catch (GeneralException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } } if (includePromoItems) { for (String productPromoCode : orh.getProductPromoCodesEntered()) { cart.addProductPromoCode(productPromoCode, dispatcher); } for (GenericValue productPromoUse : orh.getProductPromoUse()) { cart.addProductPromoUse(productPromoUse.getString("productPromoId"), productPromoUse.getString("productPromoCodeId"), productPromoUse.getBigDecimal("totalDiscountAmount"), productPromoUse.getBigDecimal("quantityLeftInActions"), new HashMap<ShoppingCartItem, BigDecimal>()); } } List<GenericValue> adjustments = orh.getOrderHeaderAdjustments(); // If applyQuoteAdjustments is set to false then standard cart // adjustments are used. if (!adjustments.isEmpty()) { // The cart adjustments are added to the cart cart.getAdjustments().addAll(adjustments); } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("shoppingCart", cart); return result; }