private Money calculateCurrentValue(List<AssetClass> allocations) {
    Money result = MoneyFactory.fromDouble(0);

    for (AssetClass ac : allocations) {
      Money itemValue;

      ItemType type = ac.getType();
      switch (type) {
        case Group:
          // Group. Calculate for children.
          itemValue = calculateCurrentValue(ac.getChildren());
          break;

        case Allocation:
          // Allocation. get value of all stocks.
          itemValue = sumStockValues(ac.getStocks());
          break;

        case Cash:
          itemValue = ac.getValue();
          break;

        default:
          ExceptionHandler handler = new ExceptionHandler(getContext());
          handler.showMessage("encountered an item with no type set!");
          itemValue = MoneyFactory.fromDouble(0);
          break;
      }

      ac.setCurrentValue(itemValue);
      result = result.add(itemValue);
    }

    return result;
  }
  /**
   * Add Cash as a separate, automatic asset class that uses all the cash amounts from the
   * investment accounts.
   *
   * @param assetAllocation Main asset allocation object.
   */
  private void addCash(AssetClass assetAllocation) {
    // get all investment accounts, their currencies and cash balances.
    AccountRepository repo = new AccountRepository(getContext());
    AccountService accountService = new AccountService(getContext());
    List<String> investmentAccounts = new ArrayList<>();
    investmentAccounts.add(AccountTypes.INVESTMENT.toString());
    CurrencyService currencyService = new CurrencyService(getContext());
    int destinationCurrency = currencyService.getBaseCurrencyId();
    Money zero = MoneyFactory.fromDouble(0);

    List<Account> accounts = accountService.loadAccounts(false, false, investmentAccounts);

    Money sum = MoneyFactory.fromDouble(0);

    // Get the balances in base currency.
    for (Account account : accounts) {
      int sourceCurrency = account.getCurrencyId();
      Money amountInBase =
          currencyService.doCurrencyExchange(
              destinationCurrency, account.getInitialBalance(), sourceCurrency);
      sum = sum.add(amountInBase);
    }

    // add the cash asset class
    // todo: the allocation needs to be editable!
    AssetClass cash = AssetClass.create(getContext().getString(R.string.cash));
    cash.setType(ItemType.Cash);
    cash.setAllocation(zero);
    cash.setCurrentAllocation(zero);
    cash.setDifference(zero);
    cash.setValue(sum);

    assetAllocation.addChild(cash);
  }
  public static MatrixCursorColumns fromCursor(Context context, Cursor cursor) {
    MatrixCursorColumns values = new MatrixCursorColumns();
    FormatUtilities format = new FormatUtilities(context);
    String display;
    Money value;

    values.id = (int) cursor.getLong(cursor.getColumnIndex(MatrixCursorColumns.ID));
    values.name = cursor.getString(cursor.getColumnIndex(MatrixCursorColumns.NAME));
    values.allocation = cursor.getString(cursor.getColumnIndex(MatrixCursorColumns.ALLOCATION));

    String valueString = cursor.getString(cursor.getColumnIndex(MatrixCursorColumns.VALUE));
    if (!TextUtils.isEmpty(valueString)) {
      value = MoneyFactory.fromString(valueString);
      display = format.getValueFormattedInBaseCurrency(value);
    } else {
      display = "";
    }
    values.value = display;

    values.currentAllocation =
        cursor.getString(cursor.getColumnIndex(MatrixCursorColumns.CURRENT_ALLOCATION));

    valueString = cursor.getString(cursor.getColumnIndex(MatrixCursorColumns.CURRENT_VALUE));
    if (!TextUtils.isEmpty(valueString)) {
      value = MoneyFactory.fromString(valueString);
      display = format.getValueFormattedInBaseCurrency(value);
    } else {
      display = "";
    }
    values.currentValue = display;

    // difference %
    valueString = cursor.getString(cursor.getColumnIndex(MatrixCursorColumns.DIFFERENCE_PERCENT));
    if (!TextUtils.isEmpty(valueString)) {
      // value = MoneyFactory.fromString(valueString);
      display = valueString;
    } else {
      display = "";
    }
    values.differencePercent = display;

    valueString = cursor.getString(cursor.getColumnIndex(MatrixCursorColumns.DIFFERENCE));
    if (!TextUtils.isEmpty(valueString)) {
      value = MoneyFactory.fromString(valueString);
      display = format.getValueFormattedInBaseCurrency(value);
    } else {
      display = "";
    }
    values.difference = display;

    String typeString = cursor.getString(cursor.getColumnIndex(MatrixCursorColumns.TYPE));
    values.type = ItemType.valueOf(typeString);

    return values;
  }
  public void readFromParcel(Parcel source) {
    this.contentValues = ContentValues.CREATOR.createFromParcel(source);

    String value = source.readString();
    setValue(MoneyFactory.fromString(value));

    value = source.readString();
    setCurrentAllocation(MoneyFactory.fromString(value));

    setCurrentValue(MoneyFactory.fromString(source.readString()));
    setDifference(MoneyFactory.fromString(source.readString()));
    setType(ItemType.valueOf(source.readString()));
  }
  public static IntentDataParameters parseData(Context context, Uri data) {
    IntentDataParameters parameters = new IntentDataParameters();

    // transaction type
    String transactionTypeName = data.getQueryParameter(PARAM_TRANSACTION_TYPE);
    TransactionTypes type = TransactionTypes.valueOf(transactionTypeName);
    if (type != null) parameters.transactionType = type;

    // account
    String accountName = data.getQueryParameter(PARAM_ACCOUNT);
    if (accountName != null) {
      AccountRepository account = new AccountRepository(context);
      int accountId = account.loadIdByName(accountName);
      parameters.accountId = accountId;
    }

    parameters.payeeName = data.getQueryParameter(PARAM_PAYEE);
    if (parameters.payeeName != null) {
      PayeeService payee = new PayeeService(context);
      int payeeId = payee.loadIdByName(parameters.payeeName);
      parameters.payeeId = payeeId;
    }

    String amount = data.getQueryParameter(PARAM_AMOUNT);
    parameters.amount = MoneyFactory.fromString(amount);

    parameters.categoryName = data.getQueryParameter(PARAM_CATEGORY);
    if (parameters.categoryName != null) {
      CategoryService category = new CategoryService(context);
      int categoryId = category.loadIdByName(parameters.categoryName);
      parameters.categoryId = categoryId;
    }

    return parameters;
  }
  /**
   * The magic happens here. Calculate all dependent variables.
   *
   * @param totalPortfolioValue The total value of the portfolio, in base currency.
   */
  private void calculateStatsFor(AssetClass item, Money totalPortfolioValue) {
    Money zero = MoneyFactory.fromString("0");
    if (totalPortfolioValue.toDouble() == 0) {
      item.setValue(zero);
      item.setCurrentAllocation(zero);
      item.setCurrentValue(zero);
      item.setDifference(zero);
      return;
    }

    // Set Value
    Money allocation = item.getAllocation();
    // value = allocation * totalPortfolioValue / 100;
    Money value =
        totalPortfolioValue
            .multiply(allocation.toDouble())
            .divide(100, Constants.DEFAULT_PRECISION);
    item.setValue(value);

    // current value
    Money currentValue = sumStockValues(item.getStocks());
    item.setCurrentValue(currentValue);

    // Current allocation.
    Money currentAllocation =
        currentValue
            .multiply(100)
            .divide(totalPortfolioValue.toDouble(), Constants.DEFAULT_PRECISION);
    item.setCurrentAllocation(currentAllocation);

    // difference
    Money difference = currentValue.subtract(value);
    item.setDifference(difference);
  }
 private Money getDifferenceSum(List<AssetClass> group) {
   Money sum = MoneyFactory.fromDouble(0);
   for (AssetClass item : group) {
     sum.add(item.getDifference());
   }
   return sum;
 }
 private Money getCurrentAllocationSum(List<AssetClass> group) {
   Money sum = MoneyFactory.fromDouble(0);
   for (AssetClass item : group) {
     sum.add(item.getCurrentAllocation());
   }
   return sum;
 }
