示例#1
0
  @Test
  public void bulkAddAccountsShouldNotModifyTransactions() {
    Account account1 = new Account("AlphaAccount");
    Account account2 = new Account("BetaAccount");
    Transaction transaction = new Transaction("MyTransaction");
    Split split = new Split(Money.getZeroInstance(), account1.getUID());
    transaction.addSplit(split);
    transaction.addSplit(split.createPair(account2.getUID()));
    account1.addTransaction(transaction);
    account2.addTransaction(transaction);

    List<Account> accounts = new ArrayList<>();
    accounts.add(account1);
    accounts.add(account2);

    mAccountsDbAdapter.bulkAddRecords(accounts);

    SplitsDbAdapter splitsDbAdapter = SplitsDbAdapter.getInstance();
    assertThat(
            splitsDbAdapter.getSplitsForTransactionInAccount(
                transaction.getUID(), account1.getUID()))
        .hasSize(1);
    assertThat(
            splitsDbAdapter.getSplitsForTransactionInAccount(
                transaction.getUID(), account2.getUID()))
        .hasSize(1);

    assertThat(mAccountsDbAdapter.getRecord(account1.getUID()).getTransactions()).hasSize(1);
  }
示例#2
0
  @Test
  public void shouldAddAccountsToDatabase() {
    Account account1 = new Account("AlphaAccount");
    Account account2 = new Account("BetaAccount");
    Transaction transaction = new Transaction("MyTransaction");
    Split split = new Split(Money.getZeroInstance(), account1.getUID());
    transaction.addSplit(split);
    transaction.addSplit(split.createPair(account2.getUID()));
    account1.addTransaction(transaction);
    account2.addTransaction(transaction);

    mAccountsDbAdapter.addRecord(account1);
    mAccountsDbAdapter.addRecord(account2);

    Account firstAccount = mAccountsDbAdapter.getRecord(account1.getUID());
    assertThat(firstAccount).isNotNull();
    assertThat(firstAccount.getUID()).isEqualTo(account1.getUID());
    assertThat(firstAccount.getFullName()).isEqualTo(account1.getFullName());

    Account secondAccount = mAccountsDbAdapter.getRecord(account2.getUID());
    assertThat(secondAccount).isNotNull();
    assertThat(secondAccount.getUID()).isEqualTo(account2.getUID());

    assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1);
  }
示例#3
0
  /**
   * Builds a QIF entry representing this transaction
   *
   * @return String QIF representation of this transaction
   */
  public String toQIF() {
    final String newLine = "\n";

    AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(GnuCashApplication.getAppContext());

    // all transactions are double transactions
    String splitAccountFullName = QifHelper.getImbalanceAccountName(mAmount.getCurrency());
    if (mDoubleEntryAccountUID != null && mDoubleEntryAccountUID.length() > 0) {
      splitAccountFullName = accountsDbAdapter.getFullyQualifiedAccountName(mDoubleEntryAccountUID);
    }

    StringBuffer transactionQifBuffer = new StringBuffer();
    transactionQifBuffer
        .append(QifHelper.DATE_PREFIX)
        .append(QifHelper.formatDate(mTimestamp))
        .append(newLine);
    transactionQifBuffer.append(QifHelper.MEMO_PREFIX).append(mName).append(newLine);

    transactionQifBuffer
        .append(QifHelper.SPLIT_CATEGORY_PREFIX)
        .append(splitAccountFullName)
        .append(newLine);
    if (mDescription != null && mDescription.length() > 0) {
      transactionQifBuffer.append(QifHelper.SPLIT_MEMO_PREFIX).append(mDescription).append(newLine);
    }
    transactionQifBuffer
        .append(QifHelper.SPLIT_AMOUNT_PREFIX)
        .append(mAmount.asString())
        .append(newLine);
    transactionQifBuffer.append(QifHelper.ENTRY_TERMINATOR).append(newLine);

    accountsDbAdapter.close();
    return transactionQifBuffer.toString();
  }
