public BigDecimal doBalance(
      ClaimPayPlan claimPayPlan, Long p2pPrepaidAccount, Investment investment, Long p2pPfAccount) {
    // 误差调整
    // 投资人利息罚息总和
    BigDecimal sumGatherInterest =
        claimGatherPlanRepository.sumInterestByInvSeqAndPeriod(
            claimPayPlan.getInvestmentSequence(), claimPayPlan.getClaimPayPlanNumber());
    // 借款人利息罚息总和
    BigDecimal sumPayInterest =
        claimPayPlan
            .getClaimPayPlanTotalAmount()
            .add(claimPayPlan.getClaimPayPlanJusticeInterest());

    BigDecimal pmFee = claimPayPlan.getClaimPayPlanPlatformManagementFee();
    BigDecimal balance = BigDecimal.ZERO;

    // 利息罚息尾数误差处理
    if (sumPayInterest.compareTo(sumGatherInterest) > 0) {
      balance = sumPayInterest.subtract(sumGatherInterest);
      pmFee = pmFee.add(balance);

      creBalanceOrder(claimPayPlan, investment, pmFee, p2pPrepaidAccount, p2pPfAccount);
    } else if (sumPayInterest.compareTo(sumGatherInterest) < 0) {
      balance = sumGatherInterest.subtract(sumPayInterest);
      pmFee = pmFee.subtract(balance);

      creBalanceOrder(claimPayPlan, investment, pmFee, p2pPfAccount, p2pPrepaidAccount);
    }
    return pmFee;
  }
  static Map<Long, BigDecimal> extract(
      BigDecimal amountToExtract, Map<Long, BigDecimal> mapToExtractFrom) {

    BigDecimal weightCollected = BigDecimal.ZERO;
    Map<Long, BigDecimal> result = new HashMap<>();

    BigDecimal availableWeightSum =
        mapToExtractFrom.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);

    for (Map.Entry<Long, BigDecimal> entry : mapToExtractFrom.entrySet()) {

      long receiptItemId = entry.getKey();
      BigDecimal weight = entry.getValue();

      if (weightCollected.compareTo(amountToExtract) == 0
          || availableWeightSum.compareTo(weightCollected) == 0) return result;

      // needed is LESS than receipt item available weight
      if (amountToExtract.compareTo(weight) < 0) {
        result.put(receiptItemId, amountToExtract);
        mapToExtractFrom.put(receiptItemId, weight.subtract(amountToExtract));
        return result;

      } else {
        // When needed weight is same or bigger than offered - taking it all
        result.put(receiptItemId, weight);
        mapToExtractFrom.put(receiptItemId, BigDecimal.ZERO);
        amountToExtract = amountToExtract.subtract(weight);
      }
    }

    return result;
  }