예제 #9
0
  protected Money getMoney(String fieldName) {
    //        Double d = contentValues.getAsDouble(fieldName);
    //        return MoneyFactory.fromDouble(d, Constants.DEFAULT_PRECISION);

    String value = contentValues.getAsString(fieldName);
    Money result = MoneyFactory.fromString(value).truncate(Constants.DEFAULT_PRECISION);
    return result;
  }
  public void showChart() {
    PayeeReportAdapter adapter = (PayeeReportAdapter) getListAdapter();
    if (adapter == null) return;
    Cursor cursor = adapter.getCursor();
    if (cursor == null) return;
    if (!cursor.moveToFirst()) return;

    ArrayList<ValuePieEntry> arrayList = new ArrayList<ValuePieEntry>();
    while (!cursor.isAfterLast()) {
      ValuePieEntry item = new ValuePieEntry();
      // total
      double total = Math.abs(cursor.getDouble(cursor.getColumnIndex("TOTAL")));
      if (!TextUtils.isEmpty(cursor.getString(cursor.getColumnIndex(ViewMobileData.PAYEE)))) {
        item.setText(cursor.getString(cursor.getColumnIndex(ViewMobileData.PAYEE)));
      } else {
        item.setText(getString(R.string.empty_payee));
      }
      item.setValue(total);
      CurrencyService currencyService = new CurrencyService(getContext());
      item.setValueFormatted(
          currencyService.getBaseCurrencyFormatted(MoneyFactory.fromDouble(total)));
      // add element
      arrayList.add(item);
      // move to next record
      cursor.moveToNext();
    }

    Bundle args = new Bundle();
    args.putSerializable(PieChartFragment.KEY_CATEGORIES_VALUES, arrayList);
    // get fragment manager
    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    if (fragmentManager != null) {
      PieChartFragment fragment;
      fragment =
          (PieChartFragment)
              fragmentManager.findFragmentByTag(
                  IncomeVsExpensesChartFragment.class.getSimpleName());
      if (fragment == null) {
        fragment = new PieChartFragment();
      }
      fragment.setChartArguments(args);
      fragment.setDisplayHomeAsUpEnabled(true);

      if (fragment.isVisible()) fragment.onResume();

      FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
      if (((PayeesReportActivity) getActivity()).mIsDualPanel) {
        fragmentTransaction.replace(
            R.id.fragmentChart, fragment, PieChartFragment.class.getSimpleName());
      } else {
        fragmentTransaction.replace(
            R.id.fragmentContent, fragment, PieChartFragment.class.getSimpleName());
        fragmentTransaction.addToBackStack(null);
      }
      fragmentTransaction.commit();
    }
  }
  private Money getAllocationSum(List<AssetClass> group) {
    List<Money> allocations = new ArrayList<>();
    for (AssetClass item : group) {
      allocations.add(item.getAllocation());
    }

    Money sum = MoneyFactory.fromString("0");
    for (Money allocation : allocations) {
      sum = sum.add(allocation);
    }
    return sum;
  }
  private Money sumStockValues(List<Stock> stocks) {
    Money sum = MoneyFactory.fromString("0");
    CurrencyService currencyService = new CurrencyService(getContext());
    AccountRepository repo = new AccountRepository(getContext());
    int baseCurrencyId = currencyService.getBaseCurrencyId();

    for (Stock stock : stocks) {
      // convert the stock value to the base currency.
      int accountId = stock.getHeldAt();
      int currencyId = repo.loadCurrencyIdFor(accountId);
      Money value =
          currencyService.doCurrencyExchange(baseCurrencyId, stock.getValue(), currencyId);

      sum = sum.add(value);
    }
    return sum;
  }
  @Override
  public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    super.onLoadFinished(loader, data);
    switch (loader.getId()) {
      case ID_LOADER:
        if (data == null) return;

        // parse cursor for calculate total
        double totalAmount = 0;
        while (data.moveToNext()) {
          totalAmount += data.getDouble(data.getColumnIndex("TOTAL"));
        }

        CurrencyService currencyService = new CurrencyService(getContext());

        TextView txtColumn2 = (TextView) mFooterListView.findViewById(R.id.textViewColumn2);
        txtColumn2.setText(
            currencyService.getBaseCurrencyFormatted(MoneyFactory.fromDouble(totalAmount)));

        // solve bug chart
        if (data.getCount() > 0) {
          getListView().removeFooterView(mFooterListView);
          getListView().addFooterView(mFooterListView);
        }
        // handler to show chart
        if (((PayeesReportActivity) getActivity()).mIsDualPanel) {
          Handler handler = new Handler();
          handler.postDelayed(
              new Runnable() {

                @Override
                public void run() {
                  showChart();
                }
              },
              1 * 1000);
        }
    }
  }
  @Override
  public void bindView(View view, Context context, Cursor cursor) {
    TextView txtColumn1 = (TextView) view.findViewById(R.id.textViewColumn1);
    TextView txtColumn2 = (TextView) view.findViewById(R.id.textViewColumn2);

    Core core = new Core(context);
    double total = cursor.getDouble(cursor.getColumnIndex("TOTAL"));
    String column1;
    String category = cursor.getString(cursor.getColumnIndex(ViewMobileData.Category));
    if (!TextUtils.isEmpty(category)) {
      column1 = "<b>" + category + "</b>";
      String subCategory = cursor.getString(cursor.getColumnIndex(ViewMobileData.Subcategory));
      if (!TextUtils.isEmpty(subCategory)) {
        column1 += " : " + subCategory;
      }
    } else {
      column1 = "<i>" + context.getString(R.string.empty_category);
    }
    txtColumn1.setText(Html.fromHtml(column1));

    CurrencyService currencyService = new CurrencyService(mContext);

    txtColumn2.setText(
        currencyService.getCurrencyFormatted(
            currencyService.getBaseCurrencyId(), MoneyFactory.fromDouble(total)));
    if (total < 0) {
      txtColumn2.setTextColor(
          context.getResources().getColor(core.resolveIdAttribute(R.attr.holo_red_color_theme)));
    } else {
      txtColumn2.setTextColor(
          context.getResources().getColor(core.resolveIdAttribute(R.attr.holo_green_color_theme)));
    }

    // view.setBackgroundColor(core.resolveColorAttribute(cursor.getPosition() % 2 == 1 ?
    // R.attr.row_dark_theme : R.attr.row_light_theme));
  }
 public static AssetClass create(String name) {
   AssetClass entity = new AssetClass();
   entity.setName(name);
   entity.setAllocation(MoneyFactory.fromString("0"));
   return entity;
 }