示例#4
0
  @Test
  public void shouldClearAllTablesWhenDeletingAllAccounts() {
    Account account = new Account("Test");
    Transaction transaction = new Transaction("Test description");
    Split split = new Split(Money.getZeroInstance(), account.getUID());
    transaction.addSplit(split);
    Account account2 = new Account("Transfer account");
    transaction.addSplit(split.createPair(account2.getUID()));

    mAccountsDbAdapter.addRecord(account);
    mAccountsDbAdapter.addRecord(account2);

    ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP);
    scheduledAction.setActionUID("Test-uid");
    ScheduledActionDbAdapter scheduledActionDbAdapter = ScheduledActionDbAdapter.getInstance();

    scheduledActionDbAdapter.addRecord(scheduledAction);

    mAccountsDbAdapter.deleteAllRecords();

    assertThat(mAccountsDbAdapter.getRecordsCount()).isZero();
    assertThat(mTransactionsDbAdapter.getRecordsCount()).isZero();
    assertThat(mSplitsDbAdapter.getRecordsCount()).isZero();
    assertThat(scheduledActionDbAdapter.getRecordsCount()).isZero();
  }
示例#5
0
  /**
   * Converts transaction to XML DOM corresponding to OFX Statement transaction and returns the
   * element node for the transaction. The Unique ID of the account is needed in order to properly
   * export double entry transactions
   *
   * @param doc XML document to which transaction should be added
   * @param accountUID Unique Identifier of the account which called the method.
   * @return Element in DOM corresponding to transaction
   */
  public Element toOfx(Document doc, String accountUID) {
    Element transactionNode = doc.createElement("STMTTRN");
    Element type = doc.createElement("TRNTYPE");
    type.appendChild(doc.createTextNode(mType.toString()));
    transactionNode.appendChild(type);

    Element datePosted = doc.createElement("DTPOSTED");
    datePosted.appendChild(doc.createTextNode(OfxExporter.getOfxFormattedTime(mTimestamp)));
    transactionNode.appendChild(datePosted);

    Element dateUser = doc.createElement("DTUSER");
    dateUser.appendChild(doc.createTextNode(OfxExporter.getOfxFormattedTime(mTimestamp)));
    transactionNode.appendChild(dateUser);

    Element amount = doc.createElement("TRNAMT");
    amount.appendChild(doc.createTextNode(mAmount.toPlainString()));
    transactionNode.appendChild(amount);

    Element transID = doc.createElement("FITID");
    transID.appendChild(doc.createTextNode(mTransactionUID));
    transactionNode.appendChild(transID);

    Element name = doc.createElement("NAME");
    name.appendChild(doc.createTextNode(mName));
    transactionNode.appendChild(name);

    if (mDescription != null && mDescription.length() > 0) {
      Element memo = doc.createElement("MEMO");
      memo.appendChild(doc.createTextNode(mDescription));
      transactionNode.appendChild(memo);
    }

    if (mDoubleEntryAccountUID != null && mDoubleEntryAccountUID.length() > 0) {
      Element bankId = doc.createElement("BANKID");
      bankId.appendChild(doc.createTextNode(OfxExporter.APP_ID));

      // select the proper account as the double account
      String doubleAccountUID =
          mDoubleEntryAccountUID.equals(accountUID) ? mAccountUID : mDoubleEntryAccountUID;

      Element acctId = doc.createElement("ACCTID");
      acctId.appendChild(doc.createTextNode(doubleAccountUID));

      Element accttype = doc.createElement("ACCTTYPE");
      AccountsDbAdapter acctDbAdapter = new AccountsDbAdapter(GnuCashApplication.getAppContext());
      OfxAccountType ofxAccountType =
          Account.convertToOfxAccountType(acctDbAdapter.getAccountType(doubleAccountUID));
      accttype.appendChild(doc.createTextNode(ofxAccountType.toString()));
      acctDbAdapter.close();

      Element bankAccountTo = doc.createElement("BANKACCTTO");
      bankAccountTo.appendChild(bankId);
      bankAccountTo.appendChild(acctId);
      bankAccountTo.appendChild(accttype);

      transactionNode.appendChild(bankAccountTo);
    }

    return transactionNode;
  }