Exemple #3
0
  /**
   * Converter from a numeric object to Long. Input is checked to be within range represented by
   * Long.
   */
  static Long convertToLong(SessionInterface session, Object a) {

    if (a instanceof Integer) {
      return ValuePool.getLong(((Integer) a).intValue());
    } else if (a instanceof Long) {
      return (Long) a;
    } else if (a instanceof BigDecimal) {
      BigDecimal bd = (BigDecimal) a;

      if (bd.compareTo(MAX_LONG) > 0 || bd.compareTo(MIN_LONG) < 0) {
        throw Error.error(ErrorCode.X_22003);
      }

      return ValuePool.getLong(bd.longValue());
    } else if (a instanceof Double || a instanceof Float) {
      double d = ((Number) a).doubleValue();

      if (session instanceof Session) {
        if (!((Session) session).database.sqlConvertTruncate) {
          d = java.lang.Math.rint(d);
        }
      }

      if (Double.isInfinite(d)
          || Double.isNaN(d)
          || d >= (double) Long.MAX_VALUE + 1
          || d <= (double) Long.MIN_VALUE - 1) {
        throw Error.error(ErrorCode.X_22003);
      }

      return ValuePool.getLong((long) d);
    } else {
      throw Error.error(ErrorCode.X_42561);
    }
  }
  public BigDecimal calcDesconto() {
    BigDecimal descontoMax = new BigDecimal(0.92);
    BigDecimal descontoMin = new BigDecimal(0.95);
    BigDecimal limiMin = new BigDecimal(150);
    BigDecimal limiMax = new BigDecimal(200);
    BigDecimal descontoAplicado = BigDecimal.ONE;
    boolean aplicouDesconto = false;

    if (valCompra.compareTo(limiMax) >= 0) {
      descontoAplicado = descontoMax;
      aplicouDesconto = true;

    } else if (valCompra.compareTo(limiMin) >= 0) {
      descontoAplicado = descontoMin;
      aplicouDesconto = true;
    }

    if (aplicouDesconto) {
      valCompra = valCompra.multiply(descontoAplicado).setScale(2, BigDecimal.ROUND_CEILING);
      for (int i = 0; i < nRoupas; i++) {
        roupa[i].setValVenda(roupa[i].getPreco().multiply(descontoAplicado));
      }
    }

    return descontoAplicado /*.setScale(2,RoundingMode.DOWN)*/;
  }
  protected void convertNumberToInt() throws IOException, JsonParseException {
    // First, converting from long ought to be easy
    if ((_numTypesValid & NR_LONG) != 0) {
      // Let's verify it's lossless conversion by simple roundtrip
      int result = (int) _numberLong;
      if (((long) result) != _numberLong) {
        _reportError("Numeric value (" + getText() + ") out of range of int");
      }
      _numberInt = result;
    } else if ((_numTypesValid & NR_BIGINT) != 0) {
      // !!! Should check for range...
      _numberInt = _numberBigInt.intValue();
    } else if ((_numTypesValid & NR_DOUBLE) != 0) {
      // Need to check boundaries
      if (_numberDouble < MIN_INT_D || _numberDouble > MAX_INT_D) {
        reportOverflowInt();
      }
      _numberInt = (int) _numberDouble;
    } else if ((_numTypesValid & NR_BIGDECIMAL) != 0) {
      if (BD_MIN_INT.compareTo(_numberBigDecimal) > 0
          || BD_MAX_INT.compareTo(_numberBigDecimal) < 0) {
        reportOverflowInt();
      }
      _numberInt = _numberBigDecimal.intValue();
    } else {
      _throwInternal(); // should never get here
    }

    _numTypesValid |= NR_INT;
  }
  /**
   * Converter from a numeric object to Long. Input is checked to be within range represented by
   * Long.
   */
  static Long convertToLong(Object a) throws HsqlException {

    if (a instanceof Integer) {
      return ValuePool.getLong(((Integer) a).intValue());
    } else if (a instanceof Long) {
      return (Long) a;
    } else if (a instanceof BigDecimal) {
      BigDecimal bd = (BigDecimal) a;

      if (bd.compareTo(MAX_LONG) > 0 || bd.compareTo(MIN_LONG) < 0) {
        throw Error.error(ErrorCode.X_22003);
      }

      return ValuePool.getLong(bd.longValue());
    } else if (a instanceof Double || a instanceof Float) {
      double d = ((Number) a).doubleValue();

      if (Double.isInfinite(d)
          || Double.isNaN(d)
          || d >= (double) Long.MAX_VALUE + 1
          || d <= (double) Long.MIN_VALUE - 1) {
        throw Error.error(ErrorCode.X_22003);
      }

      return ValuePool.getLong((long) d);
    } else {
      throw Error.error(ErrorCode.X_42561);
    }
  }
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    BigDecimal oddSum = new BigDecimal("" + 0);
    BigDecimal oddMin = new BigDecimal("" + Integer.MAX_VALUE);
    BigDecimal oddMax = new BigDecimal("" + Integer.MIN_VALUE);

    BigDecimal evenSum = new BigDecimal("" + 0);
    BigDecimal evenMin = new BigDecimal("" + Integer.MAX_VALUE);
    BigDecimal evenMax = new BigDecimal("" + Integer.MIN_VALUE);

    String inputNumbers = input.nextLine();
    String[] numbersArray = inputNumbers.split(" ");

    input.close();

    if (inputNumbers.equals("")) {
      numbersArray = new String[0];
    }

    for (int i = 0; i < numbersArray.length; i++) {
      BigDecimal currentNumber = new BigDecimal("" + Double.parseDouble(numbersArray[i]));
      if (i % 2 == 0) {
        oddSum = oddSum.add(currentNumber);
        if (currentNumber.compareTo(oddMin) == -1) {
          oddMin = currentNumber;
        }
        if (currentNumber.compareTo(oddMax) == 1) {
          oddMax = currentNumber;
        }
      } else {
        evenSum = evenSum.add(currentNumber);

        if (currentNumber.compareTo(evenMin) == -1) {
          evenMin = currentNumber;
        }
        if (currentNumber.compareTo(evenMax) == 1) {
          evenMax = currentNumber;
        }
      }
    }
    DecimalFormat df = new DecimalFormat("##########.##");

    if (numbersArray.length > 1) {
      System.out.printf(
          "OddSum=%1$s, OddMin=%2$s, OddMax=%3$s" + " EvenSum=%4$s, EvenMin=%5$s, EvenMax=%6$s",
          df.format(oddSum),
          df.format(oddMin),
          df.format(oddMax),
          df.format(evenSum),
          df.format(evenMin),
          df.format(evenMax));
    } else if (numbersArray.length == 1) {
      System.out.printf(
          "OddSum=%1$.1s, OddMin=%2$.1s, OddMax=%3$.1s" + " EvenSum=No, EvenMin=No, EvenMax=No",
          oddSum, oddMin, oddMax);
    } else if (numbersArray.length == 0) {
      System.out.println("No");
    }
  }
 private BigDecimal getAmountFromClipboard() {
   String content = Utils.getClipboardString(GetSendingAmountActivity.this);
   if (content.length() == 0) {
     return null;
   }
   String number = content.toString().trim();
   if (_enterFiatAmount) {
     number = Utils.truncateAndConvertDecimalString(number, 2);
     if (number == null) {
       return null;
     }
     BigDecimal value = new BigDecimal(number);
     if (value.compareTo(BigDecimal.ZERO) < 1) {
       return null;
     }
     return value;
   } else {
     number =
         Utils.truncateAndConvertDecimalString(
             number, _mbwManager.getBitcoinDenomination().getDecimalPlaces());
     if (number == null) {
       return null;
     }
     BigDecimal value = new BigDecimal(number);
     if (value.compareTo(BigDecimal.ZERO) < 1) {
       return null;
     }
     return value;
   }
 }
  public static void assertEquals(
      final String message,
      final BigDecimal expected,
      final BigDecimal actual,
      final BigDecimal delta) {
    if (expected == actual) {
      return;
    }

    if (expected.compareTo(actual) == 0) {
      return;
    }

    final BigDecimal deltaActual = expected.subtract(actual).abs();
    if (deltaActual.compareTo(delta) <= 0) {
      return;
    }

    Assert.fail(
        (message == null ? "" : message)
            + "\nExpected=<"
            + expected
            + ">"
            + "\nActual=<"
            + actual
            + ">"
            + "\nDelta=<"
            + delta
            + ">");
  }