示例#6
0
  @Test
  public void shouldGetDescendantAccounts() {
    loadDefaultAccounts();

    String uid = mAccountsDbAdapter.findAccountUidByFullName("Expenses:Auto");
    List<String> descendants = mAccountsDbAdapter.getDescendantAccountUIDs(uid, null, null);

    assertThat(descendants).hasSize(4);
  }
示例#7
0
  /** Test creating an account hierarchy by specifying fully qualified name */
  @Test
  public void shouldCreateAccountHierarchy() {
    String uid =
        mAccountsDbAdapter.createAccountHierarchy(
            "Assets:Current Assets:Cash in Wallet", AccountType.ASSET);

    List<Account> accounts = mAccountsDbAdapter.getAllRecords();
    assertThat(accounts).hasSize(3);
    assertThat(accounts).extracting("mUID").contains(uid);
  }
示例#8
0
  /** Tests that a ROOT account will always be created in the system */
  @Test
  public void shouldCreateDefaultRootAccount() {
    Account account = new Account("Some account");
    mAccountsDbAdapter.addRecord(account);
    assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(2L);

    List<Account> accounts = mAccountsDbAdapter.getSimpleAccountList();
    assertThat(accounts).extracting("mAccountType").contains(AccountType.ROOT);

    String rootAccountUID = mAccountsDbAdapter.getOrCreateGnuCashRootAccountUID();
    assertThat(rootAccountUID).isEqualTo(accounts.get(1).getParentUID());
  }
示例#9
0
  @Test
  public void shouldCreateImbalanceAccountOnDemand() {
    assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(0);

    Currency usd = Currency.getInstance("USD");
    String imbalanceUID = mAccountsDbAdapter.getImbalanceAccountUID(usd);
    assertThat(imbalanceUID).isNull();
    assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(0);

    imbalanceUID = mAccountsDbAdapter.getOrCreateImbalanceAccountUID(usd);
    assertThat(imbalanceUID).isNotNull().isNotEmpty();
    assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(2);
  }
示例#10
0
  /** Test that the list of accounts is always returned sorted alphabetically */
  @Test
  public void shouldBeAlphabeticallySortedByDefault() {
    Account first = new Account(ALPHA_ACCOUNT_NAME);
    Account second = new Account(BRAVO_ACCOUNT_NAME);
    // purposefully added the second after the first
    mAccountsDbAdapter.addRecord(second);
    mAccountsDbAdapter.addRecord(first);

    List<Account> accountsList = mAccountsDbAdapter.getAllRecords();
    assertEquals(2, accountsList.size());
    // bravo was saved first, but alpha should be first alphabetically
    assertThat(accountsList).contains(first, Index.atIndex(0));
    assertThat(accountsList).contains(second, Index.atIndex(1));
  }
  @Before
  public void setUp() throws Exception {
    mSplitsDbAdapter = SplitsDbAdapter.getInstance();
    mTransactionsDbAdapter = TransactionsDbAdapter.getInstance();
    mAccountsDbAdapter = AccountsDbAdapter.getInstance();

    alphaAccount = new Account(ALPHA_ACCOUNT_NAME);
    bravoAccount = new Account(BRAVO_ACCOUNT_NAME);

    mAccountsDbAdapter.addRecord(bravoAccount);
    mAccountsDbAdapter.addRecord(alphaAccount);

    mTestSplit = new Split(new Money(BigDecimal.TEN, DEFAULT_CURRENCY), alphaAccount.getUID());
  }
示例#12
0
  private void init(@Nullable SQLiteDatabase db) {
    if (db == null) {
      mAccountsDbAdapter = AccountsDbAdapter.getInstance();
      mTransactionsDbAdapter = TransactionsDbAdapter.getInstance();
      mScheduledActionsDbAdapter = ScheduledActionDbAdapter.getInstance();
      mCommoditiesDbAdapter = CommoditiesDbAdapter.getInstance();
      mPricesDbAdapter = PricesDbAdapter.getInstance();
    } else {
      mTransactionsDbAdapter = new TransactionsDbAdapter(db, new SplitsDbAdapter(db));
      mAccountsDbAdapter = new AccountsDbAdapter(db, mTransactionsDbAdapter);
      mScheduledActionsDbAdapter = new ScheduledActionDbAdapter(db);
      mCommoditiesDbAdapter = new CommoditiesDbAdapter(db);
      mPricesDbAdapter = new PricesDbAdapter(db);
    }

    mContent = new StringBuilder();

    mAccountList = new ArrayList<>();
    mAccountMap = new HashMap<>();
    mTransactionList = new ArrayList<>();
    mScheduledActionsList = new ArrayList<>();

    mTemplatAccountList = new ArrayList<>();
    mTemplateTransactions = new ArrayList<>();
    mTemplateAccountToTransactionMap = new HashMap<>();

    mAutoBalanceSplits = new ArrayList<>();

    mPriceList = new ArrayList<>();
  }
示例#13
0
  @Before
  public void setUp() throws Exception {

    mSplitsDbAdapter = SplitsDbAdapter.getInstance();
    mTransactionsDbAdapter = TransactionsDbAdapter.getInstance();
    mAccountsDbAdapter = AccountsDbAdapter.getInstance();
  }
示例#14
0
  @Test
  public void simpleAccountListShouldNotContainTransactions() {
    Account account = new Account("Test");
    Transaction transaction = new Transaction("Test description");
    Split split = new Split(Money.getZeroInstance(), account.getUID());
    transaction.addSplit(split);
    Account account1 = new Account("Transfer");
    transaction.addSplit(split.createPair(account1.getUID()));

    mAccountsDbAdapter.addRecord(account);
    mAccountsDbAdapter.addRecord(account1);

    List<Account> accounts = mAccountsDbAdapter.getSimpleAccountList();
    for (Account testAcct : accounts) {
      assertThat(testAcct.getTransactionCount()).isZero();
    }
  }
示例#15
0
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
    assert actionBar != null;
    actionBar.setTitle(R.string.title_split_editor);
    setHasOptionsMenu(true);

    mCalculatorKeyboard =
        new CalculatorKeyboard(getActivity(), mKeyboardView, R.xml.calculator_keyboard);
    mSplitItemViewList = new ArrayList<>();

    // we are editing splits for a new transaction.
    // But the user may have already created some splits before. Let's check
    List<String> splitStrings = getArguments().getStringArrayList(UxArgument.SPLIT_LIST);
    List<Split> splitList = new ArrayList<>();
    if (splitStrings != null) {
      for (String splitString : splitStrings) {
        splitList.add(Split.parseSplit(splitString));
      }
    }

    initArgs();
    if (!splitList.isEmpty()) {
      // aha! there are some splits. Let's load those instead
      loadSplitViews(splitList);
      mImbalanceWatcher.afterTextChanged(null);
    } else {
      final String currencyCode = mAccountsDbAdapter.getAccountCurrencyCode(mAccountUID);
      Split split =
          new Split(new Money(mBaseAmount.abs(), Commodity.getInstance(currencyCode)), mAccountUID);
      AccountType accountType = mAccountsDbAdapter.getAccountType(mAccountUID);
      TransactionType transactionType =
          Transaction.getTypeForBalance(accountType, mBaseAmount.signum() < 0);
      split.setType(transactionType);
      View view = addSplitView(split);
      view.findViewById(R.id.input_accounts_spinner).setEnabled(false);
      view.findViewById(R.id.btn_remove_split).setVisibility(View.GONE);
      TransactionsActivity.displayBalance(
          mImbalanceTextView, new Money(mBaseAmount.negate(), mCommodity));
    }
  }