Exemple #10
0
 /**
  *
  * <pre>
  * 方法体说明:结算限额判断
  * 作者:andy
  * 日期: 2013-11-25 下午14:18:21
  * @param map
  * @param mcDefiniTionName
  * @return:是则返回true,否则false
  * </pre>
  */
 private boolean isBalanceAccount(Map<?, ?> map, String mcDefiniTionName) {
   double balanceAccount = 0; // 结算限额
   ContractWorkflowInfo info = new ContractWorkflowInfo();
   String bizCode = (String) map.get(BPMSConstant.BIZCODE); // 流程实例ID
   String currentActivityDefId = map.get(BPMSConstant.CURRENT_ACTIVITY_DEF_ID).toString(); // 当前节点
   String nextActivityDefId = map.get(BPMSConstant.NEXT_ACTIVITY_DEF_ID).toString(); // 下一节点
   WebApplicationContext wac = WebApplicationContextHolder.getWebApplicationContext();
   IContractWorkflowManager contractWorkflowManager =
       (IContractWorkflowManager) wac.getBean("contractWorkflowManager");
   IAmountConfigService amountConfigService =
       (IAmountConfigService) wac.getBean("bpsAmountConfigService");
   info = contractWorkflowManager.findContractWorkflowInfoByWorkNo(bizCode, mcDefiniTionName);
   balanceAccount = Double.valueOf(info.getBalanceAccount());
   if (BpsConstant.EX_UPDATE_PROCESSNAME.equals(mcDefiniTionName)
       || BpsConstant.LTT_UPDATE_PROCESSNAME.equals(mcDefiniTionName)) {
     balanceAccount = Double.valueOf(info.getNewBalanceAccount());
   }
   BigDecimal amount = new BigDecimal(balanceAccount);
   AmountConfigEntity amountConfigEntity = new AmountConfigEntity();
   amountConfigEntity.setCurrentApproStepNo(currentActivityDefId);
   amountConfigEntity.setTargetApproStepNo(nextActivityDefId);
   amountConfigEntity.setMcDefiniTionName(mcDefiniTionName);
   AmountConfigEntity entity = amountConfigService.queryForBranch(amountConfigEntity);
   if (entity != null) {
     BigDecimal minAmount = entity.getMinAmount();
     BigDecimal maxAmount = entity.getMaxAmount();
     if (amount.compareTo(minAmount) > 0 && amount.compareTo(maxAmount) <= 0) {
       return true;
     }
   }
   return false;
 }
 @Override
 public boolean contains(BigDecimal value) {
   if (value == null || value.compareTo(from) < 0 || value.compareTo(to) >= 0) {
     return false;
   }
   return value.subtract(from).remainder(incrementUnit).compareTo(BigDecimal.ZERO) == 0;
 }
  public String priceBeco(
      Ctx ctx, int WindowNo, GridTab mTab, GridField mField, Object value, Object oldValue) {
    System.out.println("pricebeco ... ");
    try {
      BigDecimal precio = (BigDecimal) mField.getValue();

      String priceRuleSQL =
          "select xx_lowrank,xx_highrank,xx_termination,xx_increase,xx_infinitevalue from xx_vme_pricerule order by (xx_lowrank)";
      PreparedStatement priceRulePstmt = DB.prepareStatement(priceRuleSQL, null);
      ResultSet priceRuleRs = priceRulePstmt.executeQuery();

      Integer precioInt = precio.intValue();
      BigDecimal precioBig = new BigDecimal(precioInt);
      while (priceRuleRs.next()) {
        if (precioBig.compareTo(priceRuleRs.getBigDecimal("xx_lowrank")) >= 0
            && precioBig.compareTo(priceRuleRs.getBigDecimal("xx_highrank")) <= 0) {
          Integer incremento = priceRuleRs.getInt("xx_increase");

          for (Integer i = priceRuleRs.getInt("xx_lowrank") - 1;
              i <= priceRuleRs.getInt("xx_highrank");
              i = i + incremento) {
            BigDecimal var = new BigDecimal(i);

            if (precioBig.compareTo(var) <= 0) {
              BigDecimal beco = var;

              BigDecimal terminacion = priceRuleRs.getBigDecimal("xx_termination");
              if (terminacion.intValue() == 0) {
                beco = var.add(terminacion);
              } else {
                var = var.divide(new BigDecimal(10));
                Integer aux = var.intValue() * 10;
                beco = new BigDecimal(aux).add(terminacion);
              }
              // mTab.setValue("PriceList", beco);
              priceRuleRs.close();
              priceRulePstmt.close();

              if (beco.compareTo(precio) == 0) {
                return priceBandBeco(ctx, WindowNo, mTab, mField, value, oldValue);
                // return"";
              } else {
                mTab.setValue("PriceList", beco);
                return "";
                // return "Precio Beco Sugerido "+beco.toString();
              }
            }
          }
        }
      }
      priceRuleRs.close();
      priceRulePstmt.close();

      return priceBandBeco(ctx, WindowNo, mTab, mField, value, oldValue);
      // return "";
    } catch (Exception e) {
      return e.getMessage();
    }
  }