示例#16
0
  @Test
  public void shouldAddTransactionsAndSplitsWhenAddingAccounts() {
    Account account = new Account("Test");
    mAccountsDbAdapter.addRecord(account);

    Transaction transaction = new Transaction("Test description");
    Split split = new Split(Money.getZeroInstance(), account.getUID());
    transaction.addSplit(split);
    Account account1 = new Account("Transfer account");
    transaction.addSplit(split.createPair(account1.getUID()));
    account1.addTransaction(transaction);

    mAccountsDbAdapter.addRecord(account1);

    assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1);
    assertThat(mSplitsDbAdapter.getRecordsCount()).isEqualTo(2);
    assertThat(mAccountsDbAdapter.getRecordsCount())
        .isEqualTo(3); // ROOT account automatically added
  }
  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
    mFavoriteAccountMenu = menu.findItem(R.id.menu_favorite_account);
    MenuItem favoriteAccountMenuItem = menu.findItem(R.id.menu_favorite_account);

    if (favoriteAccountMenuItem == null) // when the activity is used to edit a transaction
    return super.onPrepareOptionsMenu(menu);

    AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(this);
    boolean isFavoriteAccount = accountsDbAdapter.isFavoriteAccount(mAccountId);
    accountsDbAdapter.close();

    int favoriteIcon =
        isFavoriteAccount
            ? android.R.drawable.btn_star_big_on
            : android.R.drawable.btn_star_big_off;
    favoriteAccountMenuItem.setIcon(favoriteIcon);
    return super.onPrepareOptionsMenu(menu);
  }
示例#18
0
  /** Extracts arguments passed to the view and initializes necessary adapters and cursors */
  private void initArgs() {
    mAccountsDbAdapter = AccountsDbAdapter.getInstance();

    Bundle args = getArguments();
    mAccountUID = ((FormActivity) getActivity()).getCurrentAccountUID();
    mBaseAmount = new BigDecimal(args.getString(UxArgument.AMOUNT_STRING));

    String conditions =
        "("
            + DatabaseSchema.AccountEntry.COLUMN_HIDDEN
            + " = 0 AND "
            + DatabaseSchema.AccountEntry.COLUMN_PLACEHOLDER
            + " = 0"
            + ")";
    mCursor = mAccountsDbAdapter.fetchAccountsOrderedByFullName(conditions, null);
    mCommodity =
        CommoditiesDbAdapter.getInstance()
            .getCommodity(mAccountsDbAdapter.getCurrencyCode(mAccountUID));
  }
示例#19
0
  @Test
  public void shouldComputeAccountBalanceCorrectly() {
    Account account = new Account("Test", Commodity.USD);
    account.setAccountType(AccountType.ASSET); // debit normal account balance
    Account transferAcct = new Account("Transfer");

    mAccountsDbAdapter.addRecord(account);
    mAccountsDbAdapter.addRecord(transferAcct);

    Transaction transaction = new Transaction("Test description");
    mTransactionsDbAdapter.addRecord(transaction);
    Split split = new Split(new Money(BigDecimal.TEN, Commodity.USD), account.getUID());
    split.setTransactionUID(transaction.getUID());
    split.setType(TransactionType.DEBIT);
    mSplitsDbAdapter.addRecord(split);

    split = new Split(new Money("4.99", "USD"), account.getUID());
    split.setTransactionUID(transaction.getUID());
    split.setType(TransactionType.DEBIT);
    mSplitsDbAdapter.addRecord(split);

    split = new Split(new Money("1.19", "USD"), account.getUID());
    split.setTransactionUID(transaction.getUID());
    split.setType(TransactionType.CREDIT);
    mSplitsDbAdapter.addRecord(split);

    split = new Split(new Money("3.49", "EUR"), account.getUID());
    split.setTransactionUID(transaction.getUID());
    split.setType(TransactionType.DEBIT);
    mSplitsDbAdapter.addRecord(split);

    split = new Split(new Money("8.39", "USD"), transferAcct.getUID());
    split.setTransactionUID(transaction.getUID());
    mSplitsDbAdapter.addRecord(split);

    // balance computation ignores the currency of the split
    Money balance = mAccountsDbAdapter.getAccountBalance(account.getUID());
    Money expectedBalance = new Money("17.29", "USD"); // EUR splits should be ignored

    assertThat(balance).isEqualTo(expectedBalance);
  }
示例#20
0
  /**
   * Extracts the input from the views and builds {@link org.gnucash.android.model.Split}s to
   * correspond to the input.
   *
   * @return List of {@link org.gnucash.android.model.Split}s represented in the view
   */
  private List<Split> extractSplitsFromView() {
    List<Split> splitList = new ArrayList<>();
    for (View splitView : mSplitItemViewList) {
      SplitViewHolder viewHolder = (SplitViewHolder) splitView.getTag();
      if (viewHolder.splitAmountEditText.getValue() == null) continue;

      BigDecimal amountBigDecimal = viewHolder.splitAmountEditText.getValue();

      String currencyCode = mAccountsDbAdapter.getCurrencyCode(mAccountUID);
      Money valueAmount = new Money(amountBigDecimal.abs(), Commodity.getInstance(currencyCode));

      String accountUID = mAccountsDbAdapter.getUID(viewHolder.accountsSpinner.getSelectedItemId());
      Split split = new Split(valueAmount, accountUID);
      split.setMemo(viewHolder.splitMemoEditText.getText().toString());
      split.setType(viewHolder.splitTypeSwitch.getTransactionType());
      split.setUID(viewHolder.splitUidTextView.getText().toString().trim());
      if (viewHolder.quantity != null) split.setQuantity(viewHolder.quantity.absolute());
      splitList.add(split);
    }
    return splitList;
  }
示例#21
0
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.i("Gnucash", "Received account creation intent");
    Bundle args = intent.getExtras();

    String uid = args.getString(Intent.EXTRA_UID);

    Account account = new Account(args.getString(Intent.EXTRA_TITLE));
    String currencyCode = args.getString(Account.EXTRA_CURRENCY_CODE);

    if (currencyCode != null) {
      Currency currency = Currency.getInstance(currencyCode);
      account.setCurrency(currency);
    }

    if (uid != null) account.setUID(uid);

    AccountsDbAdapter accountsAdapter = new AccountsDbAdapter(context);
    accountsAdapter.addAccount(account);
    accountsAdapter.close();
  }