Exemple #13
0
  /**
   * Converter from a numeric object to Integer. Input is checked to be within range represented by
   * the given number type.
   */
  static Integer convertToInt(SessionInterface session, Object a, int type) {

    int value;

    if (a instanceof Integer) {
      if (type == Types.SQL_INTEGER) {
        return (Integer) a;
      }

      value = ((Integer) a).intValue();
    } else if (a instanceof Long) {
      long temp = ((Long) a).longValue();

      if (Integer.MAX_VALUE < temp || temp < Integer.MIN_VALUE) {
        throw Error.error(ErrorCode.X_22003);
      }

      value = (int) temp;
    } else if (a instanceof BigDecimal) {
      BigDecimal bd = ((BigDecimal) a);

      if (bd.compareTo(MAX_INT) > 0 || bd.compareTo(MIN_INT) < 0) {
        throw Error.error(ErrorCode.X_22003);
      }

      value = bd.intValue();
    } else if (a instanceof Double || a instanceof Float) {
      double d = ((Number) a).doubleValue();

      if (session instanceof Session) {
        if (!((Session) session).database.sqlConvertTruncate) {
          d = java.lang.Math.rint(d);
        }
      }

      if (Double.isInfinite(d)
          || Double.isNaN(d)
          || d >= (double) Integer.MAX_VALUE + 1
          || d <= (double) Integer.MIN_VALUE - 1) {
        throw Error.error(ErrorCode.X_22003);
      }

      value = (int) d;
    } else {
      throw Error.error(ErrorCode.X_42561);
    }

    if (type == Types.TINYINT) {
      if (Byte.MAX_VALUE < value || value < Byte.MIN_VALUE) {
        throw Error.error(ErrorCode.X_22003);
      }
    } else if (type == Types.SQL_SMALLINT) {
      if (Short.MAX_VALUE < value || value < Short.MIN_VALUE) {
        throw Error.error(ErrorCode.X_22003);
      }
    }

    return Integer.valueOf(value);
  }