示例#22
0
  @Test
  public void shouldRecursivelyDeleteAccount() {
    Account account = new Account("Parent");
    Account account2 = new Account("Child");
    account2.setParentUID(account.getUID());

    Transaction transaction = new Transaction("Random");
    account2.addTransaction(transaction);

    Split split = new Split(Money.getZeroInstance(), account.getUID());
    transaction.addSplit(split);
    transaction.addSplit(split.createPair(account2.getUID()));

    mAccountsDbAdapter.addRecord(account);
    mAccountsDbAdapter.addRecord(account2);

    assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(3);
    assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1);
    assertThat(mSplitsDbAdapter.getRecordsCount()).isEqualTo(2);

    boolean result =
        mAccountsDbAdapter.recursiveDeleteAccount(mAccountsDbAdapter.getID(account.getUID()));
    assertThat(result).isTrue();

    assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(1); // the root account
    assertThat(mTransactionsDbAdapter.getRecordsCount()).isZero();
    assertThat(mSplitsDbAdapter.getRecordsCount()).isZero();
  }
  /** Sets the color for the ViewPager title indicator to match the account color */
  private void setTitleIndicatorColor() {
    // Basically, if we are in a top level account, use the default title color.
    // but propagate a parent account's title color to children who don't have own color
    String colorCode = mAccountsDbAdapter.getAccountColorCode(mAccountId);
    if (colorCode != null) {
      sLastTitleColor = Color.parseColor(colorCode);
    }

    mTitlePageIndicator.setSelectedColor(sLastTitleColor);
    mTitlePageIndicator.setTextColor(sLastTitleColor);
    mTitlePageIndicator.setFooterColor(sLastTitleColor);
    mSectionHeaderTransactions.setBackgroundColor(sLastTitleColor);
  }
 /**
  * Updates the action bar navigation list selection to that of the current account whose
  * transactions are being displayed/manipulated
  */
 public void updateNavigationSelection() {
   // set the selected item in the spinner
   int i = 0;
   Cursor accountsCursor = mAccountsDbAdapter.fetchAllRecordsOrderedByFullName();
   while (accountsCursor.moveToNext()) {
     long id = accountsCursor.getLong(DatabaseAdapter.COLUMN_ROW_ID);
     if (mAccountId == id) {
       getSupportActionBar().setSelectedNavigationItem(i);
       break;
     }
     ++i;
   }
   accountsCursor.close();
 }
示例#25
0
  /** Tests the foreign key constraint "ON DELETE CASCADE" between accounts and splits */
  @Test
  public void shouldDeleteSplitsWhenAccountDeleted() {
    Account first = new Account(ALPHA_ACCOUNT_NAME);
    first.setUID(ALPHA_ACCOUNT_NAME);
    Account second = new Account(BRAVO_ACCOUNT_NAME);
    second.setUID(BRAVO_ACCOUNT_NAME);

    mAccountsDbAdapter.addRecord(second);
    mAccountsDbAdapter.addRecord(first);

    Transaction transaction = new Transaction("TestTrn");
    Split split = new Split(Money.getZeroInstance(), ALPHA_ACCOUNT_NAME);
    transaction.addSplit(split);
    transaction.addSplit(split.createPair(BRAVO_ACCOUNT_NAME));

    mTransactionsDbAdapter.addRecord(transaction);

    mAccountsDbAdapter.deleteRecord(ALPHA_ACCOUNT_NAME);

    Transaction trxn = mTransactionsDbAdapter.getRecord(transaction.getUID());
    assertThat(trxn.getSplits().size()).isEqualTo(1);
    assertThat(trxn.getSplits().get(0).getAccountUID()).isEqualTo(BRAVO_ACCOUNT_NAME);
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        InputMethodManager imm =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(findViewById(android.R.id.content).getWindowToken(), 0);
        FragmentManager fm = getSupportFragmentManager();
        if (fm.getBackStackEntryCount() > 0) {
          fm.popBackStack();
        } else {
          AccountsActivity.start(this);
          finish();
        }
        return true;

      case R.id.menu_favorite_account:
        AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(this);
        boolean isFavorite = accountsDbAdapter.isFavoriteAccount(mAccountId);
        // toggle favorite preference
        accountsDbAdapter.updateAccount(
            mAccountId, DatabaseHelper.KEY_FAVORITE, isFavorite ? "0" : "1");
        accountsDbAdapter.close();
        supportInvalidateOptionsMenu();
        return true;

      case R.id.menu_edit_account:
        Intent editAccountIntent = new Intent(this, AccountsActivity.class);
        editAccountIntent.setAction(Intent.ACTION_INSERT_OR_EDIT);
        editAccountIntent.putExtra(UxArgument.SELECTED_ACCOUNT_ID, mAccountId);
        startActivityForResult(editAccountIntent, AccountsActivity.REQUEST_EDIT_ACCOUNT);
        return true;

      default:
        return false;
    }
  }
  /** Set up action bar navigation list and listener callbacks */
  private void setupActionBarNavigation() {
    // set up spinner adapter for navigation list
    Cursor accountsCursor = mAccountsDbAdapter.fetchAllRecordsOrderedByFullName();

    SpinnerAdapter mSpinnerAdapter =
        new QualifiedAccountNameCursorAdapter(
            getSupportActionBar().getThemedContext(),
            R.layout.sherlock_spinner_item,
            accountsCursor);
    ((ResourceCursorAdapter) mSpinnerAdapter)
        .setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    actionBar.setListNavigationCallbacks(mSpinnerAdapter, mTransactionListNavigationListener);
    actionBar.setDisplayHomeAsUpEnabled(true);

    updateNavigationSelection();
  }
示例#28
0
  @Test
  public void shouldReassignDescendantAccounts() {
    loadDefaultAccounts();

    String savingsAcctUID =
        mAccountsDbAdapter.findAccountUidByFullName("Assets:Current Assets:Savings Account");

    String currentAssetsUID = mAccountsDbAdapter.findAccountUidByFullName("Assets:Current Assets");
    String assetsUID = mAccountsDbAdapter.findAccountUidByFullName("Assets");

    assertThat(mAccountsDbAdapter.getParentAccountUID(savingsAcctUID)).isEqualTo(currentAssetsUID);
    mAccountsDbAdapter.reassignDescendantAccounts(currentAssetsUID, assetsUID);
    assertThat(mAccountsDbAdapter.getParentAccountUID(savingsAcctUID)).isEqualTo(assetsUID);

    assertThat(mAccountsDbAdapter.getFullyQualifiedAccountName(savingsAcctUID))
        .isEqualTo("Assets:Savings Account");
  }
  @Test
  public void shouldBalanceTransactionsOnSave() {
    Transaction transaction = new Transaction("Auto balance");
    Split split =
        new Split(
            new Money(BigDecimal.TEN, Currency.getInstance(Money.DEFAULT_CURRENCY_CODE)),
            alphaAccount.getUID());

    transaction.addSplit(split);

    mTransactionsDbAdapter.addRecord(transaction);

    Transaction trn = mTransactionsDbAdapter.getRecord(transaction.getUID());
    assertThat(trn.getSplits()).hasSize(2);

    String imbalanceAccountUID =
        mAccountsDbAdapter.getImbalanceAccountUID(
            Currency.getInstance(Money.DEFAULT_CURRENCY_CODE));
    assertThat(trn.getSplits()).extracting("mAccountUID").contains(imbalanceAccountUID);
  }
示例#30
0
  /**
   * Opening an XML file should set the default currency to that used by the most accounts in the
   * file
   */
  @Test
  public void importingXml_shouldSetDefaultCurrency() {
    GnuCashApplication.setDefaultCurrencyCode("JPY");

    assertThat(GnuCashApplication.getDefaultCurrencyCode()).isEqualTo("JPY");
    assertThat(Commodity.DEFAULT_COMMODITY).isEqualTo(Commodity.JPY);

    mAccountsDbAdapter.deleteAllRecords();
    loadDefaultAccounts();

    assertThat(GnuCashApplication.getDefaultCurrencyCode()).isNotEqualTo("JPY");

    Currency currency = Currency.getInstance(GnuCashApplication.getDefaultLocale());
    String expectedCode = currency.getCurrencyCode();
    Commodity expectedDefaultCommodity =
        CommoditiesDbAdapter.getInstance().getCommodity(expectedCode);

    assertThat(GnuCashApplication.getDefaultCurrencyCode()).isEqualTo(expectedCode);
    assertThat(Commodity.DEFAULT_COMMODITY).isEqualTo(expectedDefaultCommodity);

    System.out.println("Default currency is now: " + expectedCode);
  }