Exemple #14
0
  @Override
  public boolean equals(final Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    if (!super.equals(o)) {
      return false;
    }

    final DefaultPayment that = (DefaultPayment) o;

    if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
      return false;
    }
    if (authAmount != null ? authAmount.compareTo(that.authAmount) != 0 : that.authAmount != null) {
      return false;
    }
    if (captureAmount != null
        ? captureAmount.compareTo(that.captureAmount) != 0
        : that.captureAmount != null) {
      return false;
    }
    if (purchasedAmount != null
        ? purchasedAmount.compareTo(that.purchasedAmount) != 0
        : that.purchasedAmount != null) {
      return false;
    }
    if (currency != that.currency) {
      return false;
    }
    if (externalKey != null ? !externalKey.equals(that.externalKey) : that.externalKey != null) {
      return false;
    }
    if (paymentMethodId != null
        ? !paymentMethodId.equals(that.paymentMethodId)
        : that.paymentMethodId != null) {
      return false;
    }
    if (paymentNumber != null
        ? !paymentNumber.equals(that.paymentNumber)
        : that.paymentNumber != null) {
      return false;
    }
    if (refundAmount != null
        ? refundAmount.compareTo(that.refundAmount) != 0
        : that.refundAmount != null) {
      return false;
    }
    if (transactions != null
        ? !transactions.equals(that.transactions)
        : that.transactions != null) {
      return false;
    }

    return true;
  }
  /**
   * Método do 2º step-method
   *
   * @param valorFaturamento
   * @param motivo
   * @param usuario
   * @return o faturamento do prestador a ser salvo
   * @throws ValidateException
   */
  public AbstractFaturamento criarFaturamentoComAlteracao(
      AbstractFaturamento faturamento,
      BigDecimal valorFaturamentoAcres,
      BigDecimal valorFaturamentoDecres,
      String motivo,
      UsuarioInterface usuario)
      throws ValidateException {
    AlteracaoFaturamento alteracao = new AlteracaoFaturamento();
    if (valorFaturamentoAcres == null) {
      valorFaturamentoAcres = BigDecimal.ZERO;
    }

    if (valorFaturamentoDecres == null) {
      valorFaturamentoDecres = BigDecimal.ZERO;
    }

    if (valorFaturamentoAcres.compareTo(BigDecimal.ZERO) == 0
        && valorFaturamentoDecres.compareTo(BigDecimal.ZERO) == 0) {
      throw new RuntimeException("Caro usuário informe um valor.");
    }

    alteracao.setValorIncremento(valorFaturamentoAcres);
    alteracao.setValorDecremento(valorFaturamentoDecres);
    alteracao.setStatus(AlteracaoFaturamento.STATUS_ATIVO);
    alteracao.setData(new Date());
    alteracao.setMotivo(motivo);
    alteracao.setUsuario(usuario);

    if (faturamento == null) {
      if (tipo == FATURAMENTO_NORMAL) faturamento = new Faturamento();
      else faturamento = new FaturamentoPassivo();
      faturamento.setValorBruto(BigDecimal.ZERO);
      faturamento.setValorLiquido(BigDecimal.ZERO);
      faturamento.setPrestador(prestador);
      faturamento.setNome(prestador.getPessoaJuridica().getFantasia());
      faturamento.setInformacaoFinanceira(prestador.getInformacaoFinanceira());
      faturamento.setCategoria(prestador.getTipoPrestador());
      faturamento.setGeradoPosteriormente(true);
      faturamento.setMotivoGeracaoPosterior(motivo);
      faturamento.setDataGeracao(new Date());
      faturamento.setCompetencia(Utils.gerarCompetencia(competencia));
      alteracao.setFaturamento(faturamento);
      faturamento.getAlteracoesFaturamento().add(alteracao);
    } else {
      alteracao.setFaturamento(faturamento);
      faturamento.getAlteracoesFaturamento().add(alteracao);
    }

    faturamento.setValorBruto(faturamento.getValorBruto().add(alteracao.getSaldo()));

    if (faturamento.getValorBruto().compareTo(BigDecimal.ZERO) < 0) {
      throw new RuntimeException(
          "Caro usuario, o saldo das alterações não pode deixar o valor do faturamento zerado.");
    }

    faturamento.getGuiasFaturaveis().size();

    return faturamento;
  }
  public static List<Map<String, BigDecimal>> getPackageSplit(
      DispatchContext dctx, List<Map<String, Object>> shippableItemInfo, BigDecimal maxWeight) {
    // create the package list w/ the first package
    List<Map<String, BigDecimal>> packages = FastList.newInstance();

    if (UtilValidate.isNotEmpty(shippableItemInfo)) {
      for (Map<String, Object> itemInfo : shippableItemInfo) {
        long pieces = ((Long) itemInfo.get("piecesIncluded")).longValue();
        BigDecimal totalQuantity = (BigDecimal) itemInfo.get("quantity");
        BigDecimal totalWeight = (BigDecimal) itemInfo.get("weight");
        String productId = (String) itemInfo.get("productId");

        // sanity check
        if (pieces < 1) {
          pieces = 1; // can NEVER be less than one
        }
        BigDecimal weight = totalWeight.divide(BigDecimal.valueOf(pieces), generalRounding);
        for (int z = 1; z <= totalQuantity.intValue(); z++) {
          BigDecimal partialQty =
              pieces > 1
                  ? BigDecimal.ONE.divide(BigDecimal.valueOf(pieces), generalRounding)
                  : BigDecimal.ONE;
          for (long x = 0; x < pieces; x++) {
            if (weight.compareTo(maxWeight) >= 0) {
              Map<String, BigDecimal> newPackage = FastMap.newInstance();
              newPackage.put(productId, partialQty);
              packages.add(newPackage);
            } else if (totalWeight.compareTo(BigDecimal.ZERO) > 0) {
              // create the first package
              if (packages.size() == 0) {
                packages.add(FastMap.<String, BigDecimal>newInstance());
              }

              // package loop
              boolean addedToPackage = false;
              for (Map<String, BigDecimal> packageMap : packages) {
                if (!addedToPackage) {
                  BigDecimal packageWeight =
                      calcPackageWeight(dctx, packageMap, shippableItemInfo, weight);
                  if (packageWeight.compareTo(maxWeight) <= 0) {
                    BigDecimal qty = packageMap.get(productId);
                    qty = UtilValidate.isEmpty(qty) ? BigDecimal.ZERO : qty;
                    packageMap.put(productId, qty.add(partialQty));
                    addedToPackage = true;
                  }
                }
              }
              if (!addedToPackage) {
                Map<String, BigDecimal> packageMap = FastMap.newInstance();
                packageMap.put(productId, partialQty);
                packages.add(packageMap);
              }
            }
          }
        }
      }
    }
    return packages;
  }
  /** 检查是否超额 */
  public Integer ckeckOverflow(String departmentId, String fee) throws Exception {
    Integer result = 0;
    Calendar calendar = Calendar.getInstance();
    Integer month = calendar.get(Calendar.MONTH) + 1;
    Integer year = calendar.get(Calendar.YEAR);
    BigDecimal balance = BigDecimal.ZERO;
    BigDecimal money = BigDecimal.valueOf(Double.parseDouble(fee));

    // 查询记录
    HashMap<String, String> info = getOutlayByDeptIdAndYear(year, departmentId);

    // 是否进行超额检查
    if (info != null) {
      String overFlowCheck = info.get("OverFlowCheck");
      if ("01".equals(overFlowCheck)) {
        switch (month) {
          case 1:
          case 2:
          case 3:
            balance = BigDecimal.valueOf(Double.parseDouble(info.get("QuarterOneBalance")));
            if (money.compareTo(balance) > 0) {
              result = 1;
            }
            break;
          case 4:
          case 5:
          case 6:
            balance = BigDecimal.valueOf(Double.parseDouble(info.get("QuarterTwoBalance")));
            if (money.compareTo(balance) > 0) {
              result = 1;
            }
            break;
          case 7:
          case 8:
          case 9:
            balance = BigDecimal.valueOf(Double.parseDouble(info.get("QuarterThreeBalance")));
            if (money.compareTo(balance) > 0) {
              result = 1;
            }
            break;
          case 10:
          case 11:
          case 12:
            balance = BigDecimal.valueOf(Double.parseDouble(info.get("QuarterFourBalance")));
            if (money.compareTo(balance) > 0) {
              result = 1;
            }
            break;
          default:
            break;
        }
      }
    } else {
      result = -2;
    }

    return result;
  }
  /** @return */
  @Action(value = "/collectPropertyTax-generateBill")
  public String generateBill() {
    if (LOGGER.isDebugEnabled())
      LOGGER.debug(
          "Entered method generatePropertyTaxBill, Generating bill for index no : " + propertyId);
    if (propertyId == null || propertyId.isEmpty()) {
      setErrorMsg(getText("mandatory.assessmentNo"));
      return RESULT_ERROR;
    }
    final BasicProperty basicProperty =
        basicPropertyService.findByNamedQuery(
            PropertyTaxConstants.QUERY_BASICPROPERTY_BY_UPICNO, propertyId);
    if (basicProperty == null) {
      setErrorMsg(getText("validation.property.doesnot.exists"));
      return RESULT_ERROR;
    }
    if (LOGGER.isDebugEnabled())
      LOGGER.debug("generatePropertyTaxBill : BasicProperty :" + basicProperty);

    if (basicProperty.getProperty().getIsExemptedFromTax()) {
      args.add(propertyId);
      setErrorMsg(getText("msg.collection.tax.exempted", args));
      return RESULT_ERROR;
    }

    final Map<String, BigDecimal> demandCollMap =
        propertyTaxUtil.getDemandAndCollection(basicProperty.getProperty());
    final BigDecimal currDue =
        demandCollMap.get(CURR_DMD_STR).subtract(demandCollMap.get(CURR_COLL_STR));
    final BigDecimal arrDue =
        demandCollMap.get(ARR_DMD_STR).subtract(demandCollMap.get(ARR_COLL_STR));

    if (currDue.compareTo(BigDecimal.ZERO) <= 0 && arrDue.compareTo(BigDecimal.ZERO) <= 0) {
      args.add(propertyId);
      isAssessmentNoValid = Boolean.TRUE;
      setErrorMsg(getText("msg.collection.fully.paid", args));
      return RESULT_ERROR;
    }
    propertyTaxBillable.setLevyPenalty(true);
    propertyTaxBillable.setBasicProperty(basicProperty);
    propertyTaxBillable.setUserId(Long.valueOf(getSession().get("userid").toString()));
    propertyTaxBillable.setReferenceNumber(
        propertyTaxNumberGenerator.generateBillNumber(
            basicProperty.getPropertyID().getWard().getBoundaryNum().toString()));
    propertyTaxBillable.setBillType(propertyTaxUtil.getBillTypeByCode(BILLTYPE_AUTO));

    final String billXml = ptBillServiceImpl.getBillXML(propertyTaxBillable);
    try {
      collectXML = URLEncoder.encode(billXml, "UTF-8");
    } catch (final UnsupportedEncodingException e) {
      throw new RuntimeException(e.getMessage());
    }
    if (LOGGER.isDebugEnabled())
      LOGGER.debug(
          "Exiting method generatePropertyTaxBill, collectXML (before decode): " + billXml);
    return RESULT_VIEW;
  }
 private void updateEleavtion(GPXTrackPoint point) {
   BigDecimal elevation = point.getElevation();
   if (elevation.compareTo(minElevation) < 0) {
     minElevation = elevation;
   }
   if (elevation.compareTo(maxElevation) > 0) {
     maxElevation = elevation;
   }
 }
 /**
  * {@link ProjectStatusReportDTO#costMark} will be <code>!</code> if {@link
  * ProjectStatusReportDTO#totalCost} is bigger than {@link ProjectStatusReportDTO#budget}. If
  * {@link ProjectStatusReportDTO#budget} is zero then the mark will be empty.
  */
 private void calculateCostMark() {
   if (totalCost != null) {
     if (expensesBudget != null && (expensesBudget.compareTo(BigDecimal.ZERO) > 0)) {
       if (totalCost.compareTo(expensesBudget) > 0) {
         costMark = EXCLAMATION_MARK;
       }
     }
   }
 }
Exemple #21
0
  /**
   * Sums up the volume and weight of all items still unpacked, selects a bin from <code>availBins
   * </code> and updates <code>model</code> accordingly.
   *
   * <p>If there is no bin large enough for the summed up weight and volume, the largest bin
   * available is added.
   *
   * @param unallocNodes
   * @param availBins
   * @param usedBins
   * @param model
   * @param trxName
   */
  private void addBinForUsage(
      final Properties ctx,
      final List<DefaultMutableTreeNode> unallocNodes,
      final List<DefaultMutableTreeNode> availBins,
      final List<DefaultMutableTreeNode> usedBins,
      final PackingTreeModel model,
      final String trxName) {

    logger.debug("Computing the overall volume and weight we still need to cover");

    BigDecimal unallocVolumeSum = BigDecimal.ZERO;
    BigDecimal unallocWeightSum = BigDecimal.ZERO;
    BigDecimal unallocVolumeMax = BigDecimal.ZERO;
    BigDecimal unallocWeightMax = BigDecimal.ZERO;

    for (final DefaultMutableTreeNode currentNode : unallocNodes) {

      final LegacyPackingItem pi = getPI(currentNode);
      final BigDecimal volSingle = pi.retrieveVolumeSingle(trxName);
      final BigDecimal weightSingle = pi.retrieveWeightSingle(trxName);
      unallocVolumeSum = unallocVolumeSum.add(pi.getQtySum().multiply(volSingle));
      unallocWeightSum = unallocWeightSum.add(pi.getQtySum().multiply(weightSingle));

      if (unallocVolumeMax.compareTo(volSingle) < 0) {
        unallocVolumeMax = volSingle;
      }
      if (unallocWeightMax.compareTo(weightSingle) < 0) {
        unallocWeightMax = weightSingle;
      }
    }
    logger.debug(
        "Still required: volume-sum="
            + unallocVolumeSum
            + "; volume-max="
            + unallocVolumeMax
            + "; weight-sum:"
            + unallocWeightSum
            + "; weight-max="
            + unallocWeightMax);

    removeUnavailableBins(availBins, unallocVolumeMax, unallocWeightMax);

    final DefaultMutableTreeNode nexBinToUseNode =
        findBinNode(availBins, unallocVolumeSum, unallocWeightSum);
    final AvailableBins foundBin = getBin(nexBinToUseNode);

    foundBin.setQtyAvail(foundBin.getQtyAvail() - 1);

    final I_M_PackagingContainer foundPC = foundBin.getPc();

    final UsedBin newPack = new UsedBin(ctx, foundPC, trxName);
    logger.info("Adding " + newPack);

    final DefaultMutableTreeNode newPackNode = new DefaultMutableTreeNode(newPack);
    usedBins.add(newPackNode);
    model.insertNodeInto(newPackNode, model.getUsedBins(), model.getUsedBins().getChildCount());
  }
  public DCharts createChart(
      List<FuelSpendMonthlyCostBean> fuelSpendMonthlyCostBeanList, BigDecimal grandTotal) {
    // Deciding Ticks e.g. .5, 1, 1.5, 2, 2.5 ... etc
    String label = "Total Fuel Spend";
    String grandTotalAmount = df.format(Double.parseDouble(grandTotal.toString()));
    title =
        "Total Fuel Spend for the last "
            + fuelSpendMonthlyCostBeanList.size()
            + " Month(s):     R"
            + grandTotalAmount;
    float tickInterval = Float.parseFloat("350000");
    Object minTickValue = 0;
    BigDecimal highestTotal = BigDecimal.ZERO;
    for (FuelSpendMonthlyCostBean FuelSpendMonthlyCostBean : fuelSpendMonthlyCostBeanList) {
      if (FuelSpendMonthlyCostBean.getMonthlyAmountSpend().compareTo(highestTotal) > 0) {
        highestTotal = FuelSpendMonthlyCostBean.getMonthlyAmountSpend();
      }
    }

    if (highestTotal.compareTo(new BigDecimal("350000")) < 0) {
      tickInterval = Float.parseFloat("50000");
      //            minTickValue=5000;
    } else if (highestTotal.compareTo(new BigDecimal("600000")) < 0) {
      tickInterval = Float.parseFloat("100000");
      //             minTickValue=10000;
    }

    List<Object> totalList = new ArrayList<>();
    List<Object> monthList = new ArrayList<>();

    // Get Objects of Data
    for (FuelSpendMonthlyCostBean fuelSpendMonthlyCostBean : fuelSpendMonthlyCostBeanList) {
      totalList.add(fuelSpendMonthlyCostBean.getMonthlyAmountSpend());
      // Truncate the Names
      monthList.add(fuelSpendMonthlyCostBean.getMonth());
    }
    Object[] totalListArray = totalList.toArray(new Object[totalList.size()]);
    Object[] monthListArray = monthList.toArray(new Object[monthList.size()]);

    final BarChart barChart = new BarChart();
    DCharts dBarChart =
        barChart.buildBarChart(
            totalListArray, monthListArray, tickInterval, label, minTickValue, title);
    dBarChart.setWidth("600px");
    dBarChart.setHeight("300px");
    dBarChart.show();

    // USEFUL Statement
    //        dBarChart.setMarginBottom(10);
    //        dBarChart.setMarginLeft(10);
    //        dBarChart.setMarginRight(10);
    //        dBarChart.setMarginTop(-3);
    //        dBarChart.getOptions().setTitle("");

    return dBarChart;
  }
Exemple #23
0
 private static void _checkConvertibility(@Nonnull final BigDecimal aSize) {
   if (aSize.compareTo(CGlobal.BIGDEC_MAX_LONG) > 0)
     throw new IllegalArgumentException(
         "The passed BigDecimal is too large to be converted into a long value: "
             + aSize.toString());
   if (aSize.compareTo(CGlobal.BIGDEC_MIN_LONG) < 0)
     throw new IllegalArgumentException(
         "The passed BigDecimal is too small to be converted into a long value: "
             + aSize.toString());
 }
Exemple #24
0
 /**
  * return true iff this point [x,y] coordinates are the same as obj [x,y] coordinates. (the z
  * value is ignored).
  */
 @Override
 public boolean equals(Object obj) {
   if (this == obj) return true;
   if (obj == null) return false;
   if (getClass() != obj.getClass()) return false;
   Point_tp other = (Point_tp) obj;
   if (_x.compareTo(other._x) != 0) return false;
   if (_y.compareTo(other._y) != 0) return false;
   return true;
 }
  /**
   * Ver onde sao guardados os StudentInquiries (QUC): ir por CurricularCourses
   *
   * <p>1. Extrair o ED 2. A partir do ED extrair duas collections: CourseResults e TeacherResults
   * 3. Magia para tirar um score desses results (ainda nao sei o q possa ser esse score. vou
   * extrair o 'average_NDE' e 'average_P6_1' apenas a titulo de exemplo. nao tem qq valor real. os
   * values sao em double, passar a BigDecimals e trabalhar sempre neste format). 4. Aplicar 50% à
   * media do score de todos os CourseResults e 50% à media do score de todos os TeacherResults 5.
   * Mostrar esse score.
   */
  private String generateQUCResults(YearViewBean bean) {
    ExecutionDegree executionDegree =
        ExecutionDegree.getByDegreeCurricularPlanAndExecutionYear(
            bean.getDegreeCurricularPlan(), bean.getExecutionYear());

    Set<StudentInquiriesCourseResult> courseResults =
        executionDegree.getStudentInquiriesCourseResultsSet();
    Set<StudentInquiriesTeachingResult> teachingResults =
        executionDegree.getStudentInquiriesTeachingResultsSet();

    BigDecimal sigmaCR = new BigDecimal(0);
    BigDecimal cardinalityCR = new BigDecimal(0);
    BigDecimal averageCR = new BigDecimal(0);

    BigDecimal sigmaTR = new BigDecimal(0);
    BigDecimal cardinalityTR = new BigDecimal(0);
    BigDecimal averageTR = new BigDecimal(0);

    BigDecimal partialCourse = new BigDecimal(0);
    BigDecimal partialTeaching = new BigDecimal(0);

    String result;

    for (StudentInquiriesCourseResult courseResult : courseResults) {
      BigDecimal converted =
          new BigDecimal(courseResult.getAverage_NDE() != null ? courseResult.getAverage_NDE() : 0);
      sigmaCR = sigmaCR.add(converted);
      cardinalityCR = cardinalityCR.add(BigDecimal.ONE);
    }
    if (cardinalityCR.compareTo(BigDecimal.ZERO) != 0) {
      averageCR = sigmaCR.divide(cardinalityCR, 4, RoundingMode.HALF_EVEN);
    } else {
      averageCR = BigDecimal.ZERO;
    }

    for (StudentInquiriesTeachingResult teachingResult : teachingResults) {
      BigDecimal converted =
          new BigDecimal(
              teachingResult.getAverage_P6_1() != null ? teachingResult.getAverage_P6_1() : 0);
      sigmaTR = sigmaTR.add(converted);
      cardinalityTR = cardinalityTR.add(BigDecimal.ONE);
    }
    if (cardinalityCR.compareTo(BigDecimal.ZERO) != 0) {
      averageTR = sigmaTR.divide(cardinalityTR, 4, RoundingMode.HALF_EVEN);
    } else {
      averageTR = BigDecimal.ZERO;
    }

    partialCourse = averageCR.divide(new BigDecimal(2), 2, RoundingMode.HALF_EVEN);
    partialTeaching = averageTR.divide(new BigDecimal(2), 2, RoundingMode.HALF_EVEN);

    result = partialCourse.add(partialTeaching).toPlainString();

    return result;
  }
 public long getLong() throws SQLException {
   truncated_ = 0;
   outOfBounds_ = false;
   if (value_.compareTo(LONG_MAX_VALUE) > 0 || value_.compareTo(LONG_MIN_VALUE) < 0) {
     // we don't count the fractional part of the number as truncation
     int length = value_.toBigInteger().toByteArray().length;
     truncated_ = length - 8;
     outOfBounds_ = true;
   }
   return value_.longValue();
 }
 public short getShort() throws SQLException {
   truncated_ = 0;
   outOfBounds_ = false;
   if (value_.compareTo(SHORT_MAX_VALUE) > 0 || value_.compareTo(SHORT_MIN_VALUE) < 0) {
     // we don't count the fractional part of the number as truncation
     int length = value_.toBigInteger().toByteArray().length;
     truncated_ = length - 2;
     outOfBounds_ = true;
   }
   return (short) value_.shortValue();
 }
Exemple #28
0
  public int compareTo(double p) {
    BigDecimal point = BigDecimal.valueOf(p);
    if (upper_.compareTo(point) < 0) return -1;
    if (lower_.compareTo(point) > 0) return 1;
    //        if( this.upper_ < p )
    //            return -1;
    //        if( this.lower_ > p )
    //            return 1;

    return 0;
  }
  public void verificar(ActionEvent actionEvent) {
    actualizarValores();
    if (totalDebe.equals(totalHaber)
        && totalDebe.compareTo(BigDecimal.ZERO) > 0
        && totalHaber.compareTo(BigDecimal.ZERO) > 0) {
      List<Transaccion> transacciones = beanAsiento.getTransacciones();
      List<Transaccion> tSalida = new ArrayList<>();

      for (Transaccion t : transacciones) {
        if (t.getIdcodcuenta() != null
            && (t.getDebe() != BigDecimal.ZERO || t.getHaber() != BigDecimal.ZERO)) {
          tSalida.add(t);
        }
      }

      BigDecimal tdebe = BigDecimal.ZERO;
      BigDecimal thaber = BigDecimal.ZERO;

      for (Transaccion tSalida1 : tSalida) {
        tdebe = tdebe.add(tSalida1.getDebe().setScale(2, BigDecimal.ROUND_HALF_UP));
        thaber = thaber.add(tSalida1.getHaber().setScale(2, BigDecimal.ROUND_HALF_UP));
      }
      //
      if (thaber.equals(tdebe)) {
        List<Asiento> asientosAux = asientoFacade.findAll();
        int numAsiento = asientosAux.size() + 1;

        Asiento asientoAux = new Asiento();
        asientoAux.setIdcodasiento(numAsiento);
        asientoAux.setNumasiento(numAsiento);
        asientoAux.setNumdiario(beanAsiento.getNumDiario());
        asientoAux.setPeriodo(beanAsiento.getPeriodo());
        asientoAux.setFecha(beanAsiento.getFecha());
        asientoAux.setDebe(tdebe);
        asientoAux.setHaber(thaber);
        asientoAux.setConcepto(beanAsiento.getConcepto());
        asientoAux.setDocumento(beanAsiento.getDocumento());

        for (Transaccion t : tSalida) {
          t.setIdcodasiento(asientoAux);
          // transaccionFacade.create(t);
        }
        asientoAux.setTransaccionList(tSalida);
        asientoFacade.create(asientoAux);

        asientos = asientoFacade.findAll();
        JsfUtil.addSuccessMessage("Ahora puede Finalizar");
      } else {
        JsfUtil.addErrorMessage("Verifique los valores");
      }
    } else {
      JsfUtil.addErrorMessage("Verifique los valores");
    }
  }
 public BigDecimal getValor() {
   BigDecimal multiplicante = MoneyCalculation.divide(new BigDecimal(aliquota), 100f);
   multiplicante.setScale(2, BigDecimal.ROUND_HALF_UP);
   BigDecimal valorCalculado = multiplicante.multiply(this.getValorBaseCalculo());
   if (valorCalculado.compareTo(valorDescontoMinimo) < 0) {
     valorCalculado = BigDecimal.ZERO;
   } else if (valorCalculado.compareTo(valorDescontoMaximo) > 0) {
     valorCalculado = valorDescontoMaximo;
   }
   return MoneyCalculation.rounded(valorCalculado);
